You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ranger.apache.org by ab...@apache.org on 2018/10/18 22:23:21 UTC

[1/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Repository: ranger
Updated Branches:
  refs/heads/master 64cb80b71 -> d424b1a8d


http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java
index 8f19ffd..5032c12 100644
--- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java
+++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagDefService.java
@@ -22,7 +22,6 @@ import java.util.List;
 
 import org.apache.ranger.db.RangerDaoManager;
 import org.apache.ranger.db.XXServiceVersionInfoDao;
-import org.apache.ranger.db.XXTagAttributeDefDao;
 import org.apache.ranger.db.XXTagDefDao;
 import org.apache.ranger.entity.XXTagAttributeDef;
 import org.apache.ranger.entity.XXTagDef;
@@ -35,7 +34,7 @@ import org.junit.runners.MethodSorters;
 import org.mockito.InjectMocks;
 import org.mockito.Mock;
 import org.mockito.Mockito;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.mockito.runners.MockitoJUnitRunner;
 
 @RunWith(MockitoJUnitRunner.class)
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
@@ -81,21 +80,15 @@ public class TestRangerTagDefService {
 		xxTagAttributeDef.setName(name);
 		tagAttrDefList.add(xxTagAttributeDef);
 		
-		XXTagAttributeDefDao xxTagAttributeDefDao = Mockito.mock(XXTagAttributeDefDao.class);
 		XXServiceVersionInfoDao xxServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class);
-		
-		Mockito.when(daoMgr.getXXTagAttributeDef()).thenReturn(xxTagAttributeDefDao);
-		Mockito.when(xxTagAttributeDefDao.findByTagDefId(tagDef.getId())).thenReturn(tagAttrDefList);
-		
+
 		Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xxServiceVersionInfoDao);
 		Mockito.doNothing().when(xxServiceVersionInfoDao).updateServiceVersionInfoForTagDefUpdate(tagDef.getId(), tagDef.getUpdateTime());
 		
 		RangerTagDef result = rangerTagDefService.postUpdate(tagDef);
 		Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId());
 		Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName());
-		
-		Mockito.verify(daoMgr).getXXTagAttributeDef();
-		Mockito.verify(xxTagAttributeDefDao).findByTagDefId(tagDef.getId());
+
 		Mockito.verify(daoMgr).getXXServiceVersionInfo();
 		Mockito.verify(xxServiceVersionInfoDao).updateServiceVersionInfoForTagDefUpdate(tagDef.getId(), tagDef.getUpdateTime());
 	}
@@ -117,19 +110,12 @@ public class TestRangerTagDefService {
 		xxTagAttributeDef.setName(name);
 		tagAttrDefList.add(xxTagAttributeDef);
 		
-		XXTagAttributeDefDao xxTagAttributeDefDao = Mockito.mock(XXTagAttributeDefDao.class);
-		
-		Mockito.when(daoMgr.getXXTagAttributeDef()).thenReturn(xxTagAttributeDefDao);
-		Mockito.when(xxTagAttributeDefDao.findByTagDefId(xxTagDef.getId())).thenReturn(tagAttrDefList);
-		
 		RangerTagDef result = rangerTagDefService.getTagDefByGuid(guid);
 		Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId());
 		Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName());
 		
 		Mockito.verify(daoMgr).getXXTagDef();
 		Mockito.verify(xXTagDefDao).findByGuid(guid);
-		Mockito.verify(daoMgr).getXXTagAttributeDef();
-		Mockito.verify(xxTagAttributeDefDao).findByTagDefId(xxTagDef.getId());
 	}
 	
 	@Test
@@ -167,19 +153,12 @@ public class TestRangerTagDefService {
 		xxTagAttributeDef.setName(name);
 		tagAttrDefList.add(xxTagAttributeDef);
 		
-		XXTagAttributeDefDao xxTagAttributeDefDao = Mockito.mock(XXTagAttributeDefDao.class);
-		
-		Mockito.when(daoMgr.getXXTagAttributeDef()).thenReturn(xxTagAttributeDefDao);
-		Mockito.when(xxTagAttributeDefDao.findByTagDefId(xxTagDef.getId())).thenReturn(tagAttrDefList);
-		
 		RangerTagDef result = rangerTagDefService.getTagDefByName(name);
 		Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId());
 		Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName());
 		
 		Mockito.verify(daoMgr).getXXTagDef();
 		Mockito.verify(xXTagDefDao).findByName(name);
-		Mockito.verify(daoMgr).getXXTagAttributeDef();
-		Mockito.verify(xxTagAttributeDefDao).findByTagDefId(xxTagDef.getId());
 	}
 	
 	@Test
@@ -215,19 +194,12 @@ public class TestRangerTagDefService {
 		xxTagAttributeDef.setName(name);
 		tagAttrDefList.add(xxTagAttributeDef);
 		
-		XXTagAttributeDefDao xxTagAttributeDefDao = Mockito.mock(XXTagAttributeDefDao.class);
-		
-		Mockito.when(daoMgr.getXXTagAttributeDef()).thenReturn(xxTagAttributeDefDao);
-		Mockito.when(xxTagAttributeDefDao.findByTagDefId(xxTagDef.getId())).thenReturn(tagAttrDefList);
-		
 		List<RangerTagDef> result = rangerTagDefService.getTagDefsByServiceId(serviceId);
 		Assert.assertEquals(result.get(0).getId(), tagAttrDefList.get(0).getId());
 		Assert.assertEquals(result.get(0).getName(), tagAttrDefList.get(0).getName());
 		
 		Mockito.verify(daoMgr).getXXTagDef();
 		Mockito.verify(xXTagDefDao).findByServiceId(serviceId);
-		Mockito.verify(daoMgr).getXXTagAttributeDef();
-		Mockito.verify(xxTagAttributeDefDao).findByTagDefId(xxTagDef.getId());
 	}
 	
 	
@@ -259,16 +231,8 @@ public class TestRangerTagDefService {
 		xxTagAttributeDef.setName(name);
 		tagAttrDefList.add(xxTagAttributeDef);
 		
-		XXTagAttributeDefDao xxTagAttributeDefDao = Mockito.mock(XXTagAttributeDefDao.class);
-		
-		Mockito.when(daoMgr.getXXTagAttributeDef()).thenReturn(xxTagAttributeDefDao);
-		Mockito.when(xxTagAttributeDefDao.findByTagDefId(xxTagDef.getId())).thenReturn(tagAttrDefList);
-		
 		RangerTagDef result = rangerTagDefService.getPopulatedViewObject(xxTagDef);
 		Assert.assertEquals(result.getId(), tagAttrDefList.get(0).getId());
 		Assert.assertEquals(result.getName(), tagAttrDefList.get(0).getName());
-		
-		Mockito.verify(daoMgr).getXXTagAttributeDef();
-		Mockito.verify(xxTagAttributeDefDao).findByTagDefId(xxTagDef.getId());
 	}
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java
index 1175989..af80ed1 100644
--- a/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java
+++ b/security-admin/src/test/java/org/apache/ranger/service/TestRangerTagService.java
@@ -18,6 +18,8 @@
  */
 package org.apache.ranger.service;
 
+import org.apache.ranger.db.XXServiceResourceDao;
+import org.apache.ranger.entity.XXServiceResource;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -69,11 +71,16 @@ public class TestRangerTagService {
         @Mock
         XXTagDao xXTagDao;
 
+        @Mock
+    XXServiceResourceDao xxServiceResourceDao;
+
+        @Mock
+        XXServiceResource xxServiceResource;
+
         @Test
         public void test1postUpdate() {
                 Mockito.when(daoMgr.getXXPortalUser()).thenReturn(xXPortalUserDao);
                 Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao);
-                Mockito.when(daoMgr.getXXTagAttribute()).thenReturn(xXTagAttributeDao);
                 Mockito.when(xXTagDefDao.getById(xXTag.getType())).thenReturn(xXTagDef);
                 Mockito.when(daoMgr.getXXServiceVersionInfo()).thenReturn(xXServiceVersionInfoDao);
                 rangerTagService.postUpdate(xXTag);
@@ -86,7 +93,6 @@ public class TestRangerTagService {
                 Mockito.when(daoMgr.getXXTagDef()).thenReturn(xXTagDefDao);
                 XXTag xXTag = createXXTag();
                 Mockito.when(xXTagDefDao.getById(1L)).thenReturn(xXTagDef);
-                Mockito.when(daoMgr.getXXTagAttribute()).thenReturn(xXTagAttributeDao);
                 rangerTagService.getPopulatedViewObject(xXTag);
 
         }
@@ -107,14 +113,17 @@ public class TestRangerTagService {
 
         @Test
         public void test5GetTagsForResourceId() {
-                Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao);
-                rangerTagService.getTagsForResourceId(1L);
+                Mockito.when(daoMgr.getXXServiceResource()).thenReturn(xxServiceResourceDao);
+                Mockito.when(xxServiceResourceDao.getById(1L)).thenReturn(xxServiceResource);
+
+            rangerTagService.getTagsForResourceId(1L);
 
         }
 
         @Test
         public void test6GetTagsForResourceGuid() {
-                Mockito.when(daoMgr.getXXTag()).thenReturn(xXTagDao);
+            Mockito.when(daoMgr.getXXServiceResource()).thenReturn(xxServiceResourceDao);
+            Mockito.when(xxServiceResourceDao.findByGuid("1")).thenReturn(xxServiceResource);
                 rangerTagService.getTagsForResourceGuid("1");
 
         }


[6/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java
index c26f0a5..36a7b4b 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java
@@ -27,31 +27,29 @@ import java.util.Map;
 
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
-import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.ranger.authorization.utils.JsonUtils;
 import org.apache.ranger.authorization.utils.StringUtil;
 import org.apache.ranger.db.RangerDaoManager;
-import org.apache.ranger.entity.*;
+import org.apache.ranger.entity.XXPolicy;
+import org.apache.ranger.entity.XXPolicyLabel;
+import org.apache.ranger.entity.XXPolicyLabelMap;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXService;
 import org.apache.ranger.plugin.model.RangerPolicy;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemDataMaskInfo;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemRowFilterInfo;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem;
-import org.apache.ranger.plugin.model.RangerValiditySchedule;
-import org.apache.ranger.plugin.policyevaluator.RangerPolicyItemEvaluator;
 import org.apache.ranger.plugin.util.RangerPerfTracer;
-import org.apache.ranger.service.RangerPolicyService;
 import org.springframework.transaction.PlatformTransactionManager;
 import org.springframework.transaction.TransactionStatus;
 import org.springframework.transaction.support.TransactionCallback;
 import org.springframework.transaction.support.TransactionTemplate;
 
+
 public class RangerPolicyRetriever {
 	static final Log LOG      = LogFactory.getLog(RangerPolicyRetriever.class);
 	static final Log PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever");
@@ -303,35 +301,15 @@ public class RangerPolicyRetriever {
 	}
 
 	class LookupCache {
-		final Map<Long, String> userNames       = new HashMap<Long, String>();
-		final Map<Long, String> userScreenNames = new HashMap<Long, String>();
-		final Map<Long, String> groupNames      = new HashMap<Long, String>();
-		final Map<Long, String> accessTypes     = new HashMap<Long, String>();
-		final Map<Long, String> conditions      = new HashMap<Long, String>();
-		final Map<Long, String> resourceDefs    = new HashMap<Long, String>();
-		final Map<Long, String> dataMasks       = new HashMap<Long, String>();
+		final Map<Long, String>              userScreenNames            = new HashMap<Long, String>();
+		final Map<Long, Map<String, String>> groupMappingsPerPolicy     = new HashMap<>();
+		final Map<Long, Map<String, String>> userMappingsPerPolicy      = new HashMap<>();
+		final Map<Long, Map<String, String>> accessMappingsPerPolicy    = new HashMap<>();
+		final Map<Long, Map<String, String>> resourceMappingsPerPolicy  = new HashMap<>();
+		final Map<Long, Map<String, String>> dataMaskMappingsPerPolicy  = new HashMap<>();
+		final Map<Long, Map<String, String>> conditionMappingsPerPolicy = new HashMap<>();
 		final Map<Long, String> policyLabels    = new HashMap<Long, String>();
 
-		String getUserName(Long userId) {
-			String ret = null;
-
-			if(userId != null) {
-				ret = userNames.get(userId);
-
-				if(ret == null) {
-					XXUser user = daoMgr.getXXUser().getById(userId);
-
-					if(user != null) {
-						ret = user.getName(); // Name is `loginId`
-
-						userNames.put(userId,  ret);
-					}
-				}
-			}
-
-			return ret;
-		}
-
 		String getPolicyLabelName(Long policyLabelId) {
 			String ret = null;
 
@@ -386,233 +364,141 @@ public class RangerPolicyRetriever {
 			return ret;
 		}
 
-		String getGroupName(Long groupId) {
-			String ret = null;
-
-			if(groupId != null) {
-				ret = groupNames.get(groupId);
+		void setNameMapping(Map<Long, Map<String, String>> nameMappingContainer, List<PolicyTextNameMap> nameMappings) {
+			nameMappingContainer.clear();
 
-				if(ret == null) {
-					XXGroup group = daoMgr.getXXGroup().getById(groupId);
+			for (PolicyTextNameMap nameMapping : nameMappings) {
+				Map<String, String> policyNameMap = nameMappingContainer.get(nameMapping.policyId);
 
-					if(group != null) {
-						ret = group.getName();
+				if (policyNameMap == null) {
+					policyNameMap = new HashMap<>();
 
-						groupNames.put(groupId,  ret);
-					}
+					nameMappingContainer.put(nameMapping.policyId, policyNameMap);
 				}
-			}
-
-			return ret;
-		}
-
-		String getAccessType(Long accessTypeId) {
-			String ret = null;
-
-			if(accessTypeId != null) {
-				ret = accessTypes.get(accessTypeId);
 
-				if(ret == null) {
-					XXAccessTypeDef xAccessType = daoMgr.getXXAccessTypeDef().getById(accessTypeId);
-
-					if(xAccessType != null) {
-						ret = xAccessType.getName();
-
-						accessTypes.put(accessTypeId,  ret);
-					}
-				}
+				policyNameMap.put(nameMapping.oldName, nameMapping.currentName);
 			}
-
-			return ret;
 		}
 
-		String getConditionType(Long conditionDefId) {
-			String ret = null;
-
-			if(conditionDefId != null) {
-				ret = conditions.get(conditionDefId);
+		String getMappedName(Map<Long, Map<String, String>> nameMappingContainer, Long policyId, String nameToMap) {
+			Map<String, String> policyNameMap = nameMappingContainer.get(policyId);
 
-				if(ret == null) {
-					XXPolicyConditionDef xPolicyConditionDef = daoMgr.getXXPolicyConditionDef().getById(conditionDefId);
-
-					if(xPolicyConditionDef != null) {
-						ret = xPolicyConditionDef.getName();
-
-						conditions.put(conditionDefId,  ret);
-					}
-				}
-			}
-
-			return ret;
+			return policyNameMap != null ? policyNameMap.get(nameToMap) : null;
 		}
 
-		String getResourceName(Long resourceDefId) {
-			String ret = null;
-
-			if(resourceDefId != null) {
-				ret = resourceDefs.get(resourceDefId);
-
-				if(ret == null) {
-					XXResourceDef xResourceDef = daoMgr.getXXResourceDef().getById(resourceDefId);
-
-					if(xResourceDef != null) {
-						ret = xResourceDef.getName();
+		void setGroupNameMapping(List<PolicyTextNameMap> groupNameMapping) {
+			setNameMapping(groupMappingsPerPolicy, groupNameMapping);
+		}
 
-						resourceDefs.put(resourceDefId,  ret);
-					}
-				}
-			}
+		void setUserNameMapping(List<PolicyTextNameMap> userNameMapping) {
+			setNameMapping(userMappingsPerPolicy, userNameMapping);
+		}
 
-			return ret;
+		void setAccessNameMapping(List<PolicyTextNameMap> accessNameMapping) {
+			setNameMapping(accessMappingsPerPolicy, accessNameMapping);
 		}
 
-		String getDataMaskName(Long dataMaskDefId) {
-			String ret = null;
+		public void setResourceNameMapping(List<PolicyTextNameMap> resourceNameMapping) {
+			setNameMapping(resourceMappingsPerPolicy, resourceNameMapping);
+		}
 
-			if(dataMaskDefId != null) {
-				ret = dataMasks.get(dataMaskDefId);
+		public void setDataMaskNameMapping(List<PolicyTextNameMap> dataMaskMapping) {
+			setNameMapping(dataMaskMappingsPerPolicy, dataMaskMapping);
+		}
 
-				if(ret == null) {
-					XXDataMaskTypeDef xDataMaskDef = daoMgr.getXXDataMaskTypeDef().getById(dataMaskDefId);
+		public void setConditionNameMapping(List<PolicyTextNameMap> conditionNameMapping) {
+			setNameMapping(conditionMappingsPerPolicy, conditionNameMapping);
+		}
 
-					if(xDataMaskDef != null) {
-						ret = xDataMaskDef.getName();
+	}
 
-						dataMasks.put(dataMaskDefId,  ret);
-					}
-				}
-			}
+	public static class PolicyTextNameMap {
+		final Long   policyId;
+		final String oldName;
+		final String currentName;
 
-			return ret;
+		public PolicyTextNameMap(Long policyId, String oldName, String currentName) {
+			this.policyId    = policyId;
+			this.oldName     = oldName;
+			this.currentName = currentName;
 		}
 	}
 
-	static List<XXPolicy> asList(XXPolicy policy) {
-		List<XXPolicy> ret = new ArrayList<XXPolicy>();
+    static List<XXPolicy> asList(XXPolicy policy) {
+        List<XXPolicy> ret = new ArrayList<>();
 
-		if(policy != null) {
-			ret.add(policy);
-		}
+        if (policy != null) {
+            ret.add(policy);
+        }
 
-		return ret;
-	}
+        return ret;
+    }
 
 	class RetrieverContext {
-		final XXService                           service;
-		final ListIterator<XXPolicy>              iterPolicy;
-		final ListIterator<XXPolicyResource>      iterResources;
-		final ListIterator<XXPolicyResourceMap>   iterResourceMaps;
-		final ListIterator<XXPolicyItem>          iterPolicyItems;
-		final ListIterator<XXPolicyItemUserPerm>  iterUserPerms;
-		final ListIterator<XXPolicyItemGroupPerm> iterGroupPerms;
-		final ListIterator<XXPolicyItemAccess>    iterAccesses;
-		final ListIterator<XXPolicyItemCondition> iterConditions;
-		final ListIterator<XXPolicyItemDataMaskInfo>  iterDataMaskInfos;
-		final ListIterator<XXPolicyItemRowFilterInfo> iterRowFilterInfos;
-        final ListIterator<XXPolicyLabelMap> iterPolicyLabels;
+		final XXService              service;
+		final ListIterator<XXPolicy> iterPolicy;
+		final ListIterator<XXPolicyLabelMap> iterPolicyLabels;
 
 		RetrieverContext(XXService xService) {
-			Long serviceId = xService == null ? null : xService.getId();
-
-			List<XXPolicy>              xPolicies     = daoMgr.getXXPolicy().findByServiceId(serviceId);
-			List<XXPolicyResource>      xResources    = daoMgr.getXXPolicyResource().findByServiceId(serviceId);
-			List<XXPolicyResourceMap>   xResourceMaps = daoMgr.getXXPolicyResourceMap().findByServiceId(serviceId);
-			List<XXPolicyItem>          xPolicyItems  = daoMgr.getXXPolicyItem().findByServiceId(serviceId);
-			List<XXPolicyItemUserPerm>  xUserPerms    = daoMgr.getXXPolicyItemUserPerm().findByServiceId(serviceId);
-			List<XXPolicyItemGroupPerm> xGroupPerms   = daoMgr.getXXPolicyItemGroupPerm().findByServiceId(serviceId);
-			List<XXPolicyItemAccess>    xAccesses     = daoMgr.getXXPolicyItemAccess().findByServiceId(serviceId);
-			List<XXPolicyItemCondition> xConditions   = daoMgr.getXXPolicyItemCondition().findByServiceId(serviceId);
-			List<XXPolicyItemDataMaskInfo>  xDataMaskInfos  = daoMgr.getXXPolicyItemDataMaskInfo().findByServiceId(serviceId);
-			List<XXPolicyItemRowFilterInfo> xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByServiceId(serviceId);
-			List<XXPolicyLabelMap> xxPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId);
-
-			this.service          = xService;
-			this.iterPolicy       = xPolicies.listIterator();
-			this.iterResources    = xResources.listIterator();
-			this.iterResourceMaps = xResourceMaps.listIterator();
-			this.iterPolicyItems  = xPolicyItems.listIterator();
-			this.iterUserPerms    = xUserPerms.listIterator();
-			this.iterGroupPerms   = xGroupPerms.listIterator();
-			this.iterAccesses     = xAccesses.listIterator();
-			this.iterConditions   = xConditions.listIterator();
-			this.iterDataMaskInfos  = xDataMaskInfos.listIterator();
-			this.iterRowFilterInfos = xRowFilterInfos.listIterator();
-            this.iterPolicyLabels = xxPolicyLabelMap.listIterator();
-		}
-
-		RetrieverContext(XXPolicy xPolicy) {
-			this(xPolicy, getXXService(xPolicy.getService()));
+			if (xService != null) {
+				Long serviceId = xService.getId();
+
+				lookupCache.setGroupNameMapping(daoMgr.getXXPolicyRefGroup().findUpdatedGroupNamesByService(serviceId));
+				lookupCache.setUserNameMapping(daoMgr.getXXPolicyRefUser().findUpdatedUserNamesByService(serviceId));
+				lookupCache.setAccessNameMapping(daoMgr.getXXPolicyRefAccessType().findUpdatedAccessNamesByService(serviceId));
+				lookupCache.setResourceNameMapping(daoMgr.getXXPolicyRefResource().findUpdatedResourceNamesByService(serviceId));
+				lookupCache.setDataMaskNameMapping(daoMgr.getXXPolicyRefDataMaskType().findUpdatedDataMaskNamesByService(serviceId));
+				lookupCache.setConditionNameMapping(daoMgr.getXXPolicyRefCondition().findUpdatedConditionNamesByService(serviceId));
+
+				this.service    = xService;
+				this.iterPolicy = daoMgr.getXXPolicy().findByServiceId(serviceId).listIterator();
+				this.iterPolicyLabels = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId).listIterator();
+			} else {
+				this.service    = null;
+				this.iterPolicy = null;
+				this.iterPolicyLabels = null;
+			}
 		}
 
 		RetrieverContext(XXPolicy xPolicy, XXService xService) {
-			Long policyId = xPolicy == null ? null : xPolicy.getId();
-
-			List<XXPolicy>              xPolicies     = asList(xPolicy);
-			List<XXPolicyResource>      xResources    = daoMgr.getXXPolicyResource().findByPolicyId(policyId);
-			List<XXPolicyResourceMap>   xResourceMaps = daoMgr.getXXPolicyResourceMap().findByPolicyId(policyId);
-			List<XXPolicyItem>          xPolicyItems  = daoMgr.getXXPolicyItem().findByPolicyId(policyId);
-			List<XXPolicyItemUserPerm>  xUserPerms    = daoMgr.getXXPolicyItemUserPerm().findByPolicyId(policyId);
-			List<XXPolicyItemGroupPerm> xGroupPerms   = daoMgr.getXXPolicyItemGroupPerm().findByPolicyId(policyId);
-			List<XXPolicyItemAccess>    xAccesses     = daoMgr.getXXPolicyItemAccess().findByPolicyId(policyId);
-			List<XXPolicyItemCondition> xConditions   = daoMgr.getXXPolicyItemCondition().findByPolicyId(policyId);
-			List<XXPolicyItemDataMaskInfo>  xDataMaskInfos  = daoMgr.getXXPolicyItemDataMaskInfo().findByPolicyId(policyId);
-			List<XXPolicyItemRowFilterInfo> xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByPolicyId(policyId);
-			List<XXPolicyLabelMap> xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByPolicyId(policyId);
-
-			this.service          = xService;
-			this.iterPolicy       = xPolicies.listIterator();
-			this.iterResources    = xResources.listIterator();
-			this.iterResourceMaps = xResourceMaps.listIterator();
-			this.iterPolicyItems  = xPolicyItems.listIterator();
-			this.iterUserPerms    = xUserPerms.listIterator();
-			this.iterGroupPerms   = xGroupPerms.listIterator();
-			this.iterAccesses     = xAccesses.listIterator();
-			this.iterConditions   = xConditions.listIterator();
-			this.iterDataMaskInfos  = xDataMaskInfos.listIterator();
-			this.iterRowFilterInfos = xRowFilterInfos.listIterator();
-			this.iterPolicyLabels = xPolicyLabelMap.listIterator();
+			Long policyId = xPolicy.getId();
+
+			lookupCache.setGroupNameMapping(daoMgr.getXXPolicyRefGroup().findUpdatedGroupNamesByPolicy(policyId));
+			lookupCache.setUserNameMapping(daoMgr.getXXPolicyRefUser().findUpdatedUserNamesByPolicy(policyId));
+			lookupCache.setAccessNameMapping(daoMgr.getXXPolicyRefAccessType().findUpdatedAccessNamesByPolicy(policyId));
+			lookupCache.setResourceNameMapping(daoMgr.getXXPolicyRefResource().findUpdatedResourceNamesByPolicy(policyId));
+			lookupCache.setDataMaskNameMapping(daoMgr.getXXPolicyRefDataMaskType().findUpdatedDataMaskNamesByPolicy(policyId));
+			lookupCache.setConditionNameMapping(daoMgr.getXXPolicyRefCondition().findUpdatedConditionNamesByPolicy(policyId));
+
+			this.service    = xService;
+			this.iterPolicy = asList(xPolicy).listIterator();
+			this.iterPolicyLabels = daoMgr.getXXPolicyLabelMap().findByPolicyId(policyId).listIterator();
 		}
 
 		RangerPolicy getNextPolicy() {
 			RangerPolicy ret = null;
 
-			if(iterPolicy.hasNext()) {
+			if (service != null && iterPolicy != null && iterPolicy.hasNext()) {
 				XXPolicy xPolicy = iterPolicy.next();
 
-				if(xPolicy != null) {
-					ret = new RangerPolicy();
-
-					ret.setId(xPolicy.getId());
-					ret.setGuid(xPolicy.getGuid());
-					ret.setIsEnabled(xPolicy.getIsEnabled());
-					ret.setCreatedBy(lookupCache.getUserScreenName(xPolicy.getAddedByUserId()));
-					ret.setUpdatedBy(lookupCache.getUserScreenName(xPolicy.getUpdatedByUserId()));
-					ret.setCreateTime(xPolicy.getCreateTime());
-					ret.setUpdateTime(xPolicy.getUpdateTime());
-					ret.setVersion(xPolicy.getVersion());
-					ret.setService(service == null ? null : service.getName());
-					ret.setName(StringUtils.trim(xPolicy.getName()));
-					ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType());
-					ret.setPolicyPriority(xPolicy.getPolicyPriority() == null ? RangerPolicy.POLICY_PRIORITY_NORMAL : xPolicy.getPolicyPriority());
-					ret.setDescription(xPolicy.getDescription());
-					ret.setResourceSignature(xPolicy.getResourceSignature());
-					ret.setIsAuditEnabled(xPolicy.getIsAuditEnabled());
-
-					Map<String, String> mapOfOptions = JsonUtils.jsonToMapStringString(xPolicy.getOptions());
-
-					if (MapUtils.isNotEmpty(mapOfOptions)) {
-						String validitySchedulesStr = mapOfOptions.get(RangerPolicyService.OPTION_POLICY_VALIDITY_SCHEDULES);
-
-						if (StringUtils.isNotEmpty(validitySchedulesStr)) {
-							List<RangerValiditySchedule> validitySchedules = JsonUtils.jsonToRangerValiditySchedule(validitySchedulesStr);
-
-							ret.setValiditySchedules(validitySchedules);
-						}
+				if (xPolicy != null) {
+					String policyText = xPolicy.getPolicyText();
+
+					ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class);
+
+					if (ret != null) {
+						ret.setId(xPolicy.getId());
+						ret.setGuid(xPolicy.getGuid());
+						ret.setCreatedBy(lookupCache.getUserScreenName(xPolicy.getAddedByUserId()));
+						ret.setUpdatedBy(lookupCache.getUserScreenName(xPolicy.getUpdatedByUserId()));
+						ret.setCreateTime(xPolicy.getCreateTime());
+						ret.setUpdateTime(xPolicy.getUpdateTime());
+						ret.setVersion(xPolicy.getVersion());
+						ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType());
+						ret.setService(service.getName());
+						updatePolicyReferenceFields(ret);
+						getPolicyLabels(ret);
 					}
-
-					getPolicyLabels(ret);
-					getResource(ret);
-					getPolicyItems(ret);
 				}
 			}
 
@@ -638,251 +524,121 @@ public class RangerPolicyRetriever {
 			}
 		}
 
-		List<RangerPolicy> getAllPolicies() {
-			List<RangerPolicy> ret = new ArrayList<RangerPolicy>();
-
-			while(iterPolicy.hasNext()) {
-				RangerPolicy policy = getNextPolicy();
-
-				if(policy != null) {
-					ret.add(policy);
-				}
-			}
-
-			if(! hasProcessedAll()) {
-				LOG.warn("getAllPolicies(): perhaps one or more policies got updated during retrieval. Falling back to secondary method");
-
-				ret = getAllPoliciesBySecondary();
-			}
-
-			return ret;
-		}
-
-		List<RangerPolicy> getAllPoliciesBySecondary() {
-			List<RangerPolicy> ret = null;
+		void updatePolicyReferenceFields(final RangerPolicy policy) {
+			final Long policyId = policy.getId();
 
-			if(service != null) {
-				List<XXPolicy> xPolicies = daoMgr.getXXPolicy().findByServiceId(service.getId());
+			Map<String, String> policyResourceNameMap = lookupCache.resourceMappingsPerPolicy.get(policyId);
 
-				if(CollectionUtils.isNotEmpty(xPolicies)) {
-					ret = new ArrayList<RangerPolicy>(xPolicies.size());
+			if (MapUtils.isNotEmpty(policyResourceNameMap) && CollectionUtils.containsAny(policyResourceNameMap.keySet(), policy.getResources().keySet())) {
+				Map<String, RangerPolicyResource> updatedResources = new HashMap<>();
 
-					for(XXPolicy xPolicy : xPolicies) {
-						RetrieverContext ctx = new RetrieverContext(xPolicy, service);
+				for (Map.Entry<String, RangerPolicyResource> entry : policy.getResources().entrySet()) {
+					String               resourceName   = entry.getKey();
+					RangerPolicyResource policyResource = entry.getValue();
+					String               updatedName    = policyResourceNameMap.get(resourceName);
 
-						RangerPolicy policy = ctx.getNextPolicy();
-
-						if(policy != null) {
-							ret.add(policy);
-						}
+					if (updatedName == null) {
+						updatedName = resourceName;
 					}
-				}
-			}
 
-			return ret;
-		}
-
-		private boolean hasProcessedAll() {
-			boolean moreToProcess =    iterPolicy.hasNext()
-									|| iterResources.hasNext()
-									|| iterResourceMaps.hasNext()
-									|| iterPolicyItems.hasNext()
-									|| iterUserPerms.hasNext()
-									|| iterGroupPerms.hasNext()
-									|| iterAccesses.hasNext()
-									|| iterConditions.hasNext()
-									|| iterDataMaskInfos.hasNext()
-									|| iterRowFilterInfos.hasNext()
-									|| iterPolicyLabels.hasNext();
-
-			return !moreToProcess;
-		}
-
-		private void getResource(RangerPolicy policy) {
-			while(iterResources.hasNext()) {
-				XXPolicyResource xResource = iterResources.next();
+					updatedResources.put(updatedName, policyResource);
+				}
 
-				if(xResource.getPolicyid().equals(policy.getId())) {
-					RangerPolicyResource resource = new RangerPolicyResource();
+				policy.setResources(updatedResources);
+			}
 
-					resource.setIsExcludes(xResource.getIsexcludes());
-					resource.setIsRecursive(xResource.getIsrecursive());
+			for (List<? extends RangerPolicyItem> policyItems :  PolicyRefUpdater.getAllPolicyItems(policy)) {
+				if (CollectionUtils.isEmpty(policyItems)) {
+					continue;
+				}
 
-					while(iterResourceMaps.hasNext()) {
-						XXPolicyResourceMap xResourceMap = iterResourceMaps.next();
+				for (RangerPolicyItem policyItem : policyItems) {
+					if (lookupCache.groupMappingsPerPolicy.containsKey(policyId)) {
+						List<String> updatedGroups = getUpdatedNames(lookupCache.groupMappingsPerPolicy, policyId, policyItem.getGroups());
 
-						if(xResourceMap.getResourceid().equals(xResource.getId())) {
-							resource.getValues().add(xResourceMap.getValue());
-						} else {
-							if(iterResourceMaps.hasPrevious()) {
-								iterResourceMaps.previous();
-							}
-							break;
+						if (updatedGroups != null) {
+							policyItem.setGroups(updatedGroups);
 						}
 					}
 
-					policy.getResources().put(lookupCache.getResourceName(xResource.getResdefid()), resource);
-				} else if(xResource.getPolicyid().compareTo(policy.getId()) > 0) {
-					if(iterResources.hasPrevious()) {
-						iterResources.previous();
-					}
-					break;
-				}
-			}
-		}
-
-		private void getPolicyItems(RangerPolicy policy) {
-			while(iterPolicyItems.hasNext()) {
-				XXPolicyItem xPolicyItem = iterPolicyItems.next();
+					if (lookupCache.userMappingsPerPolicy.containsKey(policyId)) {
+						List<String> updatedUsers = getUpdatedNames(lookupCache.userMappingsPerPolicy, policyId, policyItem.getUsers());
 
-				if(xPolicyItem.getPolicyid().equals(policy.getId())) {
-					final RangerPolicyItem          policyItem;
-					final RangerDataMaskPolicyItem  dataMaskPolicyItem;
-					final RangerRowFilterPolicyItem rowFilterPolicyItem;
-
-					if(xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) {
-						dataMaskPolicyItem  = new RangerDataMaskPolicyItem();
-						rowFilterPolicyItem = null;
-						policyItem          = dataMaskPolicyItem;
-					} else if(xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) {
-						dataMaskPolicyItem  = null;
-						rowFilterPolicyItem = new RangerRowFilterPolicyItem();
-						policyItem          = rowFilterPolicyItem;
-					} else {
-						dataMaskPolicyItem  = null;
-						rowFilterPolicyItem = null;
-						policyItem          = new RangerPolicyItem();
+						if (updatedUsers != null) {
+							policyItem.setUsers(updatedUsers);
+						}
 					}
 
+					if (lookupCache.accessMappingsPerPolicy.containsKey(policyId)) {
+						for (RangerPolicyItemAccess itemAccess : policyItem.getAccesses()) {
+							String updatedName = lookupCache.getMappedName(lookupCache.accessMappingsPerPolicy, policyId, itemAccess.getType());
 
-					while(iterAccesses.hasNext()) {
-						XXPolicyItemAccess xAccess = iterAccesses.next();
-
-						if(xAccess.getPolicyitemid().equals(xPolicyItem.getId())) {
-							policyItem.getAccesses().add(new RangerPolicyItemAccess(lookupCache.getAccessType(xAccess.getType()), xAccess.getIsallowed()));
-						} else {
-							if(iterAccesses.hasPrevious()) {
-								iterAccesses.previous();
+							if (updatedName != null) {
+								itemAccess.setType(updatedName);
 							}
-							break;
 						}
 					}
 
-					while(iterUserPerms.hasNext()) {
-						XXPolicyItemUserPerm xUserPerm = iterUserPerms.next();
+					if (lookupCache.conditionMappingsPerPolicy.containsKey(policyId)) {
+						for (RangerPolicyItemCondition condition : policyItem.getConditions()) {
+							String updatedName = lookupCache.getMappedName(lookupCache.conditionMappingsPerPolicy, policyId, condition.getType());
 
-						if(xUserPerm.getPolicyitemid().equals(xPolicyItem.getId())) {
-							String userName = lookupCache.getUserName(xUserPerm.getUserid());
-							if (userName != null) {
-								policyItem.getUsers().add(userName);
-							}
-						} else {
-							if(iterUserPerms.hasPrevious()) {
-								iterUserPerms.previous();
+							if (updatedName != null) {
+								condition.setType(updatedName);
 							}
-							break;
 						}
 					}
 
-					while(iterGroupPerms.hasNext()) {
-						XXPolicyItemGroupPerm xGroupPerm = iterGroupPerms.next();
+					if (policyItem instanceof RangerDataMaskPolicyItem && lookupCache.dataMaskMappingsPerPolicy.containsKey(policyId)) {
+						RangerDataMaskPolicyItem dataMaskItem = (RangerDataMaskPolicyItem) policyItem;
+						String                   updatedName  = lookupCache.getMappedName(lookupCache.dataMaskMappingsPerPolicy, policyId, dataMaskItem.getDataMaskInfo().getDataMaskType());
 
-						if(xGroupPerm.getPolicyitemid().equals(xPolicyItem.getId())) {
-							String groupName = lookupCache.getGroupName(xGroupPerm.getGroupid());
-							if (groupName != null) {
-								policyItem.getGroups().add(groupName);
-							}
-						} else {
-							if(iterGroupPerms.hasPrevious()) {
-								iterGroupPerms.previous();
-							}
-							break;
+						if (updatedName != null) {
+							dataMaskItem.getDataMaskInfo().setDataMaskType(updatedName);
 						}
 					}
+				}
+			}
+		}
 
-					RangerPolicyItemCondition condition         = null;
-					Long                      prevConditionType = null;
-					while(iterConditions.hasNext()) {
-						XXPolicyItemCondition xCondition = iterConditions.next();
+		List<String> getUpdatedNames(final Map<Long, Map<String, String>> nameMappingContainer, final Long policyId, final List<String> namesToMap) {
+			List<String>        ret           = null;
+			Map<String, String> policyNameMap = nameMappingContainer.get(policyId);
 
-						if(xCondition.getPolicyitemid().equals(xPolicyItem.getId())) {
-							if(! xCondition.getType().equals(prevConditionType)) {
-								condition = new RangerPolicyItemCondition();
-								condition.setType(lookupCache.getConditionType(xCondition.getType()));
-								condition.getValues().add(xCondition.getValue());
+			if (MapUtils.isNotEmpty(policyNameMap) && CollectionUtils.containsAny(policyNameMap.keySet(), namesToMap)) {
+				ret = new ArrayList<>();
 
-								policyItem.getConditions().add(condition);
+				for (String nameToMap : namesToMap) {
+					String mappedName = policyNameMap.get(nameToMap);
 
-								prevConditionType = xCondition.getType();
-							} else {
-								condition.getValues().add(xCondition.getValue());
-							}
-						} else {
-							if(iterConditions.hasPrevious()) {
-								iterConditions.previous();
-							}
-							break;
-						}
+					if (mappedName != null) {
+						ret.add(mappedName);
+					} else {
+						ret.add(nameToMap);
 					}
+				}
 
-					policyItem.setDelegateAdmin(xPolicyItem.getDelegateAdmin());
-
-					if(dataMaskPolicyItem != null) {
-						while (iterDataMaskInfos.hasNext()) {
-							XXPolicyItemDataMaskInfo xDataMaskInfo = iterDataMaskInfos.next();
-
-							if (xDataMaskInfo.getPolicyItemId().equals(xPolicyItem.getId())) {
-								dataMaskPolicyItem.setDataMaskInfo(new RangerPolicyItemDataMaskInfo(lookupCache.getDataMaskName(xDataMaskInfo.getType()), xDataMaskInfo.getConditionExpr(), xDataMaskInfo.getValueExpr()));
-							} else {
-								if (iterDataMaskInfos.hasPrevious()) {
-									iterDataMaskInfos.previous();
-								}
-								break;
-							}
-						}
-					}
+			}
 
-					if(rowFilterPolicyItem != null) {
-						while (iterRowFilterInfos.hasNext()) {
-							XXPolicyItemRowFilterInfo xRowFilterInfo = iterRowFilterInfos.next();
+			return ret;
+		}
 
-							if (xRowFilterInfo.getPolicyItemId().equals(xPolicyItem.getId())) {
-								rowFilterPolicyItem.setRowFilterInfo(new RangerPolicyItemRowFilterInfo(xRowFilterInfo.getFilterExpr()));
-							} else {
-								if (iterRowFilterInfos.hasPrevious()) {
-									iterRowFilterInfos.previous();
-								}
-								break;
-							}
-						}
-					}
+		List<RangerPolicy> getAllPolicies() {
+			List<RangerPolicy> ret = new ArrayList<>();
 
+			if (iterPolicy != null) {
+				while (iterPolicy.hasNext()) {
+					RangerPolicy policy = getNextPolicy();
 
-					int itemType = xPolicyItem.getItemType() == null ? RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW : xPolicyItem.getItemType();
-
-					if(itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW) {
-						policy.getPolicyItems().add(policyItem);
-					} else if(itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY) {
-						policy.getDenyPolicyItems().add(policyItem);
-					} else if(itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS) {
-						policy.getAllowExceptions().add(policyItem);
-					} else if(itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS) {
-						policy.getDenyExceptions().add(policyItem);
-					} else if(itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) {
-						policy.getDataMaskPolicyItems().add(dataMaskPolicyItem);
-					} else if(itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) {
-						policy.getRowFilterPolicyItems().add(rowFilterPolicyItem);
-					} else { // unknown itemType
-						LOG.warn("RangerPolicyRetriever.getPolicy(policyId=" + policy.getId() + "): ignoring unknown policyItemType " + itemType);
-					}
-				} else if(xPolicyItem.getPolicyid().compareTo(policy.getId()) > 0) {
-					if(iterPolicyItems.hasPrevious()) {
-						iterPolicyItems.previous();
+					if (policy != null) {
+						ret.add(policy);
 					}
-					break;
 				}
 			}
+
+			return ret;
 		}
 	}
+
 }
 

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java
index 7875bc2..394c05c 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java
@@ -19,25 +19,26 @@
 
 package org.apache.ranger.biz;
 
+import java.lang.reflect.Type;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.ListIterator;
 import java.util.Map;
 
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
 import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
-import org.apache.ranger.authorization.utils.JsonUtils;
 import org.apache.ranger.authorization.utils.StringUtil;
 import org.apache.ranger.db.RangerDaoManager;
 import org.apache.ranger.entity.*;
 import org.apache.ranger.plugin.model.*;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
 import org.apache.ranger.plugin.util.RangerPerfTracer;
+import org.apache.ranger.service.RangerServiceResourceService;
 import org.springframework.transaction.PlatformTransactionManager;
 import org.springframework.transaction.TransactionStatus;
 import org.springframework.transaction.support.TransactionCallback;
@@ -48,34 +49,33 @@ public class RangerTagDBRetriever {
 	static final Log PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerTagDBRetriever");
 	public static final String OPTION_RANGER_FILTER_TAGS_FOR_SERVICE_PLUGIN = "ranger.filter.tags.for.service.plugin";
 
+	public static final Type subsumedDataType = new TypeToken<List<RangerTagDef.RangerTagAttributeDef>>() {}.getType();
+
+	public static final Gson gsonBuilder = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z")
+			.create();
+
 	private final RangerDaoManager daoMgr;
-	private final XXService xService;
 	private final LookupCache lookupCache;
 
-	private final PlatformTransactionManager  txManager;
-	private final TransactionTemplate         txTemplate;
-
 	private List<RangerServiceResource> serviceResources;
 	private Map<Long, RangerTagDef> tagDefs;
-	private Map<Long, RangerTag> tags;
-	private List<RangerTagResourceMap> tagResourceMaps;
 
-	private boolean filterForServicePlugin;
+	RangerTagDBRetriever(final RangerDaoManager daoMgr, final PlatformTransactionManager txManager, final XXService xService) {
 
-	public RangerTagDBRetriever(final RangerDaoManager daoMgr, final PlatformTransactionManager txManager, final XXService xService) {
 		this.daoMgr = daoMgr;
-		this.txManager = txManager;
-		if (this.txManager != null) {
-			this.txTemplate = new TransactionTemplate(this.txManager);
-			this.txTemplate.setReadOnly(true);
+
+		final TransactionTemplate txTemplate;
+
+		if (txManager != null) {
+			txTemplate = new TransactionTemplate(txManager);
+			txTemplate.setReadOnly(true);
 		} else {
-			this.txTemplate = null;
+			txTemplate = null;
 		}
-		this.xService = xService;
 		this.lookupCache = new LookupCache();
 
 
-		if (this.daoMgr != null && this.xService != null) {
+		if (this.daoMgr != null && xService != null) {
 
 			RangerPerfTracer perf = null;
 
@@ -83,13 +83,11 @@ public class RangerTagDBRetriever {
 				perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerTagDBReceiver.getTags(serviceName=" + xService.getName());
 			}
 
-			filterForServicePlugin = RangerConfiguration.getInstance().getBoolean(OPTION_RANGER_FILTER_TAGS_FOR_SERVICE_PLUGIN, false);
-
-			if (this.txTemplate == null) {
+			if (txTemplate == null) {
 				if (LOG.isDebugEnabled()) {
 					LOG.debug("Load Tags in the same thread and using an existing transaction");
 				}
-				if (initializeTagCache(xService) == false) {
+				if (!initializeTagCache(xService)) {
 					LOG.error("Failed to get tags for service:[" + xService.getName() + "] in the same thread and using an existing transaction");
 				}
 			} else {
@@ -112,20 +110,48 @@ public class RangerTagDBRetriever {
 		}
 	}
 
-	public List<RangerTagResourceMap> getTagResourceMaps() {
-		return tagResourceMaps;
-	}
-
-	public List<RangerServiceResource> getServiceResources() {
+	List<RangerServiceResource> getServiceResources() {
 		return serviceResources;
 	}
 
-	public Map<Long, RangerTagDef> getTagDefs() {
+	Map<Long, RangerTagDef> getTagDefs() {
 		return tagDefs;
 	}
 
-	public Map<Long, RangerTag> getTags() {
-		return tags;
+	Map<Long, RangerTag> getTags() {
+
+		Map<Long, RangerTag> ret = new HashMap<>();
+
+		if (CollectionUtils.isNotEmpty(serviceResources)) {
+			for (RangerServiceResource serviceResource : serviceResources) {
+				List<RangerTag> tags = lookupCache.serviceResourceToTags.get(serviceResource.getId());
+				if (CollectionUtils.isNotEmpty(tags)) {
+					for (RangerTag tag : tags) {
+						ret.put(tag.getId(), tag);
+					}
+				}
+			}
+		}
+
+		return ret;
+	}
+
+	Map<Long, List<Long>> getResourceToTagIds() {
+		Map<Long, List<Long>> ret = new HashMap<>();
+
+		if (CollectionUtils.isNotEmpty(serviceResources)) {
+			for (RangerServiceResource serviceResource : serviceResources) {
+				List<RangerTag> tags = lookupCache.serviceResourceToTags.get(serviceResource.getId());
+				if (CollectionUtils.isNotEmpty(tags)) {
+					List<Long> tagIds = new ArrayList<>();
+					ret.put(serviceResource.getId(), tagIds);
+					for (RangerTag tag : tags) {
+						tagIds.add(tag.getId());
+					}
+				}
+			}
+		}
+		return ret;
 	}
 
 	private boolean initializeTagCache(XXService xService) {
@@ -133,69 +159,23 @@ public class RangerTagDBRetriever {
 		try {
 			TagRetrieverServiceResourceContext  serviceResourceContext  = new TagRetrieverServiceResourceContext(xService);
 			TagRetrieverTagDefContext           tagDefContext           = new TagRetrieverTagDefContext(xService);
-			TagRetrieverTagContext              tagContext              = new TagRetrieverTagContext(xService);
 
 			serviceResources    = serviceResourceContext.getAllServiceResources();
 			tagDefs             = tagDefContext.getAllTagDefs();
-			tags                = tagContext.getAllTags();
-
-			tagResourceMaps     = getAllTagResourceMaps();
 
 			ret = true;
 		} catch (Exception ex) {
-			LOG.error("Failed to get tags for service:[" + xService.getName() + "]");
+			LOG.error("Failed to get tags for service:[" + xService.getName() + "]", ex);
 			serviceResources    = null;
 			tagDefs             = null;
-			tags                = null;
-			tagResourceMaps     = null;
 			ret = false;
 		}
 		return ret;
 	}
-	private List<RangerTagResourceMap> getAllTagResourceMaps() {
-
-		List<XXTagResourceMap> xTagResourceMaps = filterForServicePlugin ? daoMgr.getXXTagResourceMap().findForServicePlugin(xService.getId()) : daoMgr.getXXTagResourceMap().findByServiceId(xService.getId());
-
-		ListIterator<XXTagResourceMap> iterTagResourceMap = xTagResourceMaps.listIterator();
-
-		List<RangerTagResourceMap> ret = new ArrayList<RangerTagResourceMap>();
-
-		while (iterTagResourceMap.hasNext()) {
-
-			XXTagResourceMap xTagResourceMap = iterTagResourceMap.next();
-
-			if (xTagResourceMap != null) {
-
-				RangerTagResourceMap tagResourceMap = new RangerTagResourceMap();
-
-				tagResourceMap.setId(xTagResourceMap.getId());
-				tagResourceMap.setGuid(xTagResourceMap.getGuid());
-				tagResourceMap.setCreatedBy(lookupCache.getUserScreenName(xTagResourceMap.getAddedByUserId()));
-				tagResourceMap.setUpdatedBy(lookupCache.getUserScreenName(xTagResourceMap.getUpdatedByUserId()));
-				tagResourceMap.setCreateTime(xTagResourceMap.getCreateTime());
-				tagResourceMap.setUpdateTime(xTagResourceMap.getUpdateTime());
-				tagResourceMap.setResourceId(xTagResourceMap.getResourceId());
-				tagResourceMap.setTagId(xTagResourceMap.getTagId());
-
-				ret.add(tagResourceMap);
-			}
-		}
-		return ret;
-	}
-
-	static <T> List<T> asList(T obj) {
-		List<T> ret = new ArrayList<T>();
-
-		if (obj != null) {
-			ret.add(obj);
-		}
-
-		return ret;
-	}
 
 	private class LookupCache {
-		final Map<Long, String> userScreenNames = new HashMap<Long, String>();
-		final Map<Long, String> resourceDefs = new HashMap<Long, String>();
+		final Map<Long, String> userScreenNames = new HashMap<>();
+		final Map<Long, List<RangerTag>> serviceResourceToTags = new HashMap<>();
 
 		String getUserScreenName(Long userId) {
 			String ret = null;
@@ -231,25 +211,6 @@ public class RangerTagDBRetriever {
 			return ret;
 		}
 
-		String getResourceName(Long resourceDefId) {
-			String ret = null;
-
-			if (resourceDefId != null) {
-				ret = resourceDefs.get(resourceDefId);
-
-				if (ret == null) {
-					XXResourceDef xResourceDef = daoMgr.getXXResourceDef().getById(resourceDefId);
-
-					if (xResourceDef != null) {
-						ret = xResourceDef.getName();
-
-						resourceDefs.put(resourceDefId, ret);
-					}
-				}
-			}
-
-			return ret;
-		}
 	}
 
 	private class TagLoaderThread extends Thread {
@@ -289,39 +250,19 @@ public class RangerTagDBRetriever {
 
 		final XXService service;
 		final ListIterator<XXServiceResource> iterServiceResource;
-		final ListIterator<XXServiceResourceElement> iterServiceResourceElement;
-		final ListIterator<XXServiceResourceElementValue> iterServiceResourceElementValue;
 
 		TagRetrieverServiceResourceContext(XXService xService) {
 			Long serviceId = xService == null ? null : xService.getId();
-
-			List<XXServiceResource> xServiceResources = filterForServicePlugin ? daoMgr.getXXServiceResource().findForServicePlugin(serviceId) : daoMgr.getXXServiceResource().findTaggedResourcesInServiceId(serviceId);
-			List<XXServiceResourceElement> xServiceResourceElements = filterForServicePlugin ? daoMgr.getXXServiceResourceElement().findForServicePlugin(serviceId) : daoMgr.getXXServiceResourceElement().findTaggedResourcesInServiceId(serviceId);
-			List<XXServiceResourceElementValue> xServiceResourceElementValues = filterForServicePlugin ? daoMgr.getXXServiceResourceElementValue().findForServicePlugin(serviceId) : daoMgr.getXXServiceResourceElementValue().findTaggedResourcesInServiceId(serviceId);
-
 			this.service = xService;
-			this.iterServiceResource = xServiceResources.listIterator();
-			this.iterServiceResourceElement = xServiceResourceElements.listIterator();
-			this.iterServiceResourceElementValue = xServiceResourceElementValues.listIterator();
-
-		}
 
-		TagRetrieverServiceResourceContext(XXServiceResource xServiceResource, XXService xService) {
-			Long resourceId = xServiceResource == null ? null : xServiceResource.getId();
+			List<XXServiceResource> xServiceResources = daoMgr.getXXServiceResource().findTaggedResourcesInServiceId(serviceId);
 
-			List<XXServiceResource> xServiceResources = asList(xServiceResource);
-			List<XXServiceResourceElement> xServiceResourceElements = daoMgr.getXXServiceResourceElement().findByResourceId(resourceId);
-			List<XXServiceResourceElementValue> xServiceResourceElementValues = daoMgr.getXXServiceResourceElementValue().findByResourceId(resourceId);
-
-			this.service = xService;
 			this.iterServiceResource = xServiceResources.listIterator();
-			this.iterServiceResourceElement = xServiceResourceElements.listIterator();
-			this.iterServiceResourceElementValue = xServiceResourceElementValues.listIterator();
 
 		}
 
 		List<RangerServiceResource> getAllServiceResources() {
-			List<RangerServiceResource> ret = new ArrayList<RangerServiceResource>();
+			List<RangerServiceResource> ret = new ArrayList<>();
 
 			while (iterServiceResource.hasNext()) {
 				RangerServiceResource serviceResource = getNextServiceResource();
@@ -331,12 +272,6 @@ public class RangerTagDBRetriever {
 				}
 			}
 
-			if (!hasProcessedAll()) {
-				LOG.warn("getAllServiceResources(): perhaps one or more serviceResources got updated during retrieval. Using fallback ... ");
-
-				ret = getServiceResourcesBySecondary();
-			}
-
 			return ret;
 		}
 
@@ -346,7 +281,7 @@ public class RangerTagDBRetriever {
 			if (iterServiceResource.hasNext()) {
 				XXServiceResource xServiceResource = iterServiceResource.next();
 
-				if (xServiceResource != null) {
+				if (xServiceResource != null && StringUtils.isNotEmpty(xServiceResource.getTags())) {
 					ret = new RangerServiceResource();
 
 					ret.setId(xServiceResource.getId());
@@ -359,108 +294,35 @@ public class RangerTagDBRetriever {
 					ret.setVersion(xServiceResource.getVersion());
 					ret.setResourceSignature(xServiceResource.getResourceSignature());
 
-					getServiceResourceElements(ret);
-				}
-			}
-
-			return ret;
-		}
-
-		void getServiceResourceElements(RangerServiceResource serviceResource) {
-			while (iterServiceResourceElement.hasNext()) {
-				XXServiceResourceElement xServiceResourceElement = iterServiceResourceElement.next();
-
-				if (xServiceResourceElement.getResourceId().equals(serviceResource.getId())) {
-					RangerPolicyResource resource = new RangerPolicyResource();
+					Map<String, RangerPolicy.RangerPolicyResource> serviceResourceElements = gsonBuilder.fromJson(xServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType);
+					ret.setResourceElements(serviceResourceElements);
 
-					resource.setIsExcludes(xServiceResourceElement.getIsExcludes());
-					resource.setIsRecursive(xServiceResourceElement.getIsRecursive());
-
-					while (iterServiceResourceElementValue.hasNext()) {
-						XXServiceResourceElementValue xServiceResourceElementValue = iterServiceResourceElementValue.next();
-
-						if (xServiceResourceElementValue.getResElementId().equals(xServiceResourceElement.getId())) {
-							resource.getValues().add(xServiceResourceElementValue.getValue());
-						} else {
-							if (iterServiceResourceElementValue.hasPrevious()) {
-								iterServiceResourceElementValue.previous();
-							}
-							break;
-						}
-					}
-
-					serviceResource.getResourceElements().put(lookupCache.getResourceName(xServiceResourceElement.getResDefId()), resource);
-				} else if (xServiceResourceElement.getResourceId().compareTo(serviceResource.getId()) > 0) {
-					if (iterServiceResourceElement.hasPrevious()) {
-						iterServiceResourceElement.previous();
-					}
-					break;
+					List<RangerTag> tags = gsonBuilder.fromJson(xServiceResource.getTags(), RangerServiceResourceService.duplicatedDataType);
+					lookupCache.serviceResourceToTags.put(xServiceResource.getId(), tags);
 				}
 			}
-		}
-
-		boolean hasProcessedAll() {
-			boolean moreToProcess = iterServiceResource.hasNext()
-					|| iterServiceResourceElement.hasNext()
-					|| iterServiceResourceElementValue.hasNext();
-			return !moreToProcess;
-		}
-
-		List<RangerServiceResource> getServiceResourcesBySecondary() {
-			List<RangerServiceResource> ret = null;
-
-			if (service != null) {
-				List<XXServiceResource> xServiceResources = filterForServicePlugin ? daoMgr.getXXServiceResource().findForServicePlugin(service.getId()) : daoMgr.getXXServiceResource().findTaggedResourcesInServiceId(service.getId());
 
-				if (CollectionUtils.isNotEmpty(xServiceResources)) {
-					ret = new ArrayList<RangerServiceResource>(xServiceResources.size());
-
-					for (XXServiceResource xServiceResource : xServiceResources) {
-						TagRetrieverServiceResourceContext ctx = new TagRetrieverServiceResourceContext(xServiceResource, service);
-
-						RangerServiceResource serviceResource = ctx.getNextServiceResource();
-
-						if (serviceResource != null) {
-							ret.add(serviceResource);
-						}
-					}
-				}
-			}
 			return ret;
 		}
+
 	}
 
 	private class TagRetrieverTagDefContext {
 
 		final XXService service;
 		final ListIterator<XXTagDef> iterTagDef;
-		final ListIterator<XXTagAttributeDef> iterTagAttributeDef;
-
 
 		TagRetrieverTagDefContext(XXService xService) {
 			Long serviceId = xService == null ? null : xService.getId();
 
-			List<XXTagDef> xTagDefs = filterForServicePlugin ? daoMgr.getXXTagDef().findForServicePlugin(serviceId) : daoMgr.getXXTagDef().findByServiceId(serviceId);
-			List<XXTagAttributeDef> xTagAttributeDefs = filterForServicePlugin ? daoMgr.getXXTagAttributeDef().findForServicePlugin(serviceId) : daoMgr.getXXTagAttributeDef().findByServiceId(serviceId);
-
-			this.service = xService;
-			this.iterTagDef = xTagDefs.listIterator();
-			this.iterTagAttributeDef = xTagAttributeDefs.listIterator();
-		}
-
-		TagRetrieverTagDefContext(XXTagDef xTagDef, XXService xService) {
-			Long tagDefId = xTagDef == null ? null : xTagDef.getId();
-
-			List<XXTagDef> xTagDefs = asList(xTagDef);
-			List<XXTagAttributeDef> xTagAttributeDefs = daoMgr.getXXTagAttributeDef().findByTagDefId(tagDefId);
+			List<XXTagDef> xTagDefs = daoMgr.getXXTagDef().findByServiceId(serviceId);
 
 			this.service = xService;
 			this.iterTagDef = xTagDefs.listIterator();
-			this.iterTagAttributeDef = xTagAttributeDefs.listIterator();
 		}
 
 		Map<Long, RangerTagDef> getAllTagDefs() {
-			Map<Long, RangerTagDef> ret = new HashMap<Long, RangerTagDef>();
+			Map<Long, RangerTagDef> ret = new HashMap<>();
 
 			while (iterTagDef.hasNext()) {
 				RangerTagDef tagDef = getNextTagDef();
@@ -470,13 +332,6 @@ public class RangerTagDBRetriever {
 				}
 			}
 
-			if (!hasProcessedAllTagDefs()) {
-				LOG.warn("getAllTagDefs(): perhaps one or more tag-definitions got updated during retrieval.  Using fallback ... ");
-
-				ret = getTagDefsBySecondary();
-
-			}
-
 			return ret;
 		}
 
@@ -499,203 +354,14 @@ public class RangerTagDBRetriever {
 					ret.setVersion(xTagDef.getVersion());
 					ret.setName(xTagDef.getName());
 					ret.setSource(xTagDef.getSource());
-
-					getTagAttributeDefs(ret);
+					List<RangerTagDef.RangerTagAttributeDef> attributeDefs = gsonBuilder.fromJson(xTagDef.getTagAttrDefs(), RangerTagDBRetriever.subsumedDataType);
+					ret.setAttributeDefs(attributeDefs);
 				}
 			}
 
 			return ret;
 		}
 
-		void getTagAttributeDefs(RangerTagDef tagDef) {
-			while (iterTagAttributeDef.hasNext()) {
-				XXTagAttributeDef xTagAttributeDef = iterTagAttributeDef.next();
-
-				if (xTagAttributeDef.getTagDefId().equals(tagDef.getId())) {
-					RangerTagDef.RangerTagAttributeDef tagAttributeDef = new RangerTagDef.RangerTagAttributeDef();
-
-					tagAttributeDef.setName(xTagAttributeDef.getName());
-					tagAttributeDef.setType(xTagAttributeDef.getType());
-
-					tagDef.getAttributeDefs().add(tagAttributeDef);
-				} else if (xTagAttributeDef.getTagDefId().compareTo(tagDef.getId()) > 0) {
-					if (iterTagAttributeDef.hasPrevious()) {
-						iterTagAttributeDef.previous();
-					}
-					break;
-				}
-			}
-		}
-
-		boolean hasProcessedAllTagDefs() {
-			boolean moreToProcess = iterTagAttributeDef.hasNext();
-			return !moreToProcess;
-		}
-
-		Map<Long, RangerTagDef> getTagDefsBySecondary() {
-			Map<Long, RangerTagDef> ret = null;
-
-			if (service != null) {
-				List<XXTagDef> xTagDefs = daoMgr.getXXTagDef().findByServiceId(service.getId());
-
-				if (CollectionUtils.isNotEmpty(xTagDefs)) {
-					ret = new HashMap<Long, RangerTagDef>(xTagDefs.size());
-
-					for (XXTagDef xTagDef : xTagDefs) {
-						TagRetrieverTagDefContext ctx = new TagRetrieverTagDefContext(xTagDef, service);
-
-						RangerTagDef tagDef = ctx.getNextTagDef();
-
-						if (tagDef != null) {
-							ret.put(tagDef.getId(), tagDef);
-						}
-					}
-				}
-			}
-			return ret;
-		}
 	}
 
-	private class TagRetrieverTagContext {
-
-		final XXService service;
-		final ListIterator<XXTag> iterTag;
-		final ListIterator<XXTagAttribute> iterTagAttribute;
-
-		TagRetrieverTagContext(XXService xService) {
-			Long serviceId = xService == null ? null : xService.getId();
-
-			List<XXTag> xTags = filterForServicePlugin ? daoMgr.getXXTag().findForServicePlugin(serviceId) : daoMgr.getXXTag().findByServiceId(serviceId);
-			List<XXTagAttribute> xTagAttributes = filterForServicePlugin ? daoMgr.getXXTagAttribute().findForServicePlugin(serviceId) : daoMgr.getXXTagAttribute().findByServiceId(serviceId);
-
-			this.service = xService;
-			this.iterTag = xTags.listIterator();
-			this.iterTagAttribute = xTagAttributes.listIterator();
-
-		}
-
-		TagRetrieverTagContext(XXTag xTag, XXService xService) {
-			Long tagId = xTag == null ? null : xTag.getId();
-
-			List<XXTag> xTags = asList(xTag);
-			List<XXTagAttribute> xTagAttributes = daoMgr.getXXTagAttribute().findByTagId(tagId);
-
-			this.service = xService;
-			this.iterTag = xTags.listIterator();
-			this.iterTagAttribute = xTagAttributes.listIterator();
-		}
-
-
-		Map<Long, RangerTag> getAllTags() {
-			Map<Long, RangerTag> ret = new HashMap<Long, RangerTag>();
-
-			while (iterTag.hasNext()) {
-				RangerTag tag = getNextTag();
-
-				if (tag != null) {
-					ret.put(tag.getId(), tag);
-				}
-			}
-
-			if (!hasProcessedAllTags()) {
-				LOG.warn("getAllTags(): perhaps one or more tags got updated during retrieval. Using fallback ... ");
-
-				ret = getTagsBySecondary();
-			}
-
-			return ret;
-		}
-
-		RangerTag getNextTag() {
-			RangerTag ret = null;
-
-			if (iterTag.hasNext()) {
-				XXTag xTag = iterTag.next();
-
-				if (xTag != null) {
-					ret = new RangerTag();
-
-					ret.setId(xTag.getId());
-					ret.setGuid(xTag.getGuid());
-					ret.setOwner(xTag.getOwner());
-					ret.setCreatedBy(lookupCache.getUserScreenName(xTag.getAddedByUserId()));
-					ret.setUpdatedBy(lookupCache.getUserScreenName(xTag.getUpdatedByUserId()));
-					ret.setCreateTime(xTag.getCreateTime());
-					ret.setUpdateTime(xTag.getUpdateTime());
-					ret.setVersion(xTag.getVersion());
-
-					Map<String, String> mapOfOptions = JsonUtils.jsonToMapStringString(xTag.getOptions());
-
-					if (MapUtils.isNotEmpty(mapOfOptions)) {
-						String validityPeriodsStr = mapOfOptions.get(RangerTag.OPTION_TAG_VALIDITY_PERIODS);
-
-						if (StringUtils.isNotEmpty(validityPeriodsStr)) {
-							List<RangerValiditySchedule> validityPeriods = JsonUtils.jsonToRangerValiditySchedule(validityPeriodsStr);
-
-							ret.setValidityPeriods(validityPeriods);
-						}
-					}
-
-					Map<Long, RangerTagDef> tagDefs = getTagDefs();
-					if (tagDefs != null) {
-						RangerTagDef tagDef = tagDefs.get(xTag.getType());
-						if (tagDef != null) {
-							ret.setType(tagDef.getName());
-						}
-					}
-
-					getTagAttributes(ret);
-				}
-			}
-
-			return ret;
-		}
-
-		void getTagAttributes(RangerTag tag) {
-			while (iterTagAttribute.hasNext()) {
-				XXTagAttribute xTagAttribute = iterTagAttribute.next();
-
-				if (xTagAttribute.getTagId().equals(tag.getId())) {
-					String attributeName = xTagAttribute.getName();
-					String attributeValue = xTagAttribute.getValue();
-
-					tag.getAttributes().put(attributeName, attributeValue);
-				} else if (xTagAttribute.getTagId().compareTo(tag.getId()) > 0) {
-					if (iterTagAttribute.hasPrevious()) {
-						iterTagAttribute.previous();
-					}
-					break;
-				}
-			}
-		}
-
-		boolean hasProcessedAllTags() {
-			boolean moreToProcess = iterTagAttribute.hasNext();
-			return !moreToProcess;
-		}
-
-		Map<Long, RangerTag> getTagsBySecondary() {
-			Map<Long, RangerTag> ret = null;
-
-			if (service != null) {
-				List<XXTag> xTags = daoMgr.getXXTag().findByServiceId(service.getId());
-
-				if (CollectionUtils.isNotEmpty(xTags)) {
-					ret = new HashMap<Long, RangerTag>(xTags.size());
-
-					for (XXTag xTag : xTags) {
-						TagRetrieverTagContext ctx = new TagRetrieverTagContext(xTag, service);
-
-						RangerTag tag = ctx.getNextTag();
-
-						if (tag != null) {
-							ret.put(tag.getId(), tag);
-						}
-					}
-				}
-			}
-			return ret;
-		}
-	}
 }
-


[9/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates


Project: http://git-wip-us.apache.org/repos/asf/ranger/repo
Commit: http://git-wip-us.apache.org/repos/asf/ranger/commit/d424b1a8
Tree: http://git-wip-us.apache.org/repos/asf/ranger/tree/d424b1a8
Diff: http://git-wip-us.apache.org/repos/asf/ranger/diff/d424b1a8

Branch: refs/heads/master
Commit: d424b1a8dff7755b646279b10e11976d6ab88ef5
Parents: 64cb80b
Author: Abhay Kulkarni <ak...@hortonworks.com>
Authored: Thu Oct 18 15:22:48 2018 -0700
Committer: Abhay Kulkarni <ak...@hortonworks.com>
Committed: Thu Oct 18 15:22:48 2018 -0700

----------------------------------------------------------------------
 agents-common/pom.xml                           |   12 +
 .../ranger/authorization/utils/JsonUtils.java   |   15 +-
 .../ranger/plugin/model/RangerServiceDef.java   |   42 +-
 .../apache/ranger/plugin/store/TagStore.java    |    2 +
 .../scripts/ranger-admin-services.sh            |   13 +-
 .../optimized/current/ranger_core_db_mysql.sql  |  214 ++--
 .../patches/035-update-schema-for-x-policy.sql  |  200 +++
 .../patches/036-denormalize-tag-tables.sql      |   82 ++
 .../optimized/current/ranger_core_db_oracle.sql |  204 +--
 .../patches/035-update-schema-for-x-policy.sql  |  163 +++
 .../patches/036-denormalize-tag-tables.sql      |   54 +
 .../current/ranger_core_db_postgres.sql         |  226 ++--
 .../patches/035-update-schema-for-x-policy.sql  |  197 +++
 .../patches/036-denormalize-tag-tables.sql      |   79 ++
 .../current/ranger_core_db_sqlanywhere.sql      |  252 ++--
 .../patches/035-update-schema-for-x-policy.sql  |  180 +++
 .../patches/036-denormalize-tag-tables.sql      |   71 ++
 .../current/ranger_core_db_sqlserver.sql        |  510 +++++---
 .../patches/035-update-schema-for-x-policy.sql  |  453 +++++++
 .../patches/036-denormalize-tag-tables.sql      |   97 ++
 security-admin/scripts/db_setup.py              |   31 +-
 .../org/apache/ranger/biz/PolicyRefUpdater.java |  286 +++++
 .../ranger/biz/RangerPolicyRetriever.java       |  604 +++------
 .../apache/ranger/biz/RangerTagDBRetriever.java |  478 ++-----
 .../org/apache/ranger/biz/ServiceDBStore.java   |  642 ++--------
 .../java/org/apache/ranger/biz/TagDBStore.java  |  281 +----
 .../common/RangerServicePoliciesCache.java      |    1 +
 .../apache/ranger/db/RangerDaoManagerBase.java  |   24 +
 .../apache/ranger/db/XXAccessTypeDefDao.java    |    1 -
 .../apache/ranger/db/XXDataMaskTypeDefDao.java  |    1 -
 .../java/org/apache/ranger/db/XXGroupDao.java   |   16 -
 .../ranger/db/XXPolicyConditionDefDao.java      |   28 -
 .../apache/ranger/db/XXPolicyItemAccessDao.java |   25 -
 .../ranger/db/XXPolicyItemConditionDao.java     |   40 -
 .../ranger/db/XXPolicyItemDataMaskInfoDao.java  |   25 -
 .../ranger/db/XXPolicyItemGroupPermDao.java     |   13 -
 .../ranger/db/XXPolicyItemRowFilterInfoDao.java |   13 -
 .../ranger/db/XXPolicyItemUserPermDao.java      |   13 -
 .../ranger/db/XXPolicyRefAccessTypeDao.java     |  100 ++
 .../ranger/db/XXPolicyRefConditionDao.java      |  111 ++
 .../ranger/db/XXPolicyRefDataMaskTypeDao.java   |   86 ++
 .../apache/ranger/db/XXPolicyRefGroupDao.java   |   99 ++
 .../ranger/db/XXPolicyRefResourceDao.java       |   98 ++
 .../apache/ranger/db/XXPolicyRefUserDao.java    |  111 ++
 .../apache/ranger/db/XXPolicyResourceDao.java   |   14 -
 .../ranger/db/XXPolicyResourceMapDao.java       |   13 -
 .../org/apache/ranger/db/XXResourceDefDao.java  |    1 -
 .../apache/ranger/db/XXServiceResourceDao.java  |   36 +-
 .../ranger/db/XXServiceResourceElementDao.java  |   12 -
 .../db/XXServiceResourceElementValueDao.java    |   13 -
 .../org/apache/ranger/db/XXTagAttributeDao.java |   12 -
 .../apache/ranger/db/XXTagAttributeDefDao.java  |   12 -
 .../java/org/apache/ranger/db/XXTagDao.java     |   13 -
 .../java/org/apache/ranger/db/XXTagDefDao.java  |   53 +-
 .../apache/ranger/db/XXTagResourceMapDao.java   |   11 -
 .../java/org/apache/ranger/db/XXUserDao.java    |   20 +-
 .../java/org/apache/ranger/entity/XXDBBase.java |    6 +
 .../org/apache/ranger/entity/XXPolicyBase.java  |   22 +-
 .../ranger/entity/XXPolicyRefAccessType.java    |  191 +++
 .../ranger/entity/XXPolicyRefCondition.java     |  191 +++
 .../ranger/entity/XXPolicyRefDataMaskType.java  |  192 +++
 .../apache/ranger/entity/XXPolicyRefGroup.java  |  206 +++
 .../ranger/entity/XXPolicyRefResource.java      |  191 +++
 .../apache/ranger/entity/XXPolicyRefUser.java   |  191 +++
 .../apache/ranger/entity/XXServiceResource.java |   30 +
 .../java/org/apache/ranger/entity/XXTag.java    |   14 +
 .../java/org/apache/ranger/entity/XXTagDef.java |   14 +
 .../PatchForUpdatingPolicyJson_J10019.java      | 1188 ++++++++++++++++++
 .../patch/PatchForUpdatingTagsJson_J10020.java  |  789 ++++++++++++
 .../org/apache/ranger/rest/ServiceREST.java     |   19 +-
 .../ranger/service/RangerAuditFields.java       |    2 +-
 .../ranger/service/RangerPolicyServiceBase.java |   41 +-
 .../service/RangerServiceDefServiceBase.java    |    2 +-
 .../service/RangerServiceResourceService.java   |  194 +--
 .../RangerServiceResourceServiceBase.java       |   33 +-
 .../ranger/service/RangerTagDefService.java     |   24 +
 .../ranger/service/RangerTagDefServiceBase.java |    2 +-
 .../apache/ranger/service/RangerTagService.java |   53 +-
 .../ranger/service/XPortalUserService.java      |    8 -
 .../resources/META-INF/jpa_named_queries.xml    |  381 +++---
 .../apache/ranger/biz/TestServiceDBStore.java   |  515 ++++----
 .../org/apache/ranger/rest/TestServiceREST.java |    2 +-
 .../ranger/service/TestRangerTagDefService.java |   42 +-
 .../ranger/service/TestRangerTagService.java    |   19 +-
 84 files changed, 7766 insertions(+), 3199 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/agents-common/pom.xml
----------------------------------------------------------------------
diff --git a/agents-common/pom.xml b/agents-common/pom.xml
index 09a32fa..4486af3 100644
--- a/agents-common/pom.xml
+++ b/agents-common/pom.xml
@@ -20,6 +20,18 @@
     <artifactId>ranger-plugins-common</artifactId>
     <name>Common library for Plugins</name>
     <description>Plugins Common</description>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-compiler-plugin</artifactId>
+                <configuration>
+                    <source>8</source>
+                    <target>8</target>
+                </configuration>
+            </plugin>
+        </plugins>
+    </build>
     <packaging>jar</packaging>
     <properties>
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/agents-common/src/main/java/org/apache/ranger/authorization/utils/JsonUtils.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/authorization/utils/JsonUtils.java b/agents-common/src/main/java/org/apache/ranger/authorization/utils/JsonUtils.java
index bc4a8b5..74555ee 100644
--- a/agents-common/src/main/java/org/apache/ranger/authorization/utils/JsonUtils.java
+++ b/agents-common/src/main/java/org/apache/ranger/authorization/utils/JsonUtils.java
@@ -42,7 +42,6 @@ public class JsonUtils {
 
     static {
         gson = new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z")
-                .setPrettyPrinting()
                 .create();
     }
 
@@ -70,6 +69,20 @@ public class JsonUtils {
         return ret;
     }
 
+    public static String objectToJson(Object object) {
+        String ret = null;
+
+        if(object != null) {
+            try {
+                ret = gson.toJson(object);
+            } catch(Exception excp) {
+                LOG.warn("objectToJson() failed to convert object to Json", excp);
+            }
+        }
+
+        return ret;
+    }
+
     public static <T> T jsonToObject(String jsonStr, Class<T> clz) {
         T ret = null;
 

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerServiceDef.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerServiceDef.java b/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerServiceDef.java
index adafb99..50d84a4 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerServiceDef.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerServiceDef.java
@@ -1225,27 +1225,27 @@ public class RangerServiceDef extends RangerBaseModelObject implements java.io.S
 	public static class RangerResourceDef implements java.io.Serializable {
 		private static final long serialVersionUID = 1L;
 
-		private Long                itemId;
-		private String              name;
-		private String              type;
-		private Integer             level;
-		private String              parent;
-		private Boolean             mandatory;
-		private Boolean             lookupSupported;
-		private Boolean             recursiveSupported;
-		private Boolean             excludesSupported;
-		private String              matcher;
-		private Map<String, String> matcherOptions;
-		private String              validationRegEx;
-		private String              validationMessage;
-		private String              uiHint;
-		private String              label;
-		private String              description;
-		private String              rbKeyLabel;
-		private String              rbKeyDescription;
-		private String              rbKeyValidationMessage;
-		private Set<String>         accessTypeRestrictions;
-		private Boolean             isValidLeaf;
+		private Long                itemId                 = null;
+		private String              name                   = null;
+		private String              type                   = null;
+		private Integer             level                  = null;
+		private String              parent                 = null;
+		private Boolean             mandatory              = null;
+		private Boolean             lookupSupported        = null;
+		private Boolean             recursiveSupported     = null;
+		private Boolean             excludesSupported      = null;
+		private String              matcher                = null;
+		private Map<String, String> matcherOptions         = null;
+		private String              validationRegEx        = null;
+		private String              validationMessage      = null;
+		private String              uiHint                 = null;
+		private String              label                  = null;
+		private String              description            = null;
+		private String              rbKeyLabel             = null;
+		private String              rbKeyDescription       = null;
+		private String              rbKeyValidationMessage = null;
+		private Set<String>         accessTypeRestrictions = null;
+		private Boolean             isValidLeaf            = null;
 
 		public RangerResourceDef() {
 			this(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/agents-common/src/main/java/org/apache/ranger/plugin/store/TagStore.java
----------------------------------------------------------------------
diff --git a/agents-common/src/main/java/org/apache/ranger/plugin/store/TagStore.java b/agents-common/src/main/java/org/apache/ranger/plugin/store/TagStore.java
index 5918b12..fe4b278 100644
--- a/agents-common/src/main/java/org/apache/ranger/plugin/store/TagStore.java
+++ b/agents-common/src/main/java/org/apache/ranger/plugin/store/TagStore.java
@@ -84,6 +84,8 @@ public interface TagStore {
 
     RangerServiceResource updateServiceResource(RangerServiceResource resource) throws Exception;
 
+    void refreshServiceResource(Long resourceId) throws Exception;
+
     void deleteServiceResource(Long id) throws Exception;
 
     void deleteServiceResourceByGuid(String guid) throws Exception;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/embeddedwebserver/scripts/ranger-admin-services.sh
----------------------------------------------------------------------
diff --git a/embeddedwebserver/scripts/ranger-admin-services.sh b/embeddedwebserver/scripts/ranger-admin-services.sh
index b8ca6c7..990d3c7 100755
--- a/embeddedwebserver/scripts/ranger-admin-services.sh
+++ b/embeddedwebserver/scripts/ranger-admin-services.sh
@@ -28,11 +28,12 @@ action=`echo $action | tr '[:lower:]' '[:upper:]'`
 realScriptPath=`readlink -f $0`
 realScriptDir=`dirname $realScriptPath`
 XAPOLICYMGR_DIR=`(cd $realScriptDir/..; pwd)`
+max_memory=1g
 
 XAPOLICYMGR_EWS_DIR=${XAPOLICYMGR_DIR}/ews
 RANGER_JAAS_LIB_DIR="${XAPOLICYMGR_EWS_DIR}/ranger_jaas"
 RANGER_JAAS_CONF_DIR="${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/conf/ranger_jaas"
-JAVA_OPTS=" ${JAVA_OPTS} -XX:MaxPermSize=256m -Xmx1024m -Xms1024m "
+JAVA_OPTS=" ${JAVA_OPTS} -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx${max_memory} -Xms1g -Xloggc:${XAPOLICYMGR_EWS_DIR}/logs/gc-worker.log -verbose:gc -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=1m -XX:+PrintGCDetails -XX:+PrintHeapAtGC -XX:+PrintGCDateStamps"
 if [[ ${JAVA_OPTS} != *"-Duser.timezone"* ]] ;then  export JAVA_OPTS=" ${JAVA_OPTS} -Duser.timezone=UTC" ;fi
 if [ -f ${XAPOLICYMGR_DIR}/ews/webapp/WEB-INF/classes/conf/java_home.sh ]; then
         . ${XAPOLICYMGR_DIR}/ews/webapp/WEB-INF/classes/conf/java_home.sh
@@ -145,11 +146,11 @@ stop(){
 }
 
 metric(){
-  if [ "$JAVA_HOME" == "" ]; then
-    echo "[E] JAVA_HOME environment variable not defined, aborting Apache Ranger Admin metric collection" 1>&2;
-    exit 1;
-  fi
-  java ${JAVA_OPTS} -Duser=${USER} -Dhostname=${HOSTNAME} -Dlogdir=${RANGER_ADMIN_LOG_DIR} -cp "${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/conf:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/lib/*:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/META-INF:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/lib/*:${XAPOLICYMGR_EWS_DIR}/webapp/META-INF:${XAPOLICYMGR_EWS_DIR}/lib/*:${RANGER_JAAS_LIB_DIR}/*:${RANGER_JAAS_CONF_DIR}:${JAVA_HOME}/lib/*:${RANGER_HADOOP_CONF_DIR}/*:$CLASSPATH" org.apache.ranger.patch.cliutil.MetricUtil ${arg2} ${arg3} 2>/dev/null
+ if [ "$JAVA_HOME" == "" ]; then
+  echo "[E] JAVA_HOME environment variable not defined, aborting Apache Ranger Admin metric collection"
+  exit 1;
+ fi
+ java ${JAVA_OPTS} -Dlogdir=${RANGER_ADMIN_LOG_DIR} -cp "${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/conf:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/lib/*:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/classes/META-INF:${XAPOLICYMGR_EWS_DIR}/webapp/WEB-INF/lib/*:${XAPOLICYMGR_EWS_DIR}/webapp/META-INF:${XAPOLICYMGR_EWS_DIR}/lib/*:${RANGER_JAAS_LIB_DIR}/*:${RANGER_JAAS_CONF_DIR}:${JAVA_HOME}/lib/*:${RANGER_HADOOP_CONF_DIR}/*:$CLASSPATH" org.apache.ranger.patch.cliutil.MetricUtil ${arg2} ${arg3} 2>/dev/null
 }
 
 if [ "${action}" == "START" ]; then

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/mysql/optimized/current/ranger_core_db_mysql.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/mysql/optimized/current/ranger_core_db_mysql.sql b/security-admin/db/mysql/optimized/current/ranger_core_db_mysql.sql
index 32cf6db..70447fa 100644
--- a/security-admin/db/mysql/optimized/current/ranger_core_db_mysql.sql
+++ b/security-admin/db/mysql/optimized/current/ranger_core_db_mysql.sql
@@ -38,6 +38,10 @@ DROP TABLE IF EXISTS `x_policy_item_access`;
 DROP TABLE IF EXISTS `x_policy_item`;
 DROP TABLE IF EXISTS `x_policy_resource_map`;
 DROP TABLE IF EXISTS `x_policy_resource`;
+DROP TABLE IF EXISTS `x_policy_ref_resource`;
+DROP TABLE IF EXISTS `x_policy_ref_access_type`;
+DROP TABLE IF EXISTS `x_policy_ref_condition`;
+DROP TABLE IF EXISTS `x_policy_ref_datamask_type`;
 DROP TABLE IF EXISTS `x_service_config_map`;
 DROP TABLE IF EXISTS `x_enum_element_def`;
 DROP TABLE IF EXISTS `x_enum_def`;
@@ -58,6 +62,8 @@ DROP TABLE IF EXISTS `x_trx_log`;
 DROP TABLE IF EXISTS `x_resource`;
 DROP TABLE IF EXISTS `x_policy_export_audit`;
 DROP TABLE IF EXISTS `x_group_users`;
+DROP TABLE IF EXISTS `x_policy_ref_user`;
+DROP TABLE IF EXISTS `x_policy_ref_group`;
 DROP TABLE IF EXISTS `x_user`;
 DROP TABLE IF EXISTS `x_group_groups`;
 DROP TABLE IF EXISTS `x_group`;
@@ -574,6 +580,7 @@ CREATE TABLE  `x_policy` (
 `is_audit_enabled` tinyint(1) NOT NULL DEFAULT '0',
 `policy_options` varchar(4000) NULL DEFAULT NULL,
 `policy_priority` int NOT NULL DEFAULT '0',
+`policy_text` MEDIUMTEXT NULL DEFAULT NULL,
 primary key (`id`),
 KEY `x_policy_added_by_id` (`added_by_id`),
 KEY `x_policy_upd_by_id` (`upd_by_id`),
@@ -986,6 +993,7 @@ CREATE TABLE IF NOT EXISTS `x_tag_def` (
 `name` VARCHAR(255) NOT NULL,
 `source` VARCHAR(128) NULL DEFAULT NULL,
 `is_enabled` TINYINT(1) NOT NULL DEFAULT '0',
+`tag_attrs_def_text` MEDIUMTEXT NULL DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `x_tag_def_UK_guid` (`guid`),
 UNIQUE KEY `x_tag_def_UK_name` (`name`),
@@ -1008,6 +1016,7 @@ CREATE TABLE IF NOT EXISTS `x_tag` (
 `type` BIGINT(20) NOT NULL,
 `owned_by` SMALLINT DEFAULT 0 NOT NULL,
 `policy_options` varchar(4000) NULL DEFAULT NULL,
+`tag_attrs_text` MEDIUMTEXT NULL DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `x_tag_UK_guid` (`guid`),
 KEY `x_tag_IDX_type` (`type`),
@@ -1031,6 +1040,8 @@ CREATE TABLE IF NOT EXISTS `x_service_resource` (
 `service_id` BIGINT(20) NOT NULL,
 `resource_signature` varchar(128) NULL DEFAULT NULL,
 `is_enabled` TINYINT NOT NULL DEFAULT '1',
+`service_resource_elements_text` MEDIUMTEXT NULL DEFAULT NULL,
+`tags_text` MEDIUMTEXT NULL DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `x_service_res_UK_guid` (`guid`),
 KEY `x_service_res_IDX_added_by_id` (`added_by_id`),
@@ -1040,67 +1051,6 @@ CONSTRAINT `x_service_res_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES
 CONSTRAINT `x_service_res_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`)
 )ROW_FORMAT=DYNAMIC;
 -- -----------------------------------------------------
--- Table `x_service_resource_element`
--- -----------------------------------------------------
-CREATE TABLE IF NOT EXISTS `x_service_resource_element` (
-`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
-`create_time` DATETIME NULL DEFAULT NULL,
-`update_time` DATETIME NULL DEFAULT NULL,
-`added_by_id` BIGINT(20) NULL DEFAULT NULL,
-`upd_by_id` BIGINT(20) NULL DEFAULT NULL,
-`res_id` BIGINT(20) NOT NULL,
-`res_def_id` BIGINT(20) NOT NULL,
-`is_excludes` TINYINT(1) NOT NULL DEFAULT '0',
-`is_recursive` TINYINT(1) NOT NULL DEFAULT '0',
-PRIMARY KEY (`id`),
-KEY `x_srvc_res_el_IDX_added_by_id` (`added_by_id`),
-KEY `x_srvc_res_el_IDX_upd_by_id` (`upd_by_id`),
-CONSTRAINT `x_srvc_res_el_FK_res_def_id` FOREIGN KEY (`res_def_id`) REFERENCES `x_resource_def` (`id`),
-CONSTRAINT `x_srvc_res_el_FK_res_id` FOREIGN KEY (`res_id`) REFERENCES `x_service_resource` (`id`),
-CONSTRAINT `x_srvc_res_el_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
-CONSTRAINT `x_srvc_res_el_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`)
-)ROW_FORMAT=DYNAMIC;
--- -----------------------------------------------------
--- Table `x_tag_attr_def`
--- -----------------------------------------------------
-CREATE TABLE IF NOT EXISTS `x_tag_attr_def` (
-`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
-`create_time` DATETIME NULL DEFAULT NULL,
-`update_time` DATETIME NULL DEFAULT NULL,
-`added_by_id` BIGINT(20) NULL DEFAULT NULL,
-`upd_by_id` BIGINT(20) NULL DEFAULT NULL,
-`tag_def_id` BIGINT(20) NOT NULL,
-`name` VARCHAR(255) NOT NULL,
-`type` VARCHAR(50) NOT NULL,
-PRIMARY KEY (`id`),
-KEY `x_tag_attr_def_IDX_tag_def_id` (`tag_def_id`),
-KEY `x_tag_attr_def_IDX_added_by_id` (`added_by_id`),
-KEY `x_tag_attr_def_IDX_upd_by_id` (`upd_by_id`),
-CONSTRAINT `x_tag_attr_def_FK_tag_def_id` FOREIGN KEY (`tag_def_id`) REFERENCES `x_tag_def` (`id`),
-CONSTRAINT `x_tag_attr_def_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
-CONSTRAINT `x_tag_attr_def_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`)
-)ROW_FORMAT=DYNAMIC;
--- -----------------------------------------------------
--- Table `x_tag_attr`
--- -----------------------------------------------------
-CREATE TABLE IF NOT EXISTS `x_tag_attr` (
-`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
-`create_time` DATETIME NULL DEFAULT NULL,
-`update_time` DATETIME NULL DEFAULT NULL,
-`added_by_id` BIGINT(20) NULL DEFAULT NULL,
-`upd_by_id` BIGINT(20) NULL DEFAULT NULL,
-`tag_id` BIGINT(20) NOT NULL,
-`name` VARCHAR(255) NOT NULL,
-`value` VARCHAR(512) NULL,
-PRIMARY KEY (`id`),
-KEY `x_tag_attr_IDX_tag_id` (`tag_id`),
-KEY `x_tag_attr_IDX_added_by_id` (`added_by_id`),
-KEY `x_tag_attr_IDX_upd_by_id` (`upd_by_id`),
-CONSTRAINT `x_tag_attr_FK_tag_id` FOREIGN KEY (`tag_id`) REFERENCES `x_tag` (`id`),
-CONSTRAINT `x_tag_attr_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
-CONSTRAINT `x_tag_attr_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`)
-)ROW_FORMAT=DYNAMIC;
--- -----------------------------------------------------
 -- Table `x_tag_resource_map`
 -- -----------------------------------------------------
 CREATE TABLE IF NOT EXISTS `x_tag_resource_map` (
@@ -1123,28 +1073,7 @@ CONSTRAINT `x_tag_res_map_FK_res_id` FOREIGN KEY (`res_id`) REFERENCES `x_servic
 CONSTRAINT `x_tag_res_map_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
 CONSTRAINT `x_tag_res_map_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`)
 )ROW_FORMAT=DYNAMIC;
--- -----------------------------------------------------
--- Table `x_service_resource_element_val`
--- -----------------------------------------------------
-CREATE TABLE IF NOT EXISTS `x_service_resource_element_val` (
-`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
-`create_time` DATETIME NULL DEFAULT NULL,
-`update_time` DATETIME NULL DEFAULT NULL,
-`added_by_id` BIGINT(20) NULL DEFAULT NULL,
-`upd_by_id` BIGINT(20) NULL DEFAULT NULL,
-`res_element_id` BIGINT(20) NOT NULL,
-`value` VARCHAR(1024) NOT NULL,
-`sort_order` tinyint(3) NULL DEFAULT '0',
-PRIMARY KEY (`id`),
-KEY `x_srvc_res_el_val_IDX_resel_id` (`res_element_id`),
-KEY `x_srvc_res_el_val_IDX_addby_id` (`added_by_id`),
-KEY `x_srvc_res_el_val_IDX_updby_id` (`upd_by_id`),
-CONSTRAINT `x_srvc_res_el_val_FK_res_el_id` FOREIGN KEY (`res_element_id`) REFERENCES `x_service_resource_element` (`id`),
-CONSTRAINT `x_srvc_res_el_val_FK_add_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
-CONSTRAINT `x_srvc_res_el_val_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`)
-)ROW_FORMAT=DYNAMIC;
 INSERT INTO `x_modules_master` VALUES (6,now(),now(),1,1,'Tag Based Policies','');
-
 CREATE TABLE `x_datamask_type_def` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT ,
 `guid` varchar(64) NULL DEFAULT NULL,
@@ -1267,6 +1196,120 @@ CONSTRAINT `x_policy_label_map_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCE
 CONSTRAINT `x_policy_label_map_FK_policy_label_id` FOREIGN KEY (`policy_label_id`) REFERENCES `x_policy_label` (`id`)
 )ROW_FORMAT=DYNAMIC;
 
+DROP TABLE IF EXISTS `x_policy_ref_resource`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_resource` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `resource_def_id` bigint(20) NOT NULL,
+  `resource_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_res_UK_polId_resDefId`(`policy_id`, `resource_def_id`),
+  CONSTRAINT `x_policy_ref_res_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_res_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_res_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_res_FK_resource_def_id` FOREIGN KEY (`resource_def_id`) REFERENCES `x_resource_def` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+DROP TABLE IF EXISTS `x_policy_ref_access_type`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_access_type` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `access_def_id` bigint(20) NOT NULL,
+  `access_type_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_access_UK_polId_accessDefId`(`policy_id`, `access_def_id`),
+  CONSTRAINT `x_policy_ref_access_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_access_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_access_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_access_FK_access_def_id` FOREIGN KEY (`access_def_id`) REFERENCES `x_access_type_def` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+DROP TABLE IF EXISTS `x_policy_ref_condition`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_condition` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `condition_def_id` bigint(20) NOT NULL,
+  `condition_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_condition_UK_polId_condDefId`(`policy_id`, `condition_def_id`),
+  CONSTRAINT `x_policy_ref_condition_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_condition_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_condition_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_condition_FK_condition_def_id` FOREIGN KEY (`condition_def_id`) REFERENCES `x_policy_condition_def` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+DROP TABLE IF EXISTS `x_policy_ref_datamask_type`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_datamask_type` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `datamask_def_id` bigint(20) NOT NULL,
+  `datamask_type_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_datamask_UK_polId_dmaskDefId`(`policy_id`, `datamask_def_id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_datamask_def_id` FOREIGN KEY (`datamask_def_id`) REFERENCES `x_datamask_type_def` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+DROP TABLE IF EXISTS `x_policy_ref_user`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_user` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `user_id` bigint(20) NOT NULL,
+  `user_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_user_UK_polId_userId`(`policy_id`, `user_id`),
+  CONSTRAINT `x_policy_ref_user_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_user_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_user_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_user_FK_user_id` FOREIGN KEY (`user_id`) REFERENCES `x_user` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+DROP TABLE IF EXISTS `x_policy_ref_group`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_group` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `group_id` bigint(20) NOT NULL,
+  `group_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_group_UK_polId_groupId`(`policy_id`, `group_id`),
+  CONSTRAINT `x_policy_ref_group_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_group_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_group_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_group_FK_group_id` FOREIGN KEY (`group_id`) REFERENCES `x_group` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
 CREATE INDEX x_service_config_def_IDX_def_id ON x_service_config_def(def_id);
 CREATE INDEX x_resource_def_IDX_def_id ON x_resource_def(def_id);
 CREATE INDEX x_access_type_def_IDX_def_id ON x_access_type_def(def_id);
@@ -1288,8 +1331,6 @@ CREATE INDEX x_policy_item_user_perm_IDX_user_id ON x_policy_item_user_perm(user
 CREATE INDEX x_policy_item_group_perm_IDX_policy_item_id ON x_policy_item_group_perm(policy_item_id);
 CREATE INDEX x_policy_item_group_perm_IDX_group_id ON x_policy_item_group_perm(group_id);
 CREATE INDEX x_service_resource_IDX_service_id ON x_service_resource(service_id);
-CREATE INDEX x_service_resource_element_IDX_res_id ON x_service_resource_element(res_id);
-CREATE INDEX x_service_resource_element_IDX_res_def_id ON x_service_resource_element(res_def_id);
 CREATE INDEX x_datamask_type_def_IDX_def_id ON x_datamask_type_def(def_id);
 CREATE INDEX x_policy_item_datamask_IDX_policy_item_id ON x_policy_item_datamask(policy_item_id);
 CREATE INDEX x_policy_item_rowfilter_IDX_policy_item_id ON x_policy_item_rowfilter(policy_item_id);
@@ -1346,6 +1387,8 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('032',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('033',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('034',UTC_TIMESTAMP(),'Ranger 2.0.0',UTC_TIMESTAMP(),'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('035',UTC_TIMESTAMP(),'Ranger 2.0.0',UTC_TIMESTAMP(),'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('036',UTC_TIMESTAMP(),'Ranger 2.0.0',UTC_TIMESTAMP(),'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('DB_PATCHES',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
 INSERT INTO x_user_module_perm (user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (1,3,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,1,1);
 INSERT INTO x_user_module_perm (user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (1,1,UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,1,1);
@@ -1383,5 +1426,6 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10014',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10015',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10016',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
-INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10018',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10019',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10020',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('JAVA_PATCHES',UTC_TIMESTAMP(),'Ranger 1.0.0',UTC_TIMESTAMP(),'localhost','Y');

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/mysql/patches/035-update-schema-for-x-policy.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/mysql/patches/035-update-schema-for-x-policy.sql b/security-admin/db/mysql/patches/035-update-schema-for-x-policy.sql
new file mode 100644
index 0000000..ee82ae3
--- /dev/null
+++ b/security-admin/db/mysql/patches/035-update-schema-for-x-policy.sql
@@ -0,0 +1,200 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+drop procedure if exists alter_table_x_policy;
+
+delimiter ;;
+create procedure alter_table_x_policy() begin
+
+if exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_policy') then
+  if not exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_policy' and column_name = 'policy_text') then
+    ALTER TABLE `x_policy` ADD `policy_text` MEDIUMTEXT DEFAULT NULL;
+  end if;
+ end if; 
+end;;
+
+delimiter ;
+call alter_table_x_policy();
+
+drop procedure if exists alter_table_x_policy;
+
+DROP PROCEDURE IF EXISTS removeConstraints;
+DELIMITER ;;
+CREATE PROCEDURE removeConstraints(vTableName varchar(128))
+BEGIN
+  DECLARE done INT DEFAULT FALSE;
+  DECLARE cName VARCHAR(64);
+  DECLARE cur CURSOR FOR
+          SELECT DISTINCT CONSTRAINT_NAME
+          FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
+          WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME = vTableName
+          AND REFERENCED_TABLE_NAME IS NOT NULL;
+  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+  SET AUTOCOMMIT=0;
+  SET FOREIGN_KEY_CHECKS=0;
+
+  OPEN cur;
+
+  read_loop: LOOP
+    FETCH cur INTO cName;
+    IF done THEN
+      LEAVE read_loop;
+    END IF;
+    SET @sql = CONCAT('ALTER TABLE ',vTableName,' DROP FOREIGN KEY ',cName,';');
+    PREPARE stmt FROM @sql;
+    EXECUTE stmt;
+    DEALLOCATE PREPARE stmt;
+  END LOOP;
+
+  CLOSE cur;
+
+  SET FOREIGN_KEY_CHECKS=1;
+  COMMIT;
+  SET AUTOCOMMIT=1;
+END ;;
+DELIMITER ;
+
+call removeConstraints('x_policy_item');
+call removeConstraints('x_policy_item_access');
+call removeConstraints('x_policy_item_condition');
+call removeConstraints('x_policy_item_datamask');
+call removeConstraints('x_policy_item_group_perm');
+call removeConstraints('x_policy_item_user_perm');
+call removeConstraints('x_policy_item_rowfilter');
+call removeConstraints('x_policy_resource');
+call removeConstraints('x_policy_resource_map');
+
+
+DROP PROCEDURE removeConstraints;
+
+DROP TABLE IF EXISTS `x_policy_ref_resource`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_resource` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `resource_def_id` bigint(20) NOT NULL,
+  `resource_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_res_UK_polId_resDefId`(`policy_id`, `resource_def_id`),
+  CONSTRAINT `x_policy_ref_res_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_res_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_res_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_res_FK_resource_def_id` FOREIGN KEY (`resource_def_id`) REFERENCES `x_resource_def` (`id`)
+
+) ROW_FORMAT=DYNAMIC;
+
+
+DROP TABLE IF EXISTS `x_policy_ref_access_type`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_access_type` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `access_def_id` bigint(20) NOT NULL,
+  `access_type_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_access_UK_polId_accessDefId`(`policy_id`, `access_def_id`),
+  CONSTRAINT `x_policy_ref_access_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_access_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_access_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_access_FK_access_def_id` FOREIGN KEY (`access_def_id`) REFERENCES `x_access_type_def` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+
+DROP TABLE IF EXISTS `x_policy_ref_condition`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_condition` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `condition_def_id` bigint(20) NOT NULL,
+  `condition_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_condition_UK_polId_condDefId`(`policy_id`, `condition_def_id`),
+  CONSTRAINT `x_policy_ref_condition_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_condition_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_condition_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_condition_FK_condition_def_id` FOREIGN KEY (`condition_def_id`) REFERENCES `x_policy_condition_def` (`id`)
+  
+) ROW_FORMAT=DYNAMIC;
+
+DROP TABLE IF EXISTS `x_policy_ref_datamask_type`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_datamask_type` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `datamask_def_id` bigint(20) NOT NULL,
+  `datamask_type_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_datamask_UK_polId_dmaskDefId`(`policy_id`, `datamask_def_id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_datamask_FK_datamask_def_id` FOREIGN KEY (`datamask_def_id`) REFERENCES `x_datamask_type_def` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+DROP TABLE IF EXISTS `x_policy_ref_user`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_user` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `user_id` bigint(20) NOT NULL,
+  `user_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_user_UK_polId_userId`(`policy_id`, `user_id`),
+  CONSTRAINT `x_policy_ref_user_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_user_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_user_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_user_FK_user_id` FOREIGN KEY (`user_id`) REFERENCES `x_user` (`id`)
+) ROW_FORMAT=DYNAMIC;
+
+
+DROP TABLE IF EXISTS `x_policy_ref_group`;
+CREATE TABLE IF NOT EXISTS `x_policy_ref_group` (
+  `id` bigint(20) NOT NULL AUTO_INCREMENT,
+  `guid` varchar(1024) DEFAULT NULL,
+  `create_time` datetime DEFAULT NULL,
+  `update_time` datetime DEFAULT NULL,
+  `added_by_id` bigint(20) DEFAULT NULL,
+  `upd_by_id` bigint(20) DEFAULT NULL,
+  `policy_id` bigint(20) NOT NULL,
+  `group_id` bigint(20) NOT NULL,
+  `group_name` varchar(4000) DEFAULT NULL,
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `x_policy_ref_group_UK_polId_groupId`(`policy_id`, `group_id`),
+  CONSTRAINT `x_policy_ref_group_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_group_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES `x_portal_user` (`id`),
+  CONSTRAINT `x_policy_ref_group_FK_policy_id` FOREIGN KEY (`policy_id`) REFERENCES `x_policy` (`id`),
+  CONSTRAINT `x_policy_ref_group_FK_group_id` FOREIGN KEY (`group_id`) REFERENCES `x_group` (`id`)
+) ROW_FORMAT=DYNAMIC;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/mysql/patches/036-denormalize-tag-tables.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/mysql/patches/036-denormalize-tag-tables.sql b/security-admin/db/mysql/patches/036-denormalize-tag-tables.sql
new file mode 100644
index 0000000..63035bc
--- /dev/null
+++ b/security-admin/db/mysql/patches/036-denormalize-tag-tables.sql
@@ -0,0 +1,82 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+drop procedure if exists denormalize_tag_tables;
+
+delimiter ;;
+create procedure denormalize_tag_tables() begin
+
+if not exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_tag_def' and column_name='tag_attrs_def_text') then
+        ALTER TABLE x_tag_def ADD tag_attrs_def_text MEDIUMTEXT NULL DEFAULT NULL;
+end if;
+if not exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_tag' and column_name='tag_attrs_text') then
+        ALTER TABLE x_tag ADD tag_attrs_text MEDIUMTEXT NULL DEFAULT NULL;
+end if;
+if not exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_service_resource' and column_name='service_resource_elements_text') then
+        ALTER TABLE x_service_resource ADD service_resource_elements_text MEDIUMTEXT NULL DEFAULT NULL;
+end if;
+if not exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_service_resource' and column_name='tags_text') then
+        ALTER TABLE x_service_resource ADD tags_text MEDIUMTEXT NULL DEFAULT NULL;
+end if;
+end;;
+
+delimiter ;
+call denormalize_tag_tables();
+
+drop procedure if exists denormalize_tag_tables;
+
+DROP PROCEDURE IF EXISTS removeConstraints;
+DELIMITER ;;
+CREATE PROCEDURE removeConstraints(vTableName varchar(128))
+BEGIN
+  DECLARE done INT DEFAULT FALSE;
+  DECLARE cName VARCHAR(64);
+  DECLARE cur CURSOR FOR
+          SELECT DISTINCT CONSTRAINT_NAME
+          FROM INFORMATION_SCHEMA.Key_COLUMN_USAGE
+          WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME = vTableName
+          AND REFERENCED_TABLE_NAME IS NOT NULL;
+  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
+
+  SET AUTOCOMMIT=0;
+  SET FOREIGN_KEY_CHECKS=0;
+
+  OPEN cur;
+
+  read_loop: LOOP
+    FETCH cur INTO cName;
+    IF done THEN
+      LEAVE read_loop;
+    END IF;
+    SET @sql = CONCAT('ALTER TABLE ',vTableName,' DROP FOREIGN KEY ',cName,';');
+    PREPARE stmt FROM @sql;
+    EXECUTE stmt;
+    DEALLOCATE PREPARE stmt;
+  END LOOP;
+
+  CLOSE cur;
+
+  SET FOREIGN_KEY_CHECKS=1;
+  COMMIT;
+  SET AUTOCOMMIT=1;
+END ;;
+DELIMITER ;
+
+call removeConstraints('x_tag_attr_def');
+call removeConstraints('x_tag_attr');
+call removeConstraints('x_service_resource_element');
+call removeConstraints('x_service_resource_element_val');
+
+DROP PROCEDURE removeConstraints;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/oracle/optimized/current/ranger_core_db_oracle.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/oracle/optimized/current/ranger_core_db_oracle.sql b/security-admin/db/oracle/optimized/current/ranger_core_db_oracle.sql
index 2e577f3..8b51307 100644
--- a/security-admin/db/oracle/optimized/current/ranger_core_db_oracle.sql
+++ b/security-admin/db/oracle/optimized/current/ranger_core_db_oracle.sql
@@ -52,6 +52,12 @@ CREATE SEQUENCE X_POLICY_ITEM_CONDITION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE
 CREATE SEQUENCE X_CONTEXT_ENRICHER_DEF_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_POLICY_ITEM_USER_PERM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_POLICY_ITEM_GROUP_PERM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_RESOURCE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_ACCESS_TYPE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_CONDITION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_DATAMASK_TYPE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_USER_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_GROUP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_DATA_HIST_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_MODULES_MASTER_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_USER_MODULE_PERM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
@@ -59,11 +65,7 @@ CREATE SEQUENCE X_GROUP_MODULE_PERM_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCY
 CREATE SEQUENCE X_TAG_DEF_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_TAG_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_SERVICE_RESOURCE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
-CREATE SEQUENCE X_SERVICE_RESOURCE_ELEMENT_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
-CREATE SEQUENCE X_TAG_ATTR_DEF_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
-CREATE SEQUENCE X_TAG_ATTR_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_TAG_RESOURCE_MAP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
-CREATE SEQUENCE X_SERVICE_RES_EL_VAL_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_DATAMASK_TYPE_DEF_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_POLICY_ITEM_DATAMASK_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
 CREATE SEQUENCE X_POLICY_ITEM_ROWFILTER_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
@@ -458,6 +460,7 @@ is_enabled NUMBER(1) DEFAULT '0' NOT NULL,
 is_audit_enabled NUMBER(1) DEFAULT '0' NOT NULL,
 policy_options varchar(4000) DEFAULT NULL NULL,
 policy_priority NUMBER(11) DEFAULT 0 NOT NULL,
+policy_text CLOB DEFAULT NULL NULL,
 primary key (id),
 CONSTRAINT x_policy_UK_name_service UNIQUE (name,service),
 CONSTRAINT x_policy_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
@@ -860,6 +863,7 @@ version NUMBER(20) DEFAULT NULL NULL,
 name VARCHAR(255) NOT NULL,
 source VARCHAR(128) DEFAULT NULL NULL,
 is_enabled NUMBER(1) DEFAULT '0' NOT NULL,
+TAG_ATTRS_DEF_TEXT CLOB DEFAULT NULL NULL,
 PRIMARY KEY (id),
 CONSTRAINT x_tag_def_UK_guid UNIQUE (guid),
 CONSTRAINT x_tag_def_UK_name UNIQUE (name),
@@ -878,6 +882,7 @@ version NUMBER(20) DEFAULT NULL NULL,
 type NUMBER(20) NOT NULL,
 owned_by NUMBER(6) DEFAULT 0 NOT NULL,
 policy_options varchar(4000) DEFAULT NULL NULL,
+TAG_ATTRS_TEXT CLOB DEFAULT NULL NULL,
 primary key (id),
 CONSTRAINT x_tag_UK_guid UNIQUE (guid),
 CONSTRAINT x_tag_FK_type FOREIGN KEY (type) REFERENCES x_tag_def (id),
@@ -896,6 +901,8 @@ version NUMBER(20) DEFAULT NULL NULL,
 service_id NUMBER(20) NOT NULL,
 resource_signature VARCHAR(128) DEFAULT NULL NULL,
 is_enabled NUMBER(1) DEFAULT '1' NOT NULL,
+SERVICE_RESOURCE_ELEMENTS_TEXT CLOB DEFAULT NULL NULL,
+TAGS_TEXT CLOB DEFAULT NULL NULL,
 primary key (id),
 CONSTRAINT x_service_res_UK_guid UNIQUE (guid),
 CONSTRAINT x_service_res_FK_service_id FOREIGN KEY (service_id) REFERENCES x_service (id),
@@ -903,53 +910,6 @@ CONSTRAINT x_service_res_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_p
 CONSTRAINT x_service_res_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
 );
 
-CREATE TABLE x_service_resource_element(
-id NUMBER(20) NOT NULL,
-create_time DATE DEFAULT NULL NULL,
-update_time DATE DEFAULT NULL NULL,
-added_by_id NUMBER(20) DEFAULT NULL NULL,
-upd_by_id NUMBER(20) DEFAULT NULL NULL,
-res_id NUMBER(20) NOT NULL,
-res_def_id NUMBER(20) NOT NULL,
-is_excludes NUMBER(1) DEFAULT '0' NOT NULL,
-is_recursive NUMBER(1) DEFAULT '0' NOT NULL,
-primary key (id),
-CONSTRAINT x_srvc_res_el_FK_res_def_id FOREIGN KEY (res_def_id) REFERENCES x_resource_def (id),
-CONSTRAINT x_srvc_res_el_FK_res_id FOREIGN KEY (res_id) REFERENCES x_service_resource (id),
-CONSTRAINT x_srvc_res_el_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_srvc_res_el_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
-
-CREATE TABLE x_tag_attr_def(
-id NUMBER(20) NOT NULL,
-create_time DATE DEFAULT NULL NULL,
-update_time DATE DEFAULT NULL NULL,
-added_by_id NUMBER(20) DEFAULT NULL NULL,
-upd_by_id NUMBER(20) DEFAULT NULL NULL,
-tag_def_id NUMBER(20) NOT NULL,
-name VARCHAR(255) NOT NULL,
-type VARCHAR(50) NOT NULL,
-primary key (id),
-CONSTRAINT x_tag_attr_def_FK_tag_def_id FOREIGN KEY (tag_def_id) REFERENCES x_tag_def (id),
-CONSTRAINT x_tag_attr_def_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_tag_attr_def_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
-
-CREATE TABLE x_tag_attr(
-id NUMBER(20) NOT NULL,
-create_time DATE DEFAULT NULL NULL,
-update_time DATE DEFAULT NULL NULL,
-added_by_id NUMBER(20) DEFAULT NULL NULL,
-upd_by_id NUMBER(20) DEFAULT NULL NULL,
-tag_id NUMBER(20) NOT NULL,
-name VARCHAR(255) NOT NULL,
-value VARCHAR(512) DEFAULT NULL NULL,
-primary key (id),
-CONSTRAINT x_tag_attr_FK_tag_id FOREIGN KEY (tag_id) REFERENCES x_tag (id),
-CONSTRAINT x_tag_attr_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_tag_attr_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
-
 CREATE TABLE x_tag_resource_map(
 id NUMBER(20) NOT NULL,
 guid VARCHAR(64) NOT NULL,
@@ -967,20 +927,6 @@ CONSTRAINT x_tag_res_map_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_p
 CONSTRAINT x_tag_res_map_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
 );
 
-CREATE TABLE x_service_resource_element_val(
-id NUMBER(20) NOT NULL,
-create_time DATE DEFAULT NULL NULL,
-update_time DATE DEFAULT NULL NULL,
-added_by_id NUMBER(20) DEFAULT NULL NULL,
-upd_by_id NUMBER(20) DEFAULT NULL NULL,
-res_element_id NUMBER(20) NOT NULL,
-value VARCHAR(1024) NOT NULL,
-sort_order NUMBER(3) DEFAULT '0' NULL,
-primary key (id),
-CONSTRAINT x_srvc_res_el_val_FK_res_el_id FOREIGN KEY (res_element_id) REFERENCES x_service_resource_element (id),
-CONSTRAINT x_srvc_res_el_val_FK_add_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_srvc_res_el_val_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
 INSERT INTO x_modules_master VALUES(X_MODULES_MASTER_SEQ.NEXTVAL,SYSDATE,SYSDATE,1,1,'Tag Based Policies','');
 commit;
 
@@ -1115,6 +1061,115 @@ session_id VARCHAR(255) DEFAULT NULL,
 );
 commit;
 
+CREATE TABLE x_policy_ref_resource (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+resource_def_id NUMBER(20) NOT NULL,
+resource_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_res_UK_polId_resDefId UNIQUE (policy_id, resource_def_id),
+CONSTRAINT x_p_ref_res_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_res_FK_resource_def_id FOREIGN KEY (resource_def_id) REFERENCES x_resource_def (id),
+CONSTRAINT x_p_ref_res_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_res_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_access_type (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+access_def_id NUMBER(20) NOT NULL,
+access_type_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_acc_UK_polId_accDefId UNIQUE(policy_id, access_def_id),
+CONSTRAINT x_p_ref_acc_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_acc_FK_acc_def_id FOREIGN KEY (access_def_id) REFERENCES x_access_type_def (id),
+CONSTRAINT x_p_ref_acc_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_acc_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_condition (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+condition_def_id NUMBER(20) NOT NULL,
+condition_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_cond_UK_polId_cDefId UNIQUE(policy_id, condition_def_id),
+CONSTRAINT x_p_ref_cond_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_cond_FK_cond_def_id FOREIGN KEY (condition_def_id) REFERENCES x_policy_condition_def (id),
+CONSTRAINT x_p_ref_cond_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_cond_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_datamask_type (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+datamask_def_id NUMBER(20) NOT NULL,
+datamask_type_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_dmsk_UK_polId_dDefId UNIQUE(policy_id, datamask_def_id),
+CONSTRAINT x_p_ref_dmsk_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_dmsk_FK_dmk_def_id FOREIGN KEY (datamask_def_id) REFERENCES x_datamask_type_def (id),
+CONSTRAINT x_p_ref_dmsk_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_dmsk_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_user (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+user_id NUMBER(20) NOT NULL,
+user_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_usr_UK_polId_userId UNIQUE(policy_id, user_id),
+CONSTRAINT x_p_ref_usr_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_usr_FK_user_id FOREIGN KEY (user_id) REFERENCES x_user (id),
+CONSTRAINT x_p_ref_usr_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_usr_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_group (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+group_id NUMBER(20) NOT NULL,
+group_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_grp_UK_polId_grpId UNIQUE(policy_id, group_id),
+CONSTRAINT x_p_ref_grp_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_grp_FK_group_id FOREIGN KEY (group_id) REFERENCES x_group (id),
+CONSTRAINT x_p_ref_grp_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_grp_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+
 CREATE VIEW vx_trx_log AS select x_trx_log.id AS id,x_trx_log.create_time AS create_time,x_trx_log.update_time AS update_time,x_trx_log.added_by_id AS added_by_id,x_trx_log.upd_by_id AS upd_by_id,x_trx_log.class_type AS class_type,x_trx_log.object_id AS object_id,x_trx_log.parent_object_id AS parent_object_id,x_trx_log.parent_object_class_type AS parent_object_class_type,x_trx_log.attr_name AS attr_name,x_trx_log.parent_object_name AS parent_object_name,x_trx_log.object_name AS object_name,x_trx_log.prev_val AS prev_val,x_trx_log.new_val AS new_val,x_trx_log.trx_id AS trx_id,x_trx_log.action AS action,x_trx_log.sess_id AS sess_id,x_trx_log.req_id AS req_id,x_trx_log.sess_type AS sess_type from x_trx_log  where id in(select min(x_trx_log.id) from x_trx_log group by x_trx_log.trx_id);
 commit;
 
@@ -1227,21 +1282,10 @@ CREATE INDEX x_tag_IDX_added_by_id ON x_tag(added_by_id);
 CREATE INDEX x_tag_IDX_upd_by_id ON x_tag(upd_by_id);
 CREATE INDEX x_service_res_IDX_added_by_id ON x_service_resource(added_by_id);
 CREATE INDEX x_service_res_IDX_upd_by_id ON x_service_resource(upd_by_id);
-CREATE INDEX x_srvc_res_el_IDX_added_by_id ON x_service_resource_element(added_by_id);
-CREATE INDEX x_srvc_res_el_IDX_upd_by_id ON x_service_resource_element(upd_by_id);
-CREATE INDEX x_tag_attr_def_IDX_tag_def_id ON x_tag_attr_def(tag_def_id);
-CREATE INDEX x_tag_attr_def_IDX_added_by_id ON x_tag_attr_def(added_by_id);
-CREATE INDEX x_tag_attr_def_IDX_upd_by_id ON x_tag_attr_def(upd_by_id);
-CREATE INDEX x_tag_attr_IDX_tag_id ON x_tag_attr(tag_id);
-CREATE INDEX x_tag_attr_IDX_added_by_id ON x_tag_attr(added_by_id);
-CREATE INDEX x_tag_attr_IDX_upd_by_id ON x_tag_attr(upd_by_id);
 CREATE INDEX x_tag_res_map_IDX_tag_id ON x_tag_resource_map(tag_id);
 CREATE INDEX x_tag_res_map_IDX_res_id ON x_tag_resource_map(res_id);
 CREATE INDEX x_tag_res_map_IDX_added_by_id ON x_tag_resource_map(added_by_id);
 CREATE INDEX x_tag_res_map_IDX_upd_by_id ON x_tag_resource_map(upd_by_id);
-CREATE INDEX x_srvc_res_el_val_IDX_resel_id ON x_service_resource_element_val(res_element_id);
-CREATE INDEX x_srvc_res_el_val_IDX_addby_id ON x_service_resource_element_val(added_by_id);
-CREATE INDEX x_srvc_res_el_val_IDX_updby_id ON x_service_resource_element_val(upd_by_id);
 CREATE INDEX x_service_conf_def_IDX_defid ON x_service_config_def(def_id);
 CREATE INDEX x_resource_def_IDX_def_id ON x_resource_def(def_id);
 CREATE INDEX x_access_type_def_IDX_def_id ON x_access_type_def(def_id);
@@ -1263,8 +1307,6 @@ CREATE INDEX x_plc_itm_usr_perm_IDX_user_id ON x_policy_item_user_perm(user_id);
 CREATE INDEX x_plc_itm_grp_perm_IDX_pi_id ON x_policy_item_group_perm(policy_item_id);
 CREATE INDEX x_plc_itm_grp_perm_IDX_grp_id ON x_policy_item_group_perm(group_id);
 CREATE INDEX x_srvc_res_IDX_service_id ON x_service_resource(service_id);
-CREATE INDEX x_srvc_res_el_IDX_res_def_id ON x_service_resource_element(res_id);
-CREATE INDEX x_srvc_res_el_IDX_res_id ON x_service_resource_element(res_def_id);
 CREATE INDEX x_dm_type_def_IDX_def_id ON x_datamask_type_def(def_id);
 CREATE INDEX x_plc_item_dm_IDX_plc_item_id ON x_policy_item_datamask(policy_item_id);
 CREATE INDEX x_plc_item_rf_IDX_plc_item_id ON x_policy_item_rowfilter(policy_item_id);
@@ -1321,6 +1363,9 @@ INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,act
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval, '031',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval, '032',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval, '033',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
+INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval, '034',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
+INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval, '035',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
+INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval, '036',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval, 'DB_PATCHES',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 INSERT INTO x_user_module_perm (id,user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (X_USER_MODULE_PERM_SEQ.nextval,1,3,sys_extract_utc(systimestamp),sys_extract_utc(systimestamp),1,1,1);
 INSERT INTO x_user_module_perm (id,user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (X_USER_MODULE_PERM_SEQ.nextval,1,1,sys_extract_utc(systimestamp),sys_extract_utc(systimestamp),1,1,1);
@@ -1358,6 +1403,7 @@ INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,act
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval,'J10014',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval,'J10015',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval,'J10016',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
-INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval,'J10018',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
+INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval,'J10019',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
+INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval,'J10020',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 INSERT INTO x_db_version_h (id,version,inst_at,inst_by,updated_at,updated_by,active) VALUES (X_DB_VERSION_H_SEQ.nextval,'JAVA_PATCHES',sys_extract_utc(systimestamp),'Ranger 1.0.0',sys_extract_utc(systimestamp),'localhost','Y');
 commit;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/oracle/patches/035-update-schema-for-x-policy.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/oracle/patches/035-update-schema-for-x-policy.sql b/security-admin/db/oracle/patches/035-update-schema-for-x-policy.sql
new file mode 100644
index 0000000..11b4172
--- /dev/null
+++ b/security-admin/db/oracle/patches/035-update-schema-for-x-policy.sql
@@ -0,0 +1,163 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+/
+CREATE SEQUENCE X_POLICY_REF_RESOURCE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_ACCESS_TYPE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_CONDITION_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_DATAMASK_TYPE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_USER_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+CREATE SEQUENCE X_POLICY_REF_GROUP_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;
+commit;
+CREATE TABLE x_policy_ref_resource (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+resource_def_id NUMBER(20) NOT NULL,
+resource_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_res_UK_polId_resDefId UNIQUE (policy_id, resource_def_id),
+CONSTRAINT x_p_ref_res_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_res_FK_resource_def_id FOREIGN KEY (resource_def_id) REFERENCES x_resource_def (id),
+CONSTRAINT x_p_ref_res_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_res_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_access_type (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+access_def_id NUMBER(20) NOT NULL,
+access_type_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_acc_UK_polId_accDefId UNIQUE(policy_id, access_def_id),
+CONSTRAINT x_p_ref_acc_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_acc_FK_acc_def_id FOREIGN KEY (access_def_id) REFERENCES x_access_type_def (id),
+CONSTRAINT x_p_ref_acc_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_acc_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_condition (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+condition_def_id NUMBER(20) NOT NULL,
+condition_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_cond_UK_polId_cDefId UNIQUE(policy_id, condition_def_id),
+CONSTRAINT x_p_ref_cond_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_cond_FK_cond_def_id FOREIGN KEY (condition_def_id) REFERENCES x_policy_condition_def (id),
+CONSTRAINT x_p_ref_cond_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_cond_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_datamask_type (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+datamask_def_id NUMBER(20) NOT NULL,
+datamask_type_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_dmsk_UK_polId_dDefId UNIQUE(policy_id, datamask_def_id),
+CONSTRAINT x_p_ref_dmsk_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_dmsk_FK_dmk_def_id FOREIGN KEY (datamask_def_id) REFERENCES x_datamask_type_def (id),
+CONSTRAINT x_p_ref_dmsk_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_dmsk_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_user (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+user_id NUMBER(20) NOT NULL,
+user_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_usr_UK_polId_userId UNIQUE(policy_id, user_id),
+CONSTRAINT x_p_ref_usr_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_usr_FK_user_id FOREIGN KEY (user_id) REFERENCES x_user (id),
+CONSTRAINT x_p_ref_usr_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_usr_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+CREATE TABLE x_policy_ref_group (
+id NUMBER(20) NOT NULL,
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time DATE DEFAULT NULL NULL,
+update_time DATE DEFAULT NULL NULL,
+added_by_id NUMBER(20) DEFAULT NULL NULL,
+upd_by_id NUMBER(20) DEFAULT NULL NULL,
+policy_id NUMBER(20) NOT NULL,
+group_id NUMBER(20) NOT NULL,
+group_name VARCHAR(4000) DEFAULT NULL NULL,
+primary key (id),
+CONSTRAINT x_p_ref_grp_UK_polId_grpId UNIQUE(policy_id, group_id),
+CONSTRAINT x_p_ref_grp_FK_policy_id FOREIGN KEY (policy_id) REFERENCES x_policy (id),
+CONSTRAINT x_p_ref_grp_FK_group_id FOREIGN KEY (group_id) REFERENCES x_group (id),
+CONSTRAINT x_p_ref_grp_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
+CONSTRAINT x_p_ref_grp_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
+);
+commit;
+DECLARE
+	v_column_exists number := 0;
+BEGIN
+Select count(*) into v_column_exists from user_tab_cols where column_name = upper('policy_text') and table_name = upper('x_policy');
+	if (v_column_exists = 0) then
+		execute immediate 'ALTER TABLE x_policy ADD policy_text CLOB DEFAULT NULL NULL';
+		commit;
+	end if;
+end;/
+
+CREATE OR REPLACE PROCEDURE removeConstraints(ObjName IN varchar2) IS
+BEGIN
+FOR rec IN(
+select owner, constraint_name
+from all_constraints
+where owner = sys_context('userenv','current_schema')
+and table_name = ObjName
+and constraint_type = 'R')
+LOOP
+execute immediate 'ALTER TABLE ' || rec.owner || '.' || ObjName || ' DROP CONSTRAINT ' || rec.constraint_name;
+END LOOP;
+END;/
+/
+
+CALL removeConstraints('X_POLICY_ITEM');
+CALL removeConstraints('X_POLICY_ITEM_ACCESS');
+CALL removeConstraints('X_POLICY_ITEM_CONDITION');
+CALL removeConstraints('X_POLICY_ITEM_DATAMASK');
+CALL removeConstraints('X_POLICY_ITEM_GROUP_PERM');
+CALL removeConstraints('X_POLICY_RESOURCE');
+CALL removeConstraints('X_POLICY_RESOURCE_MAP');
+CALL removeConstraints('X_POLICY_ITEM_USER_PERM');
+CALL removeConstraints('X_POLICY_ITEM_ROWFILTER');

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/oracle/patches/036-denormalize-tag-tables.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/oracle/patches/036-denormalize-tag-tables.sql b/security-admin/db/oracle/patches/036-denormalize-tag-tables.sql
new file mode 100644
index 0000000..cae2927
--- /dev/null
+++ b/security-admin/db/oracle/patches/036-denormalize-tag-tables.sql
@@ -0,0 +1,54 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+DECLARE
+        v_count number:=0;
+BEGIN   
+        select count(*) into v_count from user_tab_cols where table_name='X_TAG_DEF' and column_name='TAG_ATTRS_DEF_TEXT';
+        if (v_count = 0) then 
+                execute immediate 'ALTER TABLE X_TAG_DEF ADD TAG_ATTRS_DEF_TEXT CLOB DEFAULT NULL NULL';
+        end if; 
+        select count(*) into v_count from user_tab_cols where table_name='X_TAG' and column_name='TAG_ATTRS_TEXT';
+        if (v_count = 0) then 
+                execute immediate 'ALTER TABLE X_TAG ADD TAG_ATTRS_TEXT CLOB DEFAULT NULL NULL';
+        end if; 
+        select count(*) into v_count from user_tab_cols where table_name='X_SERVICE_RESOURCE' and column_name='SERVICE_RESOURCE_ELEMENTS_TEXT';
+        if (v_count = 0) then 
+                execute immediate 'ALTER TABLE X_SERVICE_RESOURCE ADD SERVICE_RESOURCE_ELEMENTS_TEXT CLOB DEFAULT NULL NULL';
+        end if; 
+        select count(*) into v_count from user_tab_cols where table_name='X_SERVICE_RESOURCE' and column_name='TAGS_TEXT';
+        if (v_count = 0) then 
+                execute immediate 'ALTER TABLE X_SERVICE_RESOURCE ADD TAGS_TEXT CLOB DEFAULT NULL NULL';
+        end if; 
+        commit; 
+END;/
+
+CREATE OR REPLACE PROCEDURE removeConstraints(ObjName IN varchar2) IS
+BEGIN
+FOR rec IN(
+select owner, constraint_name
+from all_constraints
+where owner = sys_context('userenv','current_schema')
+and table_name = ObjName
+and constraint_type = 'R')
+LOOP
+execute immediate 'ALTER TABLE ' || rec.owner || '.' || ObjName || ' DROP CONSTRAINT ' || rec.constraint_name;
+END LOOP;
+END;/
+/
+
+CALL removeConstraints('X_TAG_ATTR_DEF');
+CALL removeConstraints('X_TAG_ATTR');
+CALL removeConstraints('X_SERVICE_RESOURCE_ELEMENT');
+CALL removeConstraints('X_SERVICE_RESOURCE_ELEMENT_VAL');


[7/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/sqlserver/optimized/current/ranger_core_db_sqlserver.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/sqlserver/optimized/current/ranger_core_db_sqlserver.sql b/security-admin/db/sqlserver/optimized/current/ranger_core_db_sqlserver.sql
index 85f3285..75c8faf 100644
--- a/security-admin/db/sqlserver/optimized/current/ranger_core_db_sqlserver.sql
+++ b/security-admin/db/sqlserver/optimized/current/ranger_core_db_sqlserver.sql
@@ -253,6 +253,102 @@ IF (OBJECT_ID('x_enum_def_FK_defid') IS NOT NULL)
 BEGIN
     ALTER TABLE [dbo].[x_enum_def] DROP CONSTRAINT x_enum_def_FK_defid
 END
+IF (OBJECT_ID('x_policy_ref_resource_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_resource] DROP CONSTRAINT x_policy_ref_resource_FK_policy_id
+END
+IF (OBJECT_ID('x_policy_ref_resource_FK_resource_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_resource] DROP CONSTRAINT x_policy_ref_resource_FK_resource_def_id
+END
+IF (OBJECT_ID('x_policy_ref_resource_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_resource] DROP CONSTRAINT x_policy_ref_resource_UK
+END
+IF (OBJECT_ID('x_policy_ref_resource') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_resource]
+END
+IF (OBJECT_ID('x_policy_ref_access_type_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_access_type] DROP CONSTRAINT x_policy_ref_access_type_FK_policy_id
+END
+IF (OBJECT_ID('x_policy_ref_access_type_FK_access_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_access_type] DROP CONSTRAINT x_policy_ref_access_type_FK_access_def_id
+END
+IF (OBJECT_ID('x_policy_ref_access_type_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_access_type] DROP CONSTRAINT x_policy_ref_access_type_UK
+END
+IF (OBJECT_ID('x_policy_ref_access_type') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_access_type]
+END
+IF (OBJECT_ID('x_policy_ref_condition_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_condition] DROP CONSTRAINT x_policy_ref_condition_FK_policy_id
+END
+IF (OBJECT_ID('x_policy_ref_condition_FK_condition_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_condition] DROP CONSTRAINT x_policy_ref_condition_FK_condition_def_id
+END
+IF (OBJECT_ID('x_policy_ref_condition_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_condition] DROP CONSTRAINT x_policy_ref_condition_UK
+END
+IF (OBJECT_ID('x_policy_ref_condition') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_condition]
+END
+IF (OBJECT_ID('x_policy_ref_datamask_type_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_datamask_type] DROP CONSTRAINT x_policy_ref_datamask_type_FK_policy_id
+END
+IF (OBJECT_ID('x_policy_ref_datamask_type_FK_datamask_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_datamask_type] DROP CONSTRAINT x_policy_ref_datamask_type_FK_datamask_def_id
+END
+IF (OBJECT_ID('x_policy_ref_datamask_type_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_datamask_type] DROP CONSTRAINT x_policy_ref_datamask_type_UK
+END
+IF (OBJECT_ID('x_policy_ref_datamask_type') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_datamask_type]
+END
+IF (OBJECT_ID('x_policy_ref_user_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_user] DROP CONSTRAINT x_policy_ref_user_FK_policy_id
+END
+IF (OBJECT_ID('x_policy_ref_user_FK_user_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_user] DROP CONSTRAINT x_policy_ref_user_FK_user_id
+END
+IF (OBJECT_ID('x_policy_ref_user_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_user] DROP CONSTRAINT x_policy_ref_user_UK
+END
+IF (OBJECT_ID('x_policy_ref_user') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_user]
+END
+IF (OBJECT_ID('x_policy_ref_group_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_group] DROP CONSTRAINT x_policy_ref_group_FK_policy_id
+END
+IF (OBJECT_ID('x_policy_ref_group_FK_group_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_group] DROP CONSTRAINT x_policy_ref_group_FK_group_id
+END
+IF (OBJECT_ID('x_policy_ref_group_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_group] DROP CONSTRAINT x_policy_ref_group_UK
+END
+IF (OBJECT_ID('x_policy_ref_group') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_group]
+END
 IF (OBJECT_ID('x_enum_element_def_FK_defid') IS NOT NULL)
 BEGIN
     ALTER TABLE [dbo].[x_enum_element_def] DROP CONSTRAINT x_enum_element_def_FK_defid
@@ -341,46 +437,6 @@ IF (OBJECT_ID('x_service_res_FK_upd_by_id') IS NOT NULL)
 BEGIN
     ALTER TABLE [dbo].[x_service_resource] DROP CONSTRAINT x_service_res_FK_upd_by_id
 END
-IF (OBJECT_ID('x_srvc_res_el_FK_res_def_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_service_resource_element] DROP CONSTRAINT x_srvc_res_el_FK_res_def_id
-END
-IF (OBJECT_ID('x_srvc_res_el_FK_res_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_service_resource_element] DROP CONSTRAINT x_srvc_res_el_FK_res_id
-END
-IF (OBJECT_ID('x_srvc_res_el_FK_added_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_service_resource_element] DROP CONSTRAINT x_srvc_res_el_FK_added_by_id
-END
-IF (OBJECT_ID('x_srvc_res_el_FK_upd_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_service_resource_element] DROP CONSTRAINT x_srvc_res_el_FK_upd_by_id
-END
-IF (OBJECT_ID('x_tag_attr_def_FK_tag_def_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_tag_attr_def] DROP CONSTRAINT x_tag_attr_def_FK_tag_def_id
-END
-IF (OBJECT_ID('x_tag_attr_def_FK_added_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_tag_attr_def] DROP CONSTRAINT x_tag_attr_def_FK_added_by_id
-END
-IF (OBJECT_ID('x_tag_attr_def_FK_upd_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_tag_attr_def] DROP CONSTRAINT x_tag_attr_def_FK_upd_by_id
-END
-IF (OBJECT_ID('x_tag_attr_FK_tag_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_tag_attr] DROP CONSTRAINT x_tag_attr_FK_tag_id
-END
-IF (OBJECT_ID('x_tag_attr_FK_added_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_tag_attr] DROP CONSTRAINT x_tag_attr_FK_added_by_id
-END
-IF (OBJECT_ID('x_tag_attr_FK_upd_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_tag_attr] DROP CONSTRAINT x_tag_attr_FK_upd_by_id
-END
 IF (OBJECT_ID('x_tag_res_map_FK_tag_id') IS NOT NULL)
 BEGIN
     ALTER TABLE [dbo].[x_tag_resource_map] DROP CONSTRAINT x_tag_res_map_FK_tag_id
@@ -397,18 +453,6 @@ IF (OBJECT_ID('x_tag_res_map_FK_upd_by_id') IS NOT NULL)
 BEGIN
     ALTER TABLE [dbo].[x_tag_resource_map] DROP CONSTRAINT x_tag_res_map_FK_upd_by_id
 END
-IF (OBJECT_ID('x_srvc_res_el_val_FK_res_el_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_service_resource_element_val] DROP CONSTRAINT x_srvc_res_el_val_FK_res_el_id
-END
-IF (OBJECT_ID('x_srvc_res_el_val_FK_add_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_service_resource_element_val] DROP CONSTRAINT x_srvc_res_el_val_FK_add_by_id
-END
-IF (OBJECT_ID('x_srvc_res_el_val_FK_upd_by_id') IS NOT NULL)
-BEGIN
-    ALTER TABLE [dbo].[x_service_resource_element_val] DROP CONSTRAINT x_srvc_res_el_val_FK_upd_by_id
-END
 IF (OBJECT_ID('x_datamask_type_def_FK_def_id') IS NOT NULL)
 BEGIN
     ALTER TABLE [dbo].[x_datamask_type_def] DROP CONSTRAINT x_datamask_type_def_FK_def_id
@@ -1161,6 +1205,7 @@ CREATE TABLE [dbo].[x_policy] (
         [is_audit_enabled] [tinyint] DEFAULT 0 NOT NULL,
         [policy_options] [varchar](4000) DEFAULT NULL NULL,
         [policy_priority] [int] DEFAULT 0 NOT NULL,
+		[policy_text] [nvarchar](max) DEFAULT NULL NULL,
 PRIMARY KEY CLUSTERED
 (
         [id] ASC
@@ -1601,6 +1646,7 @@ CREATE TABLE [dbo].[x_tag_def](
         [name] [varchar](255) NOT NULL,
         [source] [varchar](128) DEFAULT NULL NULL,
         [is_enabled] [tinyint] DEFAULT 0 NOT NULL,
+        [tag_attrs_def_text] [nvarchar](max) DEFAULT NULL NULL,
         PRIMARY KEY CLUSTERED
 (
         [id] ASC
@@ -1628,6 +1674,7 @@ CREATE TABLE [dbo].[x_tag](
         [type] [bigint] NOT NULL,
         [owned_by] [smallint] DEFAULT 0 NOT NULL,
         [policy_options] [varchar](4000) DEFAULT NULL NULL,
+        [tag_attrs_text] [nvarchar](max) DEFAULT NULL NULL,
         PRIMARY KEY CLUSTERED
 (
         [id] ASC
@@ -1651,6 +1698,8 @@ CREATE TABLE [dbo].[x_service_resource](
         [service_id] [bigint] NOT NULL,
         [resource_signature] [varchar](128) DEFAULT NULL NULL,
         [is_enabled] [tinyint] DEFAULT 1 NOT NULL,
+        [service_resource_elements_text] [nvarchar](max) DEFAULT NULL NULL,
+        [tags_text] [nvarchar](max) DEFAULT NULL NULL,
         PRIMARY KEY CLUSTERED
 (
         [id] ASC
@@ -1663,58 +1712,6 @@ CONSTRAINT [x_service_resource$x_service_res_UK_guid] UNIQUE NONCLUSTERED
 SET ANSI_NULLS ON
 SET QUOTED_IDENTIFIER ON
 SET ANSI_PADDING ON
-CREATE TABLE [dbo].[x_service_resource_element](
-        [id] [bigint] IDENTITY(1,1) NOT NULL,
-        [create_time] [datetime2] DEFAULT NULL NULL,
-        [update_time] [datetime2] DEFAULT NULL NULL,
-        [added_by_id] [bigint] DEFAULT NULL NULL,
-        [upd_by_id] [bigint] DEFAULT NULL NULL,
-        [res_id] [bigint] NOT NULL,
-        [res_def_id] [bigint] NOT NULL,
-        [is_excludes] [tinyint] DEFAULT 0 NOT NULL,
-        [is_recursive] [tinyint] DEFAULT 0 NOT NULL,
-        PRIMARY KEY CLUSTERED
-(
-        [id] ASC
-)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
-) ON [PRIMARY]
-SET ANSI_NULLS ON
-SET QUOTED_IDENTIFIER ON
-SET ANSI_PADDING ON
-CREATE TABLE [dbo].[x_tag_attr_def](
-        [id] [bigint] IDENTITY(1,1) NOT NULL,
-        [create_time] [datetime2] DEFAULT NULL NULL,
-        [update_time] [datetime2] DEFAULT NULL NULL,
-        [added_by_id] [bigint] DEFAULT NULL NULL,
-        [upd_by_id] [bigint] DEFAULT NULL NULL,
-        [tag_def_id] [bigint] NOT NULL,
-        [name] [varchar](255) NOT NULL,
-        [type] [varchar](50) NOT NULL,
-        PRIMARY KEY CLUSTERED
-(
-        [id] ASC
-)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
-) ON [PRIMARY]
-SET ANSI_NULLS ON
-SET QUOTED_IDENTIFIER ON
-SET ANSI_PADDING ON
-CREATE TABLE [dbo].[x_tag_attr](
-        [id] [bigint] IDENTITY(1,1) NOT NULL,
-        [create_time] [datetime2] DEFAULT NULL NULL,
-        [update_time] [datetime2] DEFAULT NULL NULL,
-        [added_by_id] [bigint] DEFAULT NULL NULL,
-        [upd_by_id] [bigint] DEFAULT NULL NULL,
-        [tag_id] [bigint] NOT NULL,
-        [name] [varchar](255) NOT NULL,
-        [value] [varchar](512) DEFAULT NULL NULL,
-        PRIMARY KEY CLUSTERED
-(
-        [id] ASC
-)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
-) ON [PRIMARY]
-SET ANSI_NULLS ON
-SET QUOTED_IDENTIFIER ON
-SET ANSI_PADDING ON
 CREATE TABLE [dbo].[x_tag_resource_map](
         [id] [bigint] IDENTITY(1,1) NOT NULL,
         [guid] [varchar](64) NOT NULL,
@@ -1736,23 +1733,6 @@ CONSTRAINT [x_tag_resource_map$x_tag_resource_map_UK_guid] UNIQUE NONCLUSTERED
 SET ANSI_NULLS ON
 SET QUOTED_IDENTIFIER ON
 SET ANSI_PADDING ON
-CREATE TABLE [dbo].[x_service_resource_element_val](
-        [id] [bigint] IDENTITY(1,1) NOT NULL,
-        [create_time] [datetime2] DEFAULT NULL NULL,
-        [update_time] [datetime2] DEFAULT NULL NULL,
-        [added_by_id] [bigint] DEFAULT NULL NULL,
-        [upd_by_id] [bigint] DEFAULT NULL NULL,
-        [res_element_id] [bigint] NOT NULL,
-        [value] [varchar](1024) NOT NULL,
-        [sort_order] [tinyint] DEFAULT 0 NULL,
-        PRIMARY KEY CLUSTERED
-(
-        [id] ASC
-)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
-) ON [PRIMARY]
-SET ANSI_NULLS ON
-SET QUOTED_IDENTIFIER ON
-SET ANSI_PADDING ON
 CREATE TABLE [dbo].[x_datamask_type_def](
         [id] [bigint] IDENTITY(1,1) NOT NULL,
         [guid] [varchar](64) DEFAULT NULL NULL,
@@ -1904,6 +1884,138 @@ CREATE TABLE [dbo].[x_ugsync_audit_info](
 SET ANSI_NULLS ON
 SET QUOTED_IDENTIFIER ON
 SET ANSI_PADDING ON
+CREATE TABLE [dbo].[x_policy_ref_resource] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [resource_def_id] [bigint] NOT NULL,
+  [resource_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+  CONSTRAINT [x_policy_ref_resource$x_policy_ref_resource_UK] UNIQUE NONCLUSTERED
+  (
+	[policy_id] ASC, [resource_def_id] ASC
+  )WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+SET ANSI_NULLS ON
+SET QUOTED_IDENTIFIER ON
+SET ANSI_PADDING ON
+CREATE TABLE [dbo].[x_policy_ref_access_type] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [access_def_id] [bigint] NOT NULL,
+  [access_type_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_access_type$x_policy_ref_access_type_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [access_def_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+SET ANSI_NULLS ON
+SET QUOTED_IDENTIFIER ON
+SET ANSI_PADDING ON
+CREATE TABLE [dbo].[x_policy_ref_condition] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [condition_def_id] [bigint] NOT NULL,
+  [condition_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_condition$x_policy_ref_condition_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [condition_def_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+SET ANSI_NULLS ON
+SET QUOTED_IDENTIFIER ON
+SET ANSI_PADDING ON
+CREATE TABLE [dbo].[x_policy_ref_datamask_type] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [datamask_def_id] [bigint] NOT NULL,
+  [datamask_type_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_datamask_type$x_policy_ref_datamask_type_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [datamask_def_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+SET ANSI_NULLS ON
+SET QUOTED_IDENTIFIER ON
+SET ANSI_PADDING ON
+CREATE TABLE [dbo].[x_policy_ref_user] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [user_id] [bigint] NOT NULL,
+  [user_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_user$x_policy_ref_user_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [user_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+SET ANSI_NULLS ON
+SET QUOTED_IDENTIFIER ON
+SET ANSI_PADDING ON
+CREATE TABLE [dbo].[x_policy_ref_group] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [group_id] [bigint] NOT NULL,
+  [group_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_group$x_policy_ref_group_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [group_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+SET ANSI_NULLS ON
+SET QUOTED_IDENTIFIER ON
+SET ANSI_PADDING ON
 
 ALTER TABLE [dbo].[x_asset]  WITH CHECK ADD  CONSTRAINT [x_asset_FK_added_by_id] FOREIGN KEY([added_by_id])
 REFERENCES [dbo].[x_portal_user] ([id])
@@ -2238,23 +2350,10 @@ ALTER TABLE [dbo].[x_tag] WITH CHECK ADD CONSTRAINT [x_tag_FK_type] FOREIGN KEY(
 ALTER TABLE [dbo].[x_service_resource] WITH CHECK ADD CONSTRAINT [x_service_res_FK_added_by_id] FOREIGN KEY([added_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
 ALTER TABLE [dbo].[x_service_resource] WITH CHECK ADD CONSTRAINT [x_service_res_FK_upd_by_id] FOREIGN KEY([upd_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
 ALTER TABLE [dbo].[x_service_resource] WITH CHECK ADD CONSTRAINT [x_service_res_FK_service_id] FOREIGN KEY([service_id]) REFERENCES [dbo].[x_service] ([id])
-ALTER TABLE [dbo].[x_service_resource_element] WITH CHECK ADD CONSTRAINT [x_srvc_res_el_FK_res_def_id] FOREIGN KEY([res_def_id]) REFERENCES [dbo].[x_resource_def] ([id])
-ALTER TABLE [dbo].[x_service_resource_element] WITH CHECK ADD CONSTRAINT [x_srvc_res_el_FK_res_id] FOREIGN KEY([res_id]) REFERENCES [dbo].[x_service_resource] ([id])
-ALTER TABLE [dbo].[x_service_resource_element] WITH CHECK ADD CONSTRAINT [x_srvc_res_el_FK_added_by_id] FOREIGN KEY([added_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
-ALTER TABLE [dbo].[x_service_resource_element] WITH CHECK ADD CONSTRAINT [x_srvc_res_el_FK_upd_by_id] FOREIGN KEY([upd_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
-ALTER TABLE [dbo].[x_tag_attr_def] WITH CHECK ADD CONSTRAINT [x_tag_attr_def_FK_tag_def_id] FOREIGN KEY([tag_def_id]) REFERENCES [dbo].[x_tag_def] ([id])
-ALTER TABLE [dbo].[x_tag_attr_def] WITH CHECK ADD CONSTRAINT [x_tag_attr_def_FK_added_by_id] FOREIGN KEY([added_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
-ALTER TABLE [dbo].[x_tag_attr_def] WITH CHECK ADD CONSTRAINT [x_tag_attr_def_FK_upd_by_id] FOREIGN KEY([upd_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
-ALTER TABLE [dbo].[x_tag_attr] WITH CHECK ADD CONSTRAINT [x_tag_attr_FK_tag_id] FOREIGN KEY([tag_id]) REFERENCES [dbo].[x_tag] ([id])
-ALTER TABLE [dbo].[x_tag_attr] WITH CHECK ADD CONSTRAINT [x_tag_attr_FK_added_by_id] FOREIGN KEY([added_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
-ALTER TABLE [dbo].[x_tag_attr] WITH CHECK ADD CONSTRAINT [x_tag_attr_FK_upd_by_id] FOREIGN KEY([upd_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
 ALTER TABLE [dbo].[x_tag_resource_map] WITH CHECK ADD CONSTRAINT [x_tag_res_map_FK_tag_id] FOREIGN KEY([tag_id]) REFERENCES [dbo].[x_tag] ([id])
 ALTER TABLE [dbo].[x_tag_resource_map] WITH CHECK ADD CONSTRAINT [x_tag_res_map_FK_res_id] FOREIGN KEY([res_id]) REFERENCES [dbo].[x_service_resource] ([id])
 ALTER TABLE [dbo].[x_tag_resource_map] WITH CHECK ADD CONSTRAINT [x_tag_res_map_FK_added_by_id] FOREIGN KEY([added_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
 ALTER TABLE [dbo].[x_tag_resource_map] WITH CHECK ADD CONSTRAINT [x_tag_res_map_FK_upd_by_id] FOREIGN KEY([upd_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
-ALTER TABLE [dbo].[x_service_resource_element_val] WITH CHECK ADD CONSTRAINT [x_srvc_res_el_val_FK_res_el_id] FOREIGN KEY([res_element_id]) REFERENCES [dbo].[x_service_resource_element] ([id])
-ALTER TABLE [dbo].[x_service_resource_element_val] WITH CHECK ADD CONSTRAINT [x_srvc_res_el_val_FK_add_by_id] FOREIGN KEY([added_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
-ALTER TABLE [dbo].[x_service_resource_element_val] WITH CHECK ADD CONSTRAINT [x_srvc_res_el_val_FK_upd_by_id] FOREIGN KEY([upd_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
 ALTER TABLE [dbo].[x_datamask_type_def] WITH CHECK ADD CONSTRAINT [x_datamask_type_def_FK_def_id] FOREIGN KEY([def_id]) REFERENCES [dbo].[x_service_def] ([id])
 ALTER TABLE [dbo].[x_datamask_type_def] WITH CHECK ADD CONSTRAINT [x_datamask_type_def_FK_added_by_id] FOREIGN KEY([added_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
 ALTER TABLE [dbo].[x_datamask_type_def] WITH CHECK ADD CONSTRAINT [x_datamask_type_def_FK_upd_by_id] FOREIGN KEY([upd_by_id]) REFERENCES [dbo].[x_portal_user] ([id])
@@ -2273,6 +2372,78 @@ ALTER TABLE [dbo].[x_policy_label_map] WITH CHECK ADD CONSTRAINT [x_policy_label
 ALTER TABLE [dbo].[x_policy_label_map] WITH CHECK ADD CONSTRAINT [x_policy_label_map_FK_policy_id] FOREIGN KEY ([policy_id]) REFERENCES [dbo].[x_policy] ([id])
 ALTER TABLE [dbo].[x_policy_label_map] WITH CHECK ADD CONSTRAINT [x_policy_label_map_FK_policy_label_id] FOREIGN KEY ([policy_label_id]) REFERENCES [dbo].[x_policy_label] ([id])
 ALTER TABLE [dbo].[x_policy_label_map] WITH CHECK ADD CONSTRAINT [x_policy_label_map$x_policy_label_map_pid_plid] UNIQUE (policy_id, policy_label_id)
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_resource] CHECK CONSTRAINT [x_policy_ref_resource_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_res_def_id] FOREIGN KEY ([resource_def_id])
+REFERENCES [dbo].[x_resource_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_resource] CHECK CONSTRAINT [x_policy_ref_resource_FK_res_def_id]
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_resource] CHECK CONSTRAINT [x_policy_ref_resource_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] CHECK CONSTRAINT [x_policy_ref_access_type_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_res_def_id] FOREIGN KEY ([access_def_id])
+REFERENCES [dbo].[x_resource_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] CHECK CONSTRAINT [x_policy_ref_access_type_FK_res_def_id]
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] CHECK CONSTRAINT [x_policy_ref_access_type_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] CHECK CONSTRAINT [x_policy_ref_condition_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_res_def_id] FOREIGN KEY ([condition_def_id])
+REFERENCES [dbo].[x_policy_condition_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] CHECK CONSTRAINT [x_policy_ref_condition_FK_res_def_id]
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] CHECK CONSTRAINT [x_policy_ref_condition_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] CHECK CONSTRAINT [x_policy_ref_datamask_type_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_res_def_id] FOREIGN KEY ([datamask_def_id])
+REFERENCES [dbo].[x_datamask_type_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] CHECK CONSTRAINT [x_policy_ref_datamask_type_FK_res_def_id]
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] CHECK CONSTRAINT [x_policy_ref_datamask_type_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_policy_id]
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_user_id] FOREIGN KEY ([user_id])
+REFERENCES [dbo].[x_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_user_id]
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_added_by]
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_upd_by]
+
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_group] CHECK CONSTRAINT [x_policy_ref_group_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_group_id] FOREIGN KEY ([group_id])
+REFERENCES [dbo].[x_group] ([id])
+ALTER TABLE [dbo].[x_policy_ref_group] CHECK CONSTRAINT [x_policy_ref_group_FK_group_id]
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_group] CHECK CONSTRAINT [x_policy_ref_group_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
 CREATE NONCLUSTERED INDEX [x_asset_cr_time] ON [x_asset]
 (
    [create_time] ASC
@@ -2825,46 +2996,6 @@ CREATE NONCLUSTERED INDEX [x_service_res_IDX_upd_by_id] ON [x_service_resource]
    [upd_by_id] ASC
 )
 WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_srvc_res_el_IDX_added_by_id] ON [x_service_resource_element]
-(
-   [added_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_srvc_res_el_IDX_upd_by_id] ON [x_service_resource_element]
-(
-   [upd_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_tag_attr_def_IDX_tag_def_id] ON [x_tag_attr_def]
-(
-   [tag_def_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_tag_attr_def_IDX_added_by_id] ON [x_tag_attr_def]
-(
-   [added_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_tag_attr_def_IDX_upd_by_id] ON [x_tag_attr_def]
-(
-   [upd_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_tag_attr_IDX_tag_id] ON [x_tag_attr]
-(
-   [tag_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_tag_attr_IDX_added_by_id] ON [x_tag_attr]
-(
-   [added_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_tag_attr_IDX_upd_by_id] ON [x_tag_attr]
-(
-   [upd_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
 CREATE NONCLUSTERED INDEX [x_tag_res_map_IDX_tag_id] ON [x_tag_resource_map]
 (
    [tag_id] ASC
@@ -2885,21 +3016,6 @@ CREATE NONCLUSTERED INDEX [x_tag_res_map_IDX_upd_by_id] ON [x_tag_resource_map]
    [upd_by_id] ASC
 )
 WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_srvc_res_el_val_IDX_resel_id] ON [x_service_resource_element_val]
-(
-   [res_element_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_srvc_res_el_val_IDX_addby_id] ON [x_service_resource_element_val]
-(
-   [added_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_srvc_res_el_val_IDX_updby_id] ON [x_service_resource_element_val]
-(
-   [upd_by_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
 CREATE NONCLUSTERED INDEX [x_service_config_def_IDX_def_id] ON [x_service_config_def]
 (
    [def_id] ASC
@@ -3005,16 +3121,6 @@ CREATE NONCLUSTERED INDEX [x_service_resource_IDX_service_id] ON [x_service_reso
    [service_id] ASC
 )
 WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_service_resource_element_IDX_res_id] ON [x_service_resource_element]
-(
-   [res_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
-CREATE NONCLUSTERED INDEX [x_service_resource_element_IDX_res_def_id] ON [x_service_resource_element]
-(
-   [res_def_id] ASC
-)
-WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
 CREATE NONCLUSTERED INDEX [x_datamask_type_def_IDX_def_id] ON [x_datamask_type_def]
 (
    [def_id] ASC
@@ -3108,6 +3214,9 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('031',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('032',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('033',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('034',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('035',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('036',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('DB_PATCHES',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 INSERT INTO x_user_module_perm (user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (1,3,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,1,1,1);
 INSERT INTO x_user_module_perm (user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (1,1,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,1,1,1);
@@ -3145,7 +3254,8 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10014',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10015',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10016',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
-INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10018',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10019',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10020',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('JAVA_PATCHES',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 GO
 CREATE VIEW [dbo].[vx_trx_log] AS

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/sqlserver/patches/035-update-schema-for-x-policy.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/sqlserver/patches/035-update-schema-for-x-policy.sql b/security-admin/db/sqlserver/patches/035-update-schema-for-x-policy.sql
new file mode 100644
index 0000000..ebf44ac
--- /dev/null
+++ b/security-admin/db/sqlserver/patches/035-update-schema-for-x-policy.sql
@@ -0,0 +1,453 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+GO
+IF (OBJECT_ID('x_policy_ref_resource_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_resource] DROP CONSTRAINT x_policy_ref_resource_FK_policy_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_resource_FK_resource_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_resource] DROP CONSTRAINT x_policy_ref_resource_FK_resource_def_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_resource_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_resource] DROP CONSTRAINT x_policy_ref_resource_UK
+END
+GO
+IF (OBJECT_ID('x_policy_ref_resource') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_resource]
+END
+GO
+IF (OBJECT_ID('x_policy_ref_access_type_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_access_type] DROP CONSTRAINT x_policy_ref_access_type_FK_policy_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_access_type_FK_access_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_access_type] DROP CONSTRAINT x_policy_ref_access_type_FK_access_def_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_access_type_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_access_type] DROP CONSTRAINT x_policy_ref_access_type_UK
+END
+GO
+IF (OBJECT_ID('x_policy_ref_access_type') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_access_type]
+END
+GO
+IF (OBJECT_ID('x_policy_ref_condition_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_condition] DROP CONSTRAINT x_policy_ref_condition_FK_policy_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_condition_FK_condition_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_condition] DROP CONSTRAINT x_policy_ref_condition_FK_condition_def_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_condition_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_condition] DROP CONSTRAINT x_policy_ref_condition_UK
+END
+GO
+IF (OBJECT_ID('x_policy_ref_condition') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_condition]
+END
+GO
+IF (OBJECT_ID('x_policy_ref_datamask_type_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_datamask_type] DROP CONSTRAINT x_policy_ref_datamask_type_FK_policy_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_datamask_type_FK_datamask_def_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_datamask_type] DROP CONSTRAINT x_policy_ref_datamask_type_FK_datamask_def_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_datamask_type_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_datamask_type] DROP CONSTRAINT x_policy_ref_datamask_type_UK
+END
+GO
+IF (OBJECT_ID('x_policy_ref_datamask_type') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_datamask_type]
+END
+GO
+IF (OBJECT_ID('x_policy_ref_user_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_user] DROP CONSTRAINT x_policy_ref_user_FK_policy_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_user_FK_user_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_user] DROP CONSTRAINT x_policy_ref_user_FK_user_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_user_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_user] DROP CONSTRAINT x_policy_ref_user_UK
+END
+GO
+IF (OBJECT_ID('x_policy_ref_user') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_user]
+END
+GO
+IF (OBJECT_ID('x_policy_ref_group_FK_policy_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_group] DROP CONSTRAINT x_policy_ref_group_FK_policy_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_group_FK_group_id') IS NOT NULL)
+BEGIN
+  ALTER TABLE [dbo].[x_policy_ref_group] DROP CONSTRAINT x_policy_ref_group_FK_group_id
+END
+GO
+IF (OBJECT_ID('x_policy_ref_group_UK') IS NOT NULL)
+BEGIN
+    ALTER TABLE [dbo].[x_policy_ref_group] DROP CONSTRAINT x_policy_ref_group_UK
+END
+GO
+IF (OBJECT_ID('x_policy_ref_group') IS NOT NULL)
+BEGIN
+  DROP TABLE [dbo].[x_policy_ref_group]
+END
+GO
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+CREATE TABLE [dbo].[x_policy_ref_resource] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [resource_def_id] [bigint] NOT NULL,
+  [resource_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+  CONSTRAINT [x_policy_ref_resource$x_policy_ref_resource_UK] UNIQUE NONCLUSTERED
+  (
+	[policy_id] ASC, [resource_def_id] ASC
+  )WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+GO
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+CREATE TABLE [dbo].[x_policy_ref_access_type] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [access_def_id] [bigint] NOT NULL,
+  [access_type_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_access_type$x_policy_ref_access_type_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [access_def_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+GO
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+CREATE TABLE [dbo].[x_policy_ref_condition] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [condition_def_id] [bigint] NOT NULL,
+  [condition_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_condition$x_policy_ref_condition_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [condition_def_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+GO
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+CREATE TABLE [dbo].[x_policy_ref_datamask_type] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [datamask_def_id] [bigint] NOT NULL,
+  [datamask_type_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_datamask_type$x_policy_ref_datamask_type_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [datamask_def_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+GO
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+CREATE TABLE [dbo].[x_policy_ref_user] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [user_id] [bigint] NOT NULL,
+  [user_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_user$x_policy_ref_user_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [user_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+GO
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+CREATE TABLE [dbo].[x_policy_ref_group] (
+  [id] [bigint] IDENTITY (1, 1) NOT NULL,
+  [guid] [varchar](1024) DEFAULT NULL NULL,
+  [create_time] [datetime2] DEFAULT NULL NULL,
+  [update_time] [datetime2] DEFAULT NULL NULL,
+  [added_by_id] [bigint] DEFAULT NULL NULL,
+  [upd_by_id] [bigint] DEFAULT NULL NULL,
+  [policy_id] [bigint] NOT NULL,
+  [group_id] [bigint] NOT NULL,
+  [group_name] [varchar](4000) DEFAULT NULL NULL,
+  PRIMARY KEY CLUSTERED
+  (
+  [id] ASC
+  ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
+    CONSTRAINT [x_policy_ref_group$x_policy_ref_group_UK] UNIQUE NONCLUSTERED
+(
+        [policy_id] ASC, [group_id] ASC
+)WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
+) ON [PRIMARY]
+GO
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_resource] CHECK CONSTRAINT [x_policy_ref_resource_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_resource_def_id] FOREIGN KEY ([resource_def_id])
+REFERENCES [dbo].[x_resource_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_resource] CHECK CONSTRAINT [x_policy_ref_resource_FK_resource_def_id]
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_resource] CHECK CONSTRAINT [x_policy_ref_resource_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_resource] WITH CHECK ADD CONSTRAINT [x_policy_ref_resource_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] CHECK CONSTRAINT [x_policy_ref_access_type_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_access_def_id] FOREIGN KEY ([access_def_id])
+REFERENCES [dbo].[x_access_type_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] CHECK CONSTRAINT [x_policy_ref_access_type_FK_access_def_id]
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_access_type] CHECK CONSTRAINT [x_policy_ref_access_type_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_access_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_access_type_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] CHECK CONSTRAINT [x_policy_ref_condition_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_condition_def_id] FOREIGN KEY ([condition_def_id])
+REFERENCES [dbo].[x_policy_condition_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] CHECK CONSTRAINT [x_policy_ref_condition_FK_condition_def_id]
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_condition] CHECK CONSTRAINT [x_policy_ref_condition_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_condition] WITH CHECK ADD CONSTRAINT [x_policy_ref_condition_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] CHECK CONSTRAINT [x_policy_ref_datamask_type_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_datamask_def_id] FOREIGN KEY ([datamask_def_id])
+REFERENCES [dbo].[x_datamask_type_def] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] CHECK CONSTRAINT [x_policy_ref_datamask_type_FK_datamask_def_id]
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] CHECK CONSTRAINT [x_policy_ref_datamask_type_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_datamask_type] WITH CHECK ADD CONSTRAINT [x_policy_ref_datamask_type_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_policy_id]
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_user_id] FOREIGN KEY ([user_id])
+REFERENCES [dbo].[x_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_user_id]
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_added_by]
+
+ALTER TABLE [dbo].[x_policy_ref_user] WITH CHECK ADD CONSTRAINT [x_policy_ref_user_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_user] CHECK CONSTRAINT [x_policy_ref_user_FK_upd_by]
+
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_policy_id] FOREIGN KEY ([policy_id])
+REFERENCES [dbo].[x_policy] ([id])
+ALTER TABLE [dbo].[x_policy_ref_group] CHECK CONSTRAINT [x_policy_ref_group_FK_policy_id]
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_group_id] FOREIGN KEY ([group_id])
+REFERENCES [dbo].[x_group] ([id])
+ALTER TABLE [dbo].[x_policy_ref_group] CHECK CONSTRAINT [x_policy_ref_group_FK_group_id]
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_added_by] FOREIGN KEY ([added_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+ALTER TABLE [dbo].[x_policy_ref_group] CHECK CONSTRAINT [x_policy_ref_group_FK_added_by]
+ALTER TABLE [dbo].[x_policy_ref_group] WITH CHECK ADD CONSTRAINT [x_policy_ref_group_FK_upd_by] FOREIGN KEY ([upd_by_id])
+REFERENCES [dbo].[x_portal_user] ([id])
+GO
+IF NOT EXISTS (SELECT
+    *
+  FROM INFORMATION_SCHEMA.columns
+  WHERE table_name = 'x_policy'
+  AND column_name = 'policy_text')
+BEGIN
+  ALTER TABLE [dbo].[x_policy] ADD [policy_text]  [nvarchar](max)  DEFAULT NULL NULL;
+END
+GO
+
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+IF EXISTS (
+        SELECT type_desc, type
+        FROM sys.procedures WITH(NOLOCK)
+        WHERE NAME = 'removeConstraints'
+            AND type = 'P'
+      )
+BEGIN
+	 PRINT 'Proc exist with name dbo.removeConstraints'
+     DROP PROCEDURE dbo.removeConstraints
+	 PRINT 'Proc dropped dbo.removeConstraints'
+END
+GO
+CREATE PROCEDURE dbo.removeConstraints
+	-- Add the parameters for the stored procedure here
+	@tablename nvarchar(100)
+AS
+BEGIN
+
+  DECLARE @stmt VARCHAR(300);
+
+  -- Cursor to generate ALTER TABLE DROP CONSTRAINT statements
+  DECLARE cur CURSOR FOR
+     SELECT 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) +
+                    ' DROP CONSTRAINT ' + name
+     FROM sys.foreign_keys
+     WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND
+                OBJECT_NAME(referenced_object_id) = @tablename;
+
+   OPEN cur;
+   FETCH cur INTO @stmt;
+
+   -- Drop each found foreign key constraint
+   WHILE @@FETCH_STATUS = 0
+     BEGIN
+       EXEC (@stmt);
+       FETCH cur INTO @stmt;
+     END
+
+  CLOSE cur;
+  DEALLOCATE cur;
+
+END
+GO
+
+EXEC dbo.removeConstraints 'x_policy_item'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_item_access'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_item_condition'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_item_datamask'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_item_group_perm'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_item_user_perm'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_item_rowfilter'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_resource'
+GO
+
+EXEC dbo.removeConstraints 'x_policy_resource_map'
+GO
+
+EXIT

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/sqlserver/patches/036-denormalize-tag-tables.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/sqlserver/patches/036-denormalize-tag-tables.sql b/security-admin/db/sqlserver/patches/036-denormalize-tag-tables.sql
new file mode 100644
index 0000000..9bfae30
--- /dev/null
+++ b/security-admin/db/sqlserver/patches/036-denormalize-tag-tables.sql
@@ -0,0 +1,97 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+GO
+IF NOT EXISTS(select * from INFORMATION_SCHEMA.columns where table_name = 'x_tag_def' and column_name = 'tag_attrs_def_text')
+BEGIN
+	ALTER TABLE [dbo].[x_tag_def] ADD [tag_attrs_def_text] [nvarchar](max) DEFAULT NULL NULL;
+END
+IF NOT EXISTS(select * from INFORMATION_SCHEMA.columns where table_name = 'x_tag' and column_name = 'tag_attrs_text')
+BEGIN
+	ALTER TABLE [dbo].[x_tag] ADD [tag_attrs_text] [nvarchar](max) DEFAULT NULL NULL;
+END
+IF NOT EXISTS(select * from INFORMATION_SCHEMA.columns where table_name = 'x_service_resource' and column_name = 'service_resource_elements_text')
+BEGIN
+	ALTER TABLE [dbo].[x_service_resource] ADD [service_resource_elements_text] [nvarchar](max) DEFAULT NULL NULL;
+END
+IF NOT EXISTS(select * from INFORMATION_SCHEMA.columns where table_name = 'x_service_resource' and column_name = 'tags_text')
+BEGIN
+	ALTER TABLE [dbo].[x_service_resource] ADD [tags_text] [nvarchar](max) DEFAULT NULL NULL;
+END
+GO
+
+SET ANSI_NULLS ON
+GO
+SET QUOTED_IDENTIFIER ON
+GO
+SET ANSI_PADDING ON
+GO
+IF EXISTS (
+        SELECT type_desc, type
+        FROM sys.procedures WITH(NOLOCK)
+        WHERE NAME = 'removeConstraints'
+            AND type = 'P'
+      )
+BEGIN
+	 PRINT 'Proc exist with name dbo.removeConstraints'
+     DROP PROCEDURE dbo.removeConstraints
+	 PRINT 'Proc dropped dbo.removeConstraints'
+END
+GO
+CREATE PROCEDURE dbo.removeConstraints
+	-- Add the parameters for the stored procedure here
+	@tablename nvarchar(100)
+AS
+BEGIN
+
+  DECLARE @stmt VARCHAR(300);
+
+  -- Cursor to generate ALTER TABLE DROP CONSTRAINT statements
+  DECLARE cur CURSOR FOR
+     SELECT 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) + '.' + OBJECT_NAME(parent_object_id) +
+                    ' DROP CONSTRAINT ' + name
+     FROM sys.foreign_keys
+     WHERE OBJECT_SCHEMA_NAME(referenced_object_id) = 'dbo' AND
+                OBJECT_NAME(referenced_object_id) = @tablename;
+
+   OPEN cur;
+   FETCH cur INTO @stmt;
+
+   -- Drop each found foreign key constraint
+   WHILE @@FETCH_STATUS = 0
+     BEGIN
+       EXEC (@stmt);
+       FETCH cur INTO @stmt;
+     END
+
+  CLOSE cur;
+  DEALLOCATE cur;
+
+END
+GO
+
+EXEC dbo.removeConstraints 'x_tag_attr_def'
+GO
+
+EXEC dbo.removeConstraints 'x_tag_attr'
+GO
+
+EXEC dbo.removeConstraints 'x_service_resource_element'
+GO
+
+EXEC dbo.removeConstraints 'x_service_resource_element_val'
+GO
+
+EXIT

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/scripts/db_setup.py
----------------------------------------------------------------------
diff --git a/security-admin/scripts/db_setup.py b/security-admin/scripts/db_setup.py
index 02701c7..5ac312f 100644
--- a/security-admin/scripts/db_setup.py
+++ b/security-admin/scripts/db_setup.py
@@ -29,8 +29,9 @@ os_name = os_name.upper()
 ranger_version=''
 jisql_debug=True
 retryPatchAfterSeconds=120
-
+java_patch_regex="^Patch.*?J\d{5}.class$"
 is_unix = os_name == "LINUX" or os_name == "DARWIN"
+max_memory='1g'
 
 RANGER_ADMIN_HOME = os.getenv("RANGER_ADMIN_HOME")
 if RANGER_ADMIN_HOME is None:
@@ -509,7 +510,7 @@ class MysqlConf(BaseDB):
 			files = os.listdir(javaFiles)
 			if files:
 				for filename in files:
-					f = re.match("^Patch.*?.class$",filename)
+					f = re.match(java_patch_regex,filename)
 					if f:
 						version = re.match("Patch.*?_(.*).class",filename)
 						version = version.group(1)
@@ -564,7 +565,7 @@ class MysqlConf(BaseDB):
 								path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 							elif os_name == "WINDOWS":
 								path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-							get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
+							get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,max_memory,ranger_log,path,className)
 							if is_unix:
 								ret = subprocess.call(shlex.split(get_java_cmd))
 							elif os_name == "WINDOWS":
@@ -1222,7 +1223,7 @@ class OracleConf(BaseDB):
 			files = os.listdir(javaFiles)
 			if files:
 				for filename in files:
-					f = re.match("^Patch.*?.class$",filename)
+					f = re.match(java_patch_regex,filename)
 					if f:
 						className = re.match("(Patch.*?)_.*.class",filename)
 						className = className.group(1)
@@ -1304,7 +1305,7 @@ class OracleConf(BaseDB):
 								path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 							elif os_name == "WINDOWS":
 								path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-							get_java_cmd = "%s -Djava.security.egd=file:///dev/urandom -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
+							get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Djava.security.egd=file:///dev/urandom -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,max_memory,ranger_log,path,className)
 							if is_unix:
 								ret = subprocess.call(shlex.split(get_java_cmd))
 							elif os_name == "WINDOWS":
@@ -1399,7 +1400,7 @@ class OracleConf(BaseDB):
 							path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 						elif os_name == "WINDOWS":
 							path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-                                                get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,ranger_log,path,className,'"'+userName+'"','"'+oldPassword+'"','"'+newPassword+'"')
+						get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,max_memory,ranger_log,path,className,userName,oldPassword,newPassword)
 						if is_unix:
 							status = subprocess.call(shlex.split(get_java_cmd))
 						elif os_name == "WINDOWS":
@@ -1962,7 +1963,7 @@ class PostgresConf(BaseDB):
 			files = os.listdir(javaFiles)
 			if files:
 				for filename in files:
-					f = re.match("^Patch.*?.class$",filename)
+					f = re.match(java_patch_regex,filename)
 					if f:
 						className = re.match("(Patch.*?)_.*.class",filename)
 						className = className.group(1)
@@ -2019,7 +2020,7 @@ class PostgresConf(BaseDB):
 								path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 							elif os_name == "WINDOWS":
 								path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-							get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
+							get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,max_memory,ranger_log,path,className)
 							if is_unix:
 								ret = subprocess.call(shlex.split(get_java_cmd))
 							elif os_name == "WINDOWS":
@@ -2114,7 +2115,7 @@ class PostgresConf(BaseDB):
 							path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 						elif os_name == "WINDOWS":
 							path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-                                                get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,ranger_log,path,className,'"'+userName+'"','"'+oldPassword+'"','"'+newPassword+'"')
+						get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,max_memory,ranger_log,path,className,userName,oldPassword,newPassword)
 						if is_unix:
 							status = subprocess.call(shlex.split(get_java_cmd))
 						elif os_name == "WINDOWS":
@@ -2619,7 +2620,7 @@ class SqlServerConf(BaseDB):
 			files = os.listdir(javaFiles)
 			if files:
 				for filename in files:
-					f = re.match("^Patch.*?.class$",filename)
+					f = re.match(java_patch_regex,filename)
 					if f:
 						className = re.match("(Patch.*?)_.*.class",filename)
 						className = className.group(1)
@@ -2676,7 +2677,7 @@ class SqlServerConf(BaseDB):
 								path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 							elif os_name == "WINDOWS":
 								path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-							get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
+							get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,max_memory,ranger_log,path,className)
 							if is_unix:
 								ret = subprocess.call(shlex.split(get_java_cmd))
 							elif os_name == "WINDOWS":
@@ -2771,7 +2772,7 @@ class SqlServerConf(BaseDB):
 							path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 						elif os_name == "WINDOWS":
 							path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-                                                get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,ranger_log,path,className,'"'+userName+'"','"'+oldPassword+'"','"'+newPassword+'"')
+						get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,max_memory,ranger_log,path,className,userName,oldPassword,newPassword)
 						if is_unix:
 							status = subprocess.call(shlex.split(get_java_cmd))
 						elif os_name == "WINDOWS":
@@ -3268,7 +3269,7 @@ class SqlAnywhereConf(BaseDB):
 			files = os.listdir(javaFiles)
 			if files:
 				for filename in files:
-					f = re.match("^Patch.*?.class$",filename)
+					f = re.match(java_patch_regex,filename)
 					if f:
 						className = re.match("(Patch.*?)_.*.class",filename)
 						className = className.group(1)
@@ -3325,7 +3326,7 @@ class SqlAnywhereConf(BaseDB):
 								path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 							elif os_name == "WINDOWS":
 								path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-							get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,ranger_log,path,className)
+							get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.%s"%(self.JAVA_BIN,max_memory,ranger_log,path,className)
 							if is_unix:
 								ret = subprocess.call(shlex.split(get_java_cmd))
 							elif os_name == "WINDOWS":
@@ -3441,7 +3442,7 @@ class SqlAnywhereConf(BaseDB):
 							path = os.path.join("%s","WEB-INF","classes","conf:%s","WEB-INF","classes","lib","*:%s","WEB-INF",":%s","META-INF",":%s","WEB-INF","lib","*:%s","WEB-INF","classes",":%s","WEB-INF","classes","META-INF:%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
 						elif os_name == "WINDOWS":
 							path = os.path.join("%s","WEB-INF","classes","conf;%s","WEB-INF","classes","lib","*;%s","WEB-INF",";%s","META-INF",";%s","WEB-INF","lib","*;%s","WEB-INF","classes",";%s","WEB-INF","classes","META-INF;%s" )%(app_home ,app_home ,app_home, app_home, app_home, app_home ,app_home ,self.SQL_CONNECTOR_JAR)
-                                                get_java_cmd = "%s -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,ranger_log,path,className,'"'+userName+'"','"'+oldPassword+'"','"'+newPassword+'"')
+						get_java_cmd = "%s -XX:MetaspaceSize=100m -XX:MaxMetaspaceSize=200m -Xmx%s -Xms1g -Dlogdir=%s -Dlog4j.configuration=db_patch.log4j.xml -cp %s org.apache.ranger.patch.cliutil.%s %s %s %s -default"%(self.JAVA_BIN,max_memory,ranger_log,path,className,userName,oldPassword,newPassword)
 						if is_unix:
 							status = subprocess.call(shlex.split(get_java_cmd))
 						elif os_name == "WINDOWS":

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java b/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java
new file mode 100644
index 0000000..25b48bb
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java
@@ -0,0 +1,286 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ranger.biz;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.db.XXPolicyRefAccessTypeDao;
+import org.apache.ranger.db.XXPolicyRefConditionDao;
+import org.apache.ranger.db.XXPolicyRefDataMaskTypeDao;
+import org.apache.ranger.db.XXPolicyRefGroupDao;
+import org.apache.ranger.db.XXPolicyRefResourceDao;
+import org.apache.ranger.db.XXPolicyRefUserDao;
+import org.apache.ranger.entity.XXAccessTypeDef;
+import org.apache.ranger.entity.XXDataMaskTypeDef;
+import org.apache.ranger.entity.XXGroup;
+import org.apache.ranger.entity.XXPolicy;
+import org.apache.ranger.entity.XXPolicyConditionDef;
+import org.apache.ranger.entity.XXPolicyRefAccessType;
+import org.apache.ranger.entity.XXPolicyRefCondition;
+import org.apache.ranger.entity.XXPolicyRefDataMaskType;
+import org.apache.ranger.entity.XXPolicyRefGroup;
+import org.apache.ranger.entity.XXPolicyRefResource;
+import org.apache.ranger.entity.XXPolicyRefUser;
+import org.apache.ranger.entity.XXResourceDef;
+import org.apache.ranger.entity.XXServiceDef;
+import org.apache.ranger.entity.XXUser;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemDataMaskInfo;
+import org.apache.ranger.service.RangerAuditFields;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class PolicyRefUpdater {
+
+	@Autowired
+	RangerDaoManager daoMgr;
+
+	@Autowired
+	RangerAuditFields<?> rangerAuditFields;
+
+	public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy, XXServiceDef xServiceDef) throws Exception {
+		if(policy == null) {
+			return;
+		}
+
+		cleanupRefTables(policy);
+
+		final Set<String> resourceNames   = policy.getResources().keySet();
+		final Set<String> groupNames      = new HashSet<>();
+		final Set<String> userNames       = new HashSet<>();
+		final Set<String> accessTypes     = new HashSet<>();
+		final Set<String> conditionTypes  = new HashSet<>();
+		final Set<String> dataMaskTypes   = new HashSet<>();
+
+		for (List<? extends RangerPolicyItem> policyItems :  getAllPolicyItems(policy)) {
+			if (CollectionUtils.isEmpty(policyItems)) {
+				continue;
+			}
+
+			for (RangerPolicyItem policyItem : policyItems) {
+				groupNames.addAll(policyItem.getGroups());
+				userNames.addAll(policyItem.getUsers());
+
+				if (CollectionUtils.isNotEmpty(policyItem.getAccesses())) {
+					for (RangerPolicyItemAccess access : policyItem.getAccesses()) {
+						accessTypes.add(access.getType());
+					}
+				}
+
+				if (CollectionUtils.isNotEmpty(policyItem.getConditions())) {
+					for (RangerPolicyItemCondition condition : policyItem.getConditions()) {
+						conditionTypes.add(condition.getType());
+					}
+				}
+
+				if (policyItem instanceof RangerDataMaskPolicyItem) {
+					RangerPolicyItemDataMaskInfo dataMaskInfo = ((RangerDataMaskPolicyItem) policyItem).getDataMaskInfo();
+
+					dataMaskTypes.add(dataMaskInfo.getDataMaskType());
+				}
+			}
+		}
+
+		for (String resource : resourceNames) {
+			XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(resource, policy.getId());
+
+			if (xResDef == null) {
+				throw new Exception(resource + ": is not a valid resource-type. policy='"+  policy.getName() + "' service='"+ policy.getService() + "'");
+			}
+
+			XXPolicyRefResource xPolRes = rangerAuditFields.populateAuditFields(new XXPolicyRefResource(), xPolicy);
+
+			xPolRes.setPolicyId(policy.getId());
+			xPolRes.setResourceDefId(xResDef.getId());
+			xPolRes.setResourceName(resource);
+
+			daoMgr.getXXPolicyRefResource().create(xPolRes);
+		}
+
+		for (String group : groupNames) {
+			if (StringUtils.isBlank(group)) {
+				continue;
+			}
+
+			XXGroup xGroup = daoMgr.getXXGroup().findByGroupName(group);
+
+			if (xGroup == null) {
+				throw new Exception(group + ": group does not exist. policy='"+  policy.getName() + "' service='"+ policy.getService() + "' group='" + group + "'");
+			}
+
+			XXPolicyRefGroup xPolGroup = rangerAuditFields.populateAuditFields(new XXPolicyRefGroup(), xPolicy);
+
+			xPolGroup.setPolicyId(policy.getId());
+			xPolGroup.setGroupId(xGroup.getId());
+			xPolGroup.setGroupName(group);
+
+			daoMgr.getXXPolicyRefGroup().create(xPolGroup);
+		}
+
+		for (String user : userNames) {
+			if (StringUtils.isBlank(user)) {
+				continue;
+			}
+
+			XXUser xUser = daoMgr.getXXUser().findByUserName(user);
+
+			if (xUser == null) {
+				throw new Exception(user + ": user does not exist. policy='"+  policy.getName() + "' service='"+ policy.getService() + "' user='" + user +"'");
+			}
+
+			XXPolicyRefUser xPolUser = rangerAuditFields.populateAuditFields(new XXPolicyRefUser(), xPolicy);
+
+			xPolUser.setPolicyId(policy.getId());
+			xPolUser.setUserId(xUser.getId());
+			xPolUser.setUserName(user);
+
+			daoMgr.getXXPolicyRefUser().create(xPolUser);
+		}
+
+		for (String accessType : accessTypes) {
+			XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef().findByNameAndServiceId(accessType, xPolicy.getService());
+
+			if (xAccTypeDef == null) {
+				throw new Exception(accessType + ": is not a valid access-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'");
+			}
+
+			XXPolicyRefAccessType xPolAccess = rangerAuditFields.populateAuditFields(new XXPolicyRefAccessType(), xPolicy);
+
+			xPolAccess.setPolicyId(policy.getId());
+			xPolAccess.setAccessDefId(xAccTypeDef.getId());
+			xPolAccess.setAccessTypeName(accessType);
+
+			daoMgr.getXXPolicyRefAccessType().create(xPolAccess);
+		}
+
+		for (String condition : conditionTypes) {
+			XXPolicyConditionDef xPolCondDef = daoMgr.getXXPolicyConditionDef().findByServiceDefIdAndName(xServiceDef.getId(), condition);
+
+			if (xPolCondDef == null) {
+				throw new Exception(condition + ": is not a valid condition-type. policy='"+  xPolicy.getName() + "' service='"+ xPolicy.getService() + "'");
+			}
+
+			XXPolicyRefCondition xPolCond = rangerAuditFields.populateAuditFields(new XXPolicyRefCondition(), xPolicy);
+
+			xPolCond.setPolicyId(policy.getId());
+			xPolCond.setConditionDefId(xPolCondDef.getId());
+			xPolCond.setConditionName(condition);
+
+			daoMgr.getXXPolicyRefCondition().create(xPolCond);
+		}
+
+		for (String dataMaskType : dataMaskTypes ) {
+			XXDataMaskTypeDef dataMaskDef = daoMgr.getXXDataMaskTypeDef().findByNameAndServiceId(dataMaskType, xPolicy.getService());
+
+			if (dataMaskDef == null) {
+				throw new Exception(dataMaskType + ": is not a valid datamask-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'");
+			}
+
+			XXPolicyRefDataMaskType xxDataMaskInfo = new XXPolicyRefDataMaskType();
+
+			xxDataMaskInfo.setPolicyId(policy.getId());
+			xxDataMaskInfo.setDataMaskDefId(dataMaskDef.getId());
+			xxDataMaskInfo.setDataMaskTypeName(dataMaskType);
+
+			daoMgr.getXXPolicyRefDataMaskType().create(xxDataMaskInfo);
+		}
+	}
+
+	public Boolean cleanupRefTables(RangerPolicy policy) {
+		final Long policyId = policy == null ? null : policy.getId();
+
+		if (policyId == null) {
+			return false;
+		}
+
+		XXPolicyRefResourceDao     xPolResDao      = daoMgr.getXXPolicyRefResource();
+		XXPolicyRefGroupDao        xPolGroupDao    = daoMgr.getXXPolicyRefGroup();
+		XXPolicyRefUserDao         xPolUserDao     = daoMgr.getXXPolicyRefUser();
+		XXPolicyRefAccessTypeDao   xPolAccessDao   = daoMgr.getXXPolicyRefAccessType();
+		XXPolicyRefConditionDao    xPolCondDao     = daoMgr.getXXPolicyRefCondition();
+		XXPolicyRefDataMaskTypeDao xPolDataMaskDao = daoMgr.getXXPolicyRefDataMaskType();
+
+		for (XXPolicyRefResource resource : xPolResDao.findByPolicyId(policyId)) {
+			xPolResDao.remove(resource);
+		}
+
+		for(XXPolicyRefGroup group : xPolGroupDao.findByPolicyId(policyId)) {
+			xPolGroupDao.remove(group);
+		}
+
+		for(XXPolicyRefUser user : xPolUserDao.findByPolicyId(policyId)) {
+			xPolUserDao.remove(user);
+		}
+
+		for(XXPolicyRefAccessType access : xPolAccessDao.findByPolicyId(policyId)) {
+			xPolAccessDao.remove(access);
+		}
+
+		for(XXPolicyRefCondition condVal : xPolCondDao.findByPolicyId(policyId)) {
+			xPolCondDao.remove(condVal);
+		}
+
+		for(XXPolicyRefDataMaskType dataMask : xPolDataMaskDao.findByPolicyId(policyId)) {
+			xPolDataMaskDao.remove(dataMask);
+		}
+
+		return true;
+	}
+
+	static List<List<? extends RangerPolicyItem>> getAllPolicyItems(RangerPolicy policy) {
+		List<List<? extends RangerPolicyItem>> ret = new ArrayList<>();
+
+		if (CollectionUtils.isNotEmpty(policy.getPolicyItems())) {
+			ret.add(policy.getPolicyItems());
+		}
+
+		if (CollectionUtils.isNotEmpty(policy.getDenyPolicyItems())) {
+			ret.add(policy.getDenyPolicyItems());
+		}
+
+		if (CollectionUtils.isNotEmpty(policy.getAllowExceptions())) {
+			ret.add(policy.getAllowExceptions());
+		}
+
+		if (CollectionUtils.isNotEmpty(policy.getDenyExceptions())) {
+			ret.add(policy.getDenyExceptions());
+		}
+
+		if (CollectionUtils.isNotEmpty(policy.getDataMaskPolicyItems())) {
+			ret.add(policy.getDataMaskPolicyItems());
+		}
+
+		if (CollectionUtils.isNotEmpty(policy.getRowFilterPolicyItems())) {
+			ret.add(policy.getRowFilterPolicyItems());
+		}
+
+		return ret;
+	}
+}


[3/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java
new file mode 100644
index 0000000..6a21eff
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingPolicyJson_J10019.java
@@ -0,0 +1,1188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *	 http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ranger.patch;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.Logger;
+import org.apache.ranger.authorization.utils.JsonUtils;
+import org.apache.ranger.authorization.utils.StringUtil;
+import org.apache.ranger.biz.PolicyRefUpdater;
+import org.apache.ranger.biz.ServiceDBStore;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.db.XXGroupDao;
+import org.apache.ranger.db.XXPolicyDao;
+import org.apache.ranger.db.XXPolicyRefAccessTypeDao;
+import org.apache.ranger.db.XXPolicyRefConditionDao;
+import org.apache.ranger.db.XXPolicyRefDataMaskTypeDao;
+import org.apache.ranger.db.XXPolicyRefGroupDao;
+import org.apache.ranger.db.XXPolicyRefResourceDao;
+import org.apache.ranger.db.XXPolicyRefUserDao;
+import org.apache.ranger.db.XXUserDao;
+import org.apache.ranger.entity.XXAccessTypeDef;
+import org.apache.ranger.entity.XXDataMaskTypeDef;
+import org.apache.ranger.entity.XXGroup;
+import org.apache.ranger.entity.XXPolicy;
+import org.apache.ranger.entity.XXPolicyConditionDef;
+import org.apache.ranger.entity.XXPolicyItem;
+import org.apache.ranger.entity.XXPolicyItemAccess;
+import org.apache.ranger.entity.XXPolicyItemCondition;
+import org.apache.ranger.entity.XXPolicyItemDataMaskInfo;
+import org.apache.ranger.entity.XXPolicyItemGroupPerm;
+import org.apache.ranger.entity.XXPolicyItemRowFilterInfo;
+import org.apache.ranger.entity.XXPolicyItemUserPerm;
+import org.apache.ranger.entity.XXPolicyLabel;
+import org.apache.ranger.entity.XXPolicyLabelMap;
+import org.apache.ranger.entity.XXPolicyRefAccessType;
+import org.apache.ranger.entity.XXPolicyRefCondition;
+import org.apache.ranger.entity.XXPolicyRefDataMaskType;
+import org.apache.ranger.entity.XXPolicyRefGroup;
+import org.apache.ranger.entity.XXPolicyRefResource;
+import org.apache.ranger.entity.XXPolicyRefUser;
+import org.apache.ranger.entity.XXPolicyResource;
+import org.apache.ranger.entity.XXPolicyResourceMap;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXResourceDef;
+import org.apache.ranger.entity.XXService;
+import org.apache.ranger.entity.XXServiceDef;
+import org.apache.ranger.entity.XXUser;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemDataMaskInfo;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemRowFilterInfo;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem;
+import org.apache.ranger.plugin.model.RangerService;
+import org.apache.ranger.plugin.model.RangerValiditySchedule;
+import org.apache.ranger.plugin.policyevaluator.RangerPolicyItemEvaluator;
+import org.apache.ranger.plugin.util.RangerPerfTracer;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.apache.ranger.service.RangerPolicyService;
+import org.apache.ranger.util.CLIUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.TransactionCallback;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Consolidates Ranger policy details into a JSON string and stores it into a
+ * column in x_policy table After running this patch Ranger policy can be
+ * completely read/saved into x_policy table and some related Ref tables (which
+ * maintain ID->String mapping for each policy).
+ *
+ */
+@Component
+public class PatchForUpdatingPolicyJson_J10019 extends BaseLoader {
+	private static final Logger logger = Logger.getLogger(PatchForUpdatingPolicyJson_J10019.class);
+
+	@Autowired
+	RangerDaoManager daoMgr;
+
+	@Autowired
+	ServiceDBStore svcStore;
+
+	@Autowired
+	@Qualifier(value = "transactionManager")
+	PlatformTransactionManager txManager;
+
+	@Autowired
+	PolicyRefUpdater policyRefUpdater;
+
+	private final Map<String, Long>              groupIdMap         = new HashMap<>();
+	private final Map<String, Long>              userIdMap          = new HashMap<>();
+	private final Map<String, Map<String, Long>> resourceNameIdMap  = new HashMap<>();
+	private final Map<String, Map<String, Long>> accessTypeIdMap    = new HashMap<>();
+	private final Map<String, Map<String, Long>> conditionNameIdMap = new HashMap<>();
+	private final Map<String, Map<String, Long>> dataMaskTypeIdMap  = new HashMap<>();
+
+	public static void main(String[] args) {
+		logger.info("main()");
+		try {
+			PatchForUpdatingPolicyJson_J10019 loader = (PatchForUpdatingPolicyJson_J10019) CLIUtil.getBean(PatchForUpdatingPolicyJson_J10019.class);
+
+			loader.init();
+
+			while (loader.isMoreToProcess()) {
+				loader.load();
+			}
+
+			logger.info("Load complete. Exiting!!!");
+
+			System.exit(0);
+		} catch (Exception e) {
+			logger.error("Error loading", e);
+			System.exit(1);
+		}
+	}
+
+	@Override
+	public void init() throws Exception {
+		// Do Nothing
+	}
+
+	@Override
+	public void execLoad() {
+		logger.info("==> PatchForUpdatingPolicyJson.execLoad()");
+
+		try {
+			updateRangerPolicyTableWithPolicyJson();
+		} catch (Exception e) {
+			logger.error("Error while updateRangerPolicyTableWithPolicyJson()", e);
+			System.exit(1);
+		}
+
+		logger.info("<== PatchForUpdatingPolicyJson.execLoad()");
+	}
+
+	@Override
+	public void printStats() {
+		logger.info("updateRangerPolicyTableWithPolicyJson data ");
+	}
+
+	private void updateRangerPolicyTableWithPolicyJson() throws Exception {
+		logger.info("==> updateRangerPolicyTableWithPolicyJson() ");
+
+		List<RangerService> allServices = svcStore.getServices(new SearchFilter());
+
+		if (CollectionUtils.isNotEmpty(allServices)) {
+			for (RangerService service : allServices) {
+				XXService dbService = daoMgr.getXXService().getById(service.getId());
+
+				logger.info("==> Port Policies of service(name=" + dbService.getName() + ")");
+
+				RangerPolicyRetriever policyRetriever = new RangerPolicyRetriever(daoMgr, txManager);
+
+				List<RangerPolicy> policies = policyRetriever.getServicePolicies(dbService);
+
+				if (CollectionUtils.isNotEmpty(policies)) {
+					for (RangerPolicy policy : policies) {
+						policyRefUpdater.cleanupRefTables(policy);
+						portPolicy(service.getType(), policy);
+					}
+				}
+			}
+		}
+
+		logger.info("<== updateRangerPolicyTableWithPolicyJson() ");
+	}
+
+	private void portPolicy(String serviceType, RangerPolicy policy) throws Exception {
+		logger.info("==> portPolicy(id=" + policy.getId() + ")");
+
+		String policyText = JsonUtils.objectToJson(policy);
+
+		if (StringUtils.isEmpty(policyText)) {
+			throw new Exception("Failed to convert policy to json string. Policy: [id=" +  policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]");
+		}
+
+		XXPolicyDao policyDao = daoMgr.getXXPolicy();
+		XXPolicy    dbBean    = policyDao.getById(policy.getId());
+
+		dbBean.setPolicyText(policyText);
+
+		policyDao.update(dbBean);
+
+		try {
+            		Set<String> accesses = new HashSet<>();
+            		Set<String> users = new HashSet<>();
+            		Set<String> groups = new HashSet<>();
+            		Set<String> conditions = new HashSet<>();
+            		Set<String> dataMasks = new HashSet<>();
+
+            		buildLists(policy.getPolicyItems(), accesses, conditions, users, groups);
+            		buildLists(policy.getDenyPolicyItems(), accesses, conditions, users, groups);
+            		buildLists(policy.getAllowExceptions(), accesses, conditions, users, groups);
+            		buildLists(policy.getDenyExceptions(), accesses, conditions, users, groups);
+            		buildLists(policy.getDataMaskPolicyItems(), accesses, conditions, users, groups);
+            		buildLists(policy.getRowFilterPolicyItems(), accesses, conditions, users, groups);
+
+            		buildList(policy.getDataMaskPolicyItems(), dataMasks);
+
+            		addResourceDefRef(serviceType, policy);
+            		addUserNameRef(policy.getId(), users);
+            		addGroupNameRef(policy.getId(), groups);
+            		addAccessDefRef(serviceType, policy.getId(), accesses);
+            		addPolicyConditionDefRef(serviceType, policy.getId(), conditions);
+            		addDataMaskDefRef(serviceType, policy.getId(), dataMasks);
+        	} catch (Exception e) {
+		    logger.error("portPoliry(id=" + policy.getId() +") failed!!");
+		    logger.error("Offending policy:" + policyText);
+		    throw e;
+        	}
+
+		logger.info("<== portPolicy(id=" + policy.getId() + ")");
+	}
+
+	private void addResourceDefRef(String serviceType, RangerPolicy policy) throws Exception {
+		logger.info("==> addResourceDefRef(id=" + policy.getId() + ")");
+
+		Map<String, Long> serviceDefResourceNameIDMap = resourceNameIdMap.get(serviceType);
+
+		if (serviceDefResourceNameIDMap == null) {
+			serviceDefResourceNameIDMap = new HashMap<>();
+
+			resourceNameIdMap.put(serviceType, serviceDefResourceNameIDMap);
+
+			XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType);
+
+			for (XXResourceDef resourceDef : daoMgr.getXXResourceDef().findByServiceDefId(dbServiceDef.getId())) {
+				serviceDefResourceNameIDMap.put(resourceDef.getName(), resourceDef.getId());
+			}
+		}
+
+		Map<String, RangerPolicyResource> policyResources = policy.getResources();
+
+		if (MapUtils.isNotEmpty(policyResources)) {
+			XXPolicyRefResourceDao policyRefResourceDao = daoMgr.getXXPolicyRefResource();
+			Set<String>            resourceNames        = policyResources.keySet();
+
+			for (String resourceName : resourceNames) {
+				Long resourceDefId = serviceDefResourceNameIDMap.get(resourceName);
+
+				if (resourceDefId == null) {
+					throw new Exception(resourceName + ": unknown resource in policy [id=" +  policy.getId() + "; name=" + policy.getName() + "; serviceType=" + serviceType + "]. Known resources: " + serviceDefResourceNameIDMap.keySet());
+				}
+
+				// insert policy-id, resourceDefId, resourceName into Ref table
+				XXPolicyRefResource policyRefResource = new XXPolicyRefResource();
+
+				policyRefResource.setPolicyId(policy.getId());
+				policyRefResource.setResourceDefId(resourceDefId);
+				policyRefResource.setResourceName(resourceName);
+
+				policyRefResourceDao.create(policyRefResource);
+			}
+		}
+
+		logger.info("<== addResourceDefRef(id=" + policy.getId() + ")");
+	}
+
+	private void addUserNameRef(Long policyId, Set<String> users) throws Exception {
+		logger.info("==> addUserNameRef(id=" + policyId + ")");
+
+		XXPolicyRefUserDao policyRefUserDao = daoMgr.getXXPolicyRefUser();
+		XXUserDao          userDao          = daoMgr.getXXUser();
+
+		// insert policy-id, userName into Ref table
+		for (String user : users) {
+			Long userId = userIdMap.get(user);
+
+			if (userId == null) {
+				XXUser userObject = userDao.findByUserName(user);
+
+				if (userObject == null) {
+					throw new Exception(user + ": unknown user in policy [id=" + policyId + "]");
+				}
+
+				userId = userObject.getId();
+
+				userIdMap.put(user, userId);
+			}
+
+			XXPolicyRefUser policyRefUser = new XXPolicyRefUser();
+
+			policyRefUser.setPolicyId(policyId);
+			policyRefUser.setUserName(user);
+			policyRefUser.setUserId(userId);
+
+			policyRefUserDao.create(policyRefUser);
+		}
+
+		logger.info("<== addUserNameRef(id=" + policyId + ")");
+	}
+
+	private void addGroupNameRef(Long policyId, Set<String> groups) throws Exception {
+		logger.info("==> addGroupNameRef(id=" + policyId + ")");
+
+		// insert policy-id, groupName into Ref table
+		XXPolicyRefGroupDao policyRefGroupDao = daoMgr.getXXPolicyRefGroup();
+		XXGroupDao          groupDao          = daoMgr.getXXGroup();
+
+		for (String group : groups) {
+			Long groupId = groupIdMap.get(group);
+
+			if (groupId == null) {
+				XXGroup groupObject = groupDao.findByGroupName(group);
+
+				if (groupObject == null) {
+					throw new Exception(group + ": unknown group in policy [id=" + policyId + "]");
+				}
+
+				groupId = groupObject.getId();
+
+				groupIdMap.put(group, groupId);
+			}
+
+			XXPolicyRefGroup policyRefGroup = new XXPolicyRefGroup();
+
+			policyRefGroup.setPolicyId(policyId);
+			policyRefGroup.setGroupName(group);
+			policyRefGroup.setGroupId(groupId);
+
+			policyRefGroupDao.create(policyRefGroup);
+		}
+
+		logger.info("<== addGroupNameRef(id=" + policyId + ")");
+
+	}
+
+	private void addAccessDefRef(String serviceType, Long policyId, Set<String> accesses) throws Exception {
+		logger.info("==> addAccessDefRef(id=" + policyId + ")");
+		// insert policy-id, accessName into Ref table
+
+		Map<String, Long> serviceDefAccessTypeIDMap = accessTypeIdMap.get(serviceType);
+
+		if (serviceDefAccessTypeIDMap == null) {
+			serviceDefAccessTypeIDMap = new HashMap<>();
+
+			accessTypeIdMap.put(serviceType, serviceDefAccessTypeIDMap);
+
+			XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType);
+
+			for (XXAccessTypeDef accessTypeDef : daoMgr.getXXAccessTypeDef().findByServiceDefId(dbServiceDef.getId())) {
+				serviceDefAccessTypeIDMap.put(accessTypeDef.getName(), accessTypeDef.getId());
+			}
+		}
+
+		XXPolicyRefAccessTypeDao policyRefAccessTypeDao = daoMgr.getXXPolicyRefAccessType();
+
+		for (String access : accesses) {
+			Long accessTypeDefId = serviceDefAccessTypeIDMap.get(access);
+
+			if (accessTypeDefId == null) {
+				throw new Exception(access + ": unknown accessType in policy [id=" +  policyId + "; serviceType=" + serviceType + "]. Known accessTypes: " + serviceDefAccessTypeIDMap.keySet());
+			}
+
+			XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType();
+
+			policyRefAccessType.setPolicyId(policyId);
+			policyRefAccessType.setAccessTypeName(access);
+			policyRefAccessType.setAccessDefId(accessTypeDefId);
+
+			policyRefAccessTypeDao.create(policyRefAccessType);
+		}
+
+		logger.info("<== addAccessDefRef(id=" + policyId + ")");
+	}
+
+	private void addPolicyConditionDefRef(String serviceType, Long policyId, Set<String> conditions) throws Exception {
+		logger.info("==> addPolicyConditionDefRef(id=" + policyId + ")");
+		// insert policy-id, conditionName into Ref table
+
+		Map<String, Long> serviceDefConditionNameIDMap = conditionNameIdMap.get(serviceType);
+
+		if (serviceDefConditionNameIDMap == null) {
+			serviceDefConditionNameIDMap = new HashMap<>();
+
+			conditionNameIdMap.put(serviceType, serviceDefConditionNameIDMap);
+
+			XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType);
+
+			for (XXPolicyConditionDef conditionDef : daoMgr.getXXPolicyConditionDef().findByServiceDefId(dbServiceDef.getId())) {
+				serviceDefConditionNameIDMap.put(conditionDef.getName(), conditionDef.getId());
+			}
+		}
+
+		XXPolicyRefConditionDao policyRefConditionDao = daoMgr.getXXPolicyRefCondition();
+
+		for (String condition : conditions) {
+			Long conditionDefId = serviceDefConditionNameIDMap.get(condition);
+
+			if (conditionDefId == null) {
+				throw new Exception(condition + ": unknown condition in policy [id=" +  policyId + "; serviceType=" + serviceType + "]. Known conditions are: " + serviceDefConditionNameIDMap.keySet());
+			}
+
+			XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition();
+
+			policyRefCondition.setPolicyId(policyId);
+			policyRefCondition.setConditionName(condition);
+			policyRefCondition.setConditionDefId(conditionDefId);
+
+			policyRefConditionDao.create(policyRefCondition);
+		}
+
+		logger.info("<== addPolicyConditionDefRef(id=" + policyId + ")");
+	}
+
+	private void addDataMaskDefRef(String serviceType, Long policyId, Set<String> datamasks) throws Exception {
+		logger.info("==> addDataMaskDefRef(id=" + policyId + ")");
+
+		// insert policy-id, datamaskName into Ref table
+
+		Map<String, Long> serviceDefDataMaskTypeIDMap = dataMaskTypeIdMap.get(serviceType);
+
+		if (serviceDefDataMaskTypeIDMap == null) {
+			serviceDefDataMaskTypeIDMap = new HashMap<>();
+
+			dataMaskTypeIdMap.put(serviceType, serviceDefDataMaskTypeIDMap);
+
+			XXServiceDef dbServiceDef = daoMgr.getXXServiceDef().findByName(serviceType);
+
+			for (XXDataMaskTypeDef dataMaskTypeDef : daoMgr.getXXDataMaskTypeDef().findByServiceDefId(dbServiceDef.getId())) {
+				serviceDefDataMaskTypeIDMap.put(dataMaskTypeDef.getName(), dataMaskTypeDef.getId());
+			}
+		}
+
+		XXPolicyRefDataMaskTypeDao policyRefDataMaskTypeDao = daoMgr.getXXPolicyRefDataMaskType();
+
+		for (String datamask : datamasks) {
+			Long dataMaskTypeId = serviceDefDataMaskTypeIDMap.get(datamask);
+
+			if (dataMaskTypeId == null) {
+				throw new Exception(datamask + ": unknown dataMaskType in policy [id=" +  policyId + "; serviceType=" + serviceType + "]. Known dataMaskTypes " + serviceDefDataMaskTypeIDMap.keySet());
+			}
+
+			XXPolicyRefDataMaskType policyRefDataMaskType = new XXPolicyRefDataMaskType();
+
+			policyRefDataMaskType.setPolicyId(policyId);
+			policyRefDataMaskType.setDataMaskTypeName(datamask);
+			policyRefDataMaskType.setDataMaskDefId(dataMaskTypeId);
+
+			policyRefDataMaskTypeDao.create(policyRefDataMaskType);
+		}
+
+		logger.info("<== addDataMaskDefRef(id=" + policyId + ")");
+
+	}
+
+	private void buildLists(List<? extends RangerPolicyItem> policyItems, Set<String> accesses, Set<String> conditions, Set<String> users, Set<String> groups) {
+		for (RangerPolicyItem item : policyItems) {
+			for (RangerPolicyItemAccess policyAccess : item.getAccesses()) {
+				accesses.add(policyAccess.getType());
+			}
+
+			for (RangerPolicyItemCondition policyCondition : item.getConditions()) {
+				conditions.add(policyCondition.getType());
+			}
+
+			users.addAll(item.getUsers());
+			groups.addAll(item.getGroups());
+		}
+	}
+
+	private void buildList(List<RangerDataMaskPolicyItem> dataMaskPolicyItems, Set<String> dataMasks) {
+		for (RangerDataMaskPolicyItem datMaskPolicyItem : dataMaskPolicyItems) {
+			dataMasks.add(datMaskPolicyItem.getDataMaskInfo().getDataMaskType());
+		}
+	}
+
+	static private class RangerPolicyRetriever {
+		static final Log LOG      = LogFactory.getLog(RangerPolicyRetriever.class);
+		static final Log PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever");
+
+		private final RangerDaoManager daoMgr;
+		private final LookupCache      lookupCache = new LookupCache();
+
+		private final PlatformTransactionManager txManager;
+		private final TransactionTemplate        txTemplate;
+
+		RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) {
+			this.daoMgr    = daoMgr;
+			this.txManager = txManager;
+
+			if (this.txManager != null) {
+				this.txTemplate = new TransactionTemplate(this.txManager);
+
+				this.txTemplate.setReadOnly(true);
+			} else {
+				this.txTemplate = null;
+			}
+		}
+
+		private class PolicyLoaderThread extends Thread {
+			final TransactionTemplate txTemplate;
+			final XXService           xService;
+			List<RangerPolicy>        policies;
+
+			PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) {
+				this.txTemplate = txTemplate;
+				this.xService   = xService;
+			}
+
+			public List<RangerPolicy> getPolicies() {
+				return policies;
+			}
+
+			@Override
+			public void run() {
+				txTemplate.setReadOnly(true);
+				policies = txTemplate.execute(new TransactionCallback<List<RangerPolicy>>() {
+					@Override
+					public List<RangerPolicy> doInTransaction(TransactionStatus status) {
+						RetrieverContext ctx = new RetrieverContext(xService);
+						return ctx.getAllPolicies();
+					}
+				});
+			}
+		}
+
+		public List<RangerPolicy> getServicePolicies(final XXService xService) throws InterruptedException {
+			String serviceName = xService == null ? null : xService.getName();
+			Long   serviceId   = xService == null ? null : xService.getId();
+
+			if (LOG.isDebugEnabled()) {
+				LOG.debug("==> RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + ")");
+			}
+
+			List<RangerPolicy> ret  = null;
+			RangerPerfTracer   perf = null;
+
+			if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
+				perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ",serviceId=" + serviceId + ")");
+			}
+
+			if (xService != null) {
+				if (txTemplate == null) {
+					if (LOG.isDebugEnabled()) {
+						LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction");
+					}
+
+					RetrieverContext ctx = new RetrieverContext(xService);
+
+					ret = ctx.getAllPolicies();
+				} else {
+					if (LOG.isDebugEnabled()) {
+						LOG.debug("Retrieving policies in a new, read-only transaction");
+					}
+
+					PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService);
+					t.start();
+					t.join();
+					ret = t.getPolicies();
+				}
+			} else {
+				if (LOG.isDebugEnabled()) {
+					LOG.debug("RangerPolicyRetriever.getServicePolicies(xService=" + xService + "): invalid parameter");
+				}
+			}
+
+			RangerPerfTracer.log(perf);
+
+			if (LOG.isDebugEnabled()) {
+				LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName=" + serviceName + ", serviceId=" + serviceId + "): policyCount=" + (ret == null ? 0 : ret.size()));
+			}
+
+			return ret;
+		}
+
+		class LookupCache {
+			final Map<Long, String> userNames       = new HashMap<Long, String>();
+			final Map<Long, String> userScreenNames = new HashMap<Long, String>();
+			final Map<Long, String> groupNames      = new HashMap<Long, String>();
+			final Map<Long, String> accessTypes     = new HashMap<Long, String>();
+			final Map<Long, String> conditions      = new HashMap<Long, String>();
+			final Map<Long, String> resourceDefs    = new HashMap<Long, String>();
+			final Map<Long, String> dataMasks       = new HashMap<Long, String>();
+            final Map<Long, String> policyLabels    = new HashMap<Long, String>();
+
+			String getUserName(Long userId) {
+				String ret = null;
+
+				if (userId != null) {
+					ret = userNames.get(userId);
+
+					if (ret == null) {
+						XXUser user = daoMgr.getXXUser().getById(userId);
+
+						if (user != null) {
+							ret = user.getName(); // Name is `loginId`
+
+							userNames.put(userId, ret);
+						}
+					}
+				}
+
+				return ret;
+			}
+
+            String getPolicyLabelName(Long policyLabelId) {
+                String ret = null;
+
+                if (policyLabelId != null) {
+                    ret = policyLabels.get(policyLabelId);
+
+                    if (ret == null) {
+                        XXPolicyLabel xxPolicyLabel = daoMgr.getXXPolicyLabels().getById(policyLabelId);
+
+                        if (xxPolicyLabel != null) {
+                            ret = xxPolicyLabel.getPolicyLabel();
+
+                            policyLabels.put(policyLabelId, ret);
+                        }
+                    }
+                }
+
+                return ret;
+            }
+
+			String getUserScreenName(Long userId) {
+				String ret = null;
+
+				if (userId != null) {
+					ret = userScreenNames.get(userId);
+
+					if (ret == null) {
+						XXPortalUser user = daoMgr.getXXPortalUser().getById(userId);
+
+						if (user != null) {
+							ret = user.getPublicScreenName();
+
+							if (StringUtil.isEmpty(ret)) {
+								ret = user.getFirstName();
+
+								if (StringUtil.isEmpty(ret)) {
+									ret = user.getLoginId();
+								} else {
+									if (!StringUtil.isEmpty(user.getLastName())) {
+										ret += (" " + user.getLastName());
+									}
+								}
+							}
+
+							if (ret != null) {
+								userScreenNames.put(userId, ret);
+							}
+						}
+					}
+				}
+
+				return ret;
+			}
+
+			String getGroupName(Long groupId) {
+				String ret = null;
+
+				if (groupId != null) {
+					ret = groupNames.get(groupId);
+
+					if (ret == null) {
+						XXGroup group = daoMgr.getXXGroup().getById(groupId);
+
+						if (group != null) {
+							ret = group.getName();
+
+							groupNames.put(groupId, ret);
+						}
+					}
+				}
+
+				return ret;
+			}
+
+			String getAccessType(Long accessTypeId) {
+				String ret = null;
+
+				if (accessTypeId != null) {
+					ret = accessTypes.get(accessTypeId);
+
+					if (ret == null) {
+						XXAccessTypeDef xAccessType = daoMgr.getXXAccessTypeDef().getById(accessTypeId);
+
+						if (xAccessType != null) {
+							ret = xAccessType.getName();
+
+							accessTypes.put(accessTypeId, ret);
+						} else {
+							LOG.warn("getAccessType(): Canot find name for accessTypeId " + accessTypeId + ". This will cause Ranger policy migration to fail. Please check if all service-defs are migrated correctly!");
+						}
+					}
+				}
+
+				return ret;
+			}
+
+			String getConditionType(Long conditionDefId) {
+				String ret = null;
+
+				if (conditionDefId != null) {
+					ret = conditions.get(conditionDefId);
+
+					if (ret == null) {
+						XXPolicyConditionDef xPolicyConditionDef = daoMgr.getXXPolicyConditionDef()
+								.getById(conditionDefId);
+
+						if (xPolicyConditionDef != null) {
+							ret = xPolicyConditionDef.getName();
+
+							conditions.put(conditionDefId, ret);
+						}
+					}
+				}
+
+				return ret;
+			}
+
+			String getResourceName(Long resourceDefId) {
+				String ret = null;
+
+				if (resourceDefId != null) {
+					ret = resourceDefs.get(resourceDefId);
+
+					if (ret == null) {
+						XXResourceDef xResourceDef = daoMgr.getXXResourceDef().getById(resourceDefId);
+
+						if (xResourceDef != null) {
+							ret = xResourceDef.getName();
+
+							resourceDefs.put(resourceDefId, ret);
+						}
+					}
+				}
+
+				return ret;
+			}
+
+			String getDataMaskName(Long dataMaskDefId) {
+				String ret = null;
+
+				if (dataMaskDefId != null) {
+					ret = dataMasks.get(dataMaskDefId);
+
+					if (ret == null) {
+						XXDataMaskTypeDef xDataMaskDef = daoMgr.getXXDataMaskTypeDef().getById(dataMaskDefId);
+
+						if (xDataMaskDef != null) {
+							ret = xDataMaskDef.getName();
+
+							dataMasks.put(dataMaskDefId, ret);
+						}
+					}
+				}
+
+				return ret;
+			}
+		}
+
+		static List<XXPolicy> asList(XXPolicy policy) {
+			List<XXPolicy> ret = new ArrayList<XXPolicy>();
+
+			if (policy != null) {
+				ret.add(policy);
+			}
+
+			return ret;
+		}
+
+		class RetrieverContext {
+			final XXService                               service;
+			final ListIterator<XXPolicy>                  iterPolicy;
+			final ListIterator<XXPolicyResource>          iterResources;
+			final ListIterator<XXPolicyResourceMap>       iterResourceMaps;
+			final ListIterator<XXPolicyItem>              iterPolicyItems;
+			final ListIterator<XXPolicyItemUserPerm>      iterUserPerms;
+			final ListIterator<XXPolicyItemGroupPerm>     iterGroupPerms;
+			final ListIterator<XXPolicyItemAccess>        iterAccesses;
+			final ListIterator<XXPolicyItemCondition>     iterConditions;
+			final ListIterator<XXPolicyItemDataMaskInfo>  iterDataMaskInfos;
+			final ListIterator<XXPolicyItemRowFilterInfo> iterRowFilterInfos;
+            final ListIterator<XXPolicyLabelMap>          iterPolicyLabels;
+
+			RetrieverContext(XXService xService) {
+				Long           serviceId = xService == null ? null : xService.getId();
+				List<XXPolicy> xPolicies = daoMgr.getXXPolicy().findByServiceId(serviceId);
+
+				this.service    = xService;
+				this.iterPolicy = xPolicies.listIterator();
+
+				List<XXPolicyResource>          xResources      = daoMgr.getXXPolicyResource().findByServiceId(serviceId);
+				List<XXPolicyResourceMap>       xResourceMaps   = daoMgr.getXXPolicyResourceMap().findByServiceId(serviceId);
+				List<XXPolicyItem>              xPolicyItems    = daoMgr.getXXPolicyItem().findByServiceId(serviceId);
+				List<XXPolicyItemUserPerm>      xUserPerms      = daoMgr.getXXPolicyItemUserPerm().findByServiceId(serviceId);
+				List<XXPolicyItemGroupPerm>     xGroupPerms     = daoMgr.getXXPolicyItemGroupPerm().findByServiceId(serviceId);
+				List<XXPolicyItemAccess>        xAccesses       = daoMgr.getXXPolicyItemAccess().findByServiceId(serviceId);
+				List<XXPolicyItemCondition>     xConditions     = daoMgr.getXXPolicyItemCondition().findByServiceId(serviceId);
+				List<XXPolicyItemDataMaskInfo>  xDataMaskInfos  = daoMgr.getXXPolicyItemDataMaskInfo().findByServiceId(serviceId);
+				List<XXPolicyItemRowFilterInfo> xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByServiceId(serviceId);
+                List<XXPolicyLabelMap>          xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId);
+
+				this.iterResources      = xResources.listIterator();
+				this.iterResourceMaps   = xResourceMaps.listIterator();
+				this.iterPolicyItems    = xPolicyItems.listIterator();
+				this.iterUserPerms      = xUserPerms.listIterator();
+				this.iterGroupPerms     = xGroupPerms.listIterator();
+				this.iterAccesses       = xAccesses.listIterator();
+				this.iterConditions     = xConditions.listIterator();
+				this.iterDataMaskInfos  = xDataMaskInfos.listIterator();
+				this.iterRowFilterInfos = xRowFilterInfos.listIterator();
+                this.iterPolicyLabels   = xPolicyLabelMap.listIterator();
+			}
+
+			RetrieverContext(XXPolicy xPolicy, XXService xService) {
+				Long           policyId  = xPolicy == null ? null : xPolicy.getId();
+				List<XXPolicy> xPolicies = asList(xPolicy);
+
+				this.service    = xService;
+				this.iterPolicy = xPolicies.listIterator();
+
+				List<XXPolicyResource>          xResources      = daoMgr.getXXPolicyResource().findByPolicyId(policyId);
+				List<XXPolicyResourceMap>       xResourceMaps   = daoMgr.getXXPolicyResourceMap().findByPolicyId(policyId);
+				List<XXPolicyItem>              xPolicyItems    = daoMgr.getXXPolicyItem().findByPolicyId(policyId);
+				List<XXPolicyItemUserPerm>      xUserPerms      = daoMgr.getXXPolicyItemUserPerm().findByPolicyId(policyId);
+				List<XXPolicyItemGroupPerm>     xGroupPerms     = daoMgr.getXXPolicyItemGroupPerm().findByPolicyId(policyId);
+				List<XXPolicyItemAccess>        xAccesses       = daoMgr.getXXPolicyItemAccess().findByPolicyId(policyId);
+				List<XXPolicyItemCondition>     xConditions     = daoMgr.getXXPolicyItemCondition().findByPolicyId(policyId);
+				List<XXPolicyItemDataMaskInfo>  xDataMaskInfos  = daoMgr.getXXPolicyItemDataMaskInfo().findByPolicyId(policyId);
+				List<XXPolicyItemRowFilterInfo> xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByPolicyId(policyId);
+                List<XXPolicyLabelMap>          xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByPolicyId(policyId);
+
+				this.iterResources      = xResources.listIterator();
+				this.iterResourceMaps   = xResourceMaps.listIterator();
+				this.iterPolicyItems    = xPolicyItems.listIterator();
+				this.iterUserPerms      = xUserPerms.listIterator();
+				this.iterGroupPerms     = xGroupPerms.listIterator();
+				this.iterAccesses       = xAccesses.listIterator();
+				this.iterConditions     = xConditions.listIterator();
+				this.iterDataMaskInfos  = xDataMaskInfos.listIterator();
+				this.iterRowFilterInfos = xRowFilterInfos.listIterator();
+                this.iterPolicyLabels   = xPolicyLabelMap.listIterator();
+			}
+
+			RangerPolicy getNextPolicy() {
+				RangerPolicy ret = null;
+
+				if (iterPolicy.hasNext()) {
+					XXPolicy xPolicy = iterPolicy.next();
+
+					if (xPolicy != null) {
+						ret = new RangerPolicy();
+
+						ret.setId(xPolicy.getId());
+						ret.setGuid(xPolicy.getGuid());
+						ret.setIsEnabled(xPolicy.getIsEnabled());
+						ret.setCreatedBy(lookupCache.getUserScreenName(xPolicy.getAddedByUserId()));
+						ret.setUpdatedBy(lookupCache.getUserScreenName(xPolicy.getUpdatedByUserId()));
+						ret.setCreateTime(xPolicy.getCreateTime());
+						ret.setUpdateTime(xPolicy.getUpdateTime());
+						ret.setVersion(xPolicy.getVersion());
+						ret.setService(service == null ? null : service.getName());
+						ret.setName(StringUtils.trim(xPolicy.getName()));
+						ret.setPolicyType(xPolicy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : xPolicy.getPolicyType());
+						ret.setDescription(xPolicy.getDescription());
+						ret.setResourceSignature(xPolicy.getResourceSignature());
+						ret.setIsAuditEnabled(xPolicy.getIsAuditEnabled());
+						ret.setPolicyPriority(xPolicy.getPolicyPriority());
+
+						Map<String, String> mapOfOptions = JsonUtils.jsonToMapStringString(xPolicy.getOptions());
+
+						if (MapUtils.isNotEmpty(mapOfOptions)) {
+							String validitySchedulesStr = mapOfOptions.get(RangerPolicyService.OPTION_POLICY_VALIDITY_SCHEDULES);
+
+							if (StringUtils.isNotEmpty(validitySchedulesStr)) {
+								List<RangerValiditySchedule> validitySchedules = JsonUtils.jsonToRangerValiditySchedule(validitySchedulesStr);
+
+								ret.setValiditySchedules(validitySchedules);
+							}
+						}
+
+						getPolicyLabels(ret);
+						getResource(ret);
+						getPolicyItems(ret);
+					}
+				}
+
+				return ret;
+			}
+
+            private void getPolicyLabels(RangerPolicy ret) {
+                List<String> xPolicyLabels = new ArrayList<String>();
+                while (iterPolicyLabels.hasNext()) {
+                    XXPolicyLabelMap xPolicyLabel = iterPolicyLabels.next();
+                    if (xPolicyLabel.getPolicyId().equals(ret.getId())) {
+                        String policyLabel = lookupCache.getPolicyLabelName(xPolicyLabel.getPolicyLabelId());
+                        if (policyLabel != null) {
+                            xPolicyLabels.add(policyLabel);
+                        }
+                        ret.setPolicyLabels(xPolicyLabels);
+                    } else {
+                        if (iterPolicyLabels.hasPrevious()) {
+                            iterPolicyLabels.previous();
+                        }
+                        break;
+                    }
+                }
+            }
+
+			List<RangerPolicy> getAllPolicies() {
+				List<RangerPolicy> ret = new ArrayList<RangerPolicy>();
+
+				while (iterPolicy.hasNext()) {
+					RangerPolicy policy = getNextPolicy();
+
+					if (policy != null) {
+						ret.add(policy);
+					}
+				}
+
+				if (!hasProcessedAll()) {
+					LOG.warn("getAllPolicies(): perhaps one or more policies got updated during retrieval. Falling back to secondary method");
+
+					ret = getAllPoliciesBySecondary();
+				}
+
+				return ret;
+			}
+
+			List<RangerPolicy> getAllPoliciesBySecondary() {
+				List<RangerPolicy> ret = null;
+
+				if (service != null) {
+					List<XXPolicy> xPolicies = daoMgr.getXXPolicy().findByServiceId(service.getId());
+
+					if (CollectionUtils.isNotEmpty(xPolicies)) {
+						ret = new ArrayList<RangerPolicy>(xPolicies.size());
+
+						for (XXPolicy xPolicy : xPolicies) {
+							RetrieverContext ctx = new RetrieverContext(xPolicy, service);
+
+							RangerPolicy policy = ctx.getNextPolicy();
+
+							if (policy != null) {
+								ret.add(policy);
+							}
+						}
+					}
+				}
+
+				return ret;
+			}
+
+			private boolean hasProcessedAll() {
+				boolean moreToProcess = iterPolicy.hasNext() || iterResources.hasNext() || iterResourceMaps.hasNext()
+						|| iterPolicyItems.hasNext() || iterUserPerms.hasNext() || iterGroupPerms.hasNext()
+						|| iterAccesses.hasNext() || iterConditions.hasNext() || iterDataMaskInfos.hasNext()
+						|| iterRowFilterInfos.hasNext() || iterPolicyLabels.hasNext();
+
+				return !moreToProcess;
+			}
+
+			private void getResource(RangerPolicy policy) {
+				while (iterResources.hasNext()) {
+					XXPolicyResource xResource = iterResources.next();
+
+					if (xResource.getPolicyid().equals(policy.getId())) {
+						RangerPolicyResource resource = new RangerPolicyResource();
+
+						resource.setIsExcludes(xResource.getIsexcludes());
+						resource.setIsRecursive(xResource.getIsrecursive());
+
+						while (iterResourceMaps.hasNext()) {
+							XXPolicyResourceMap xResourceMap = iterResourceMaps.next();
+
+							if (xResourceMap.getResourceid().equals(xResource.getId())) {
+								resource.getValues().add(xResourceMap.getValue());
+							} else {
+								if (iterResourceMaps.hasPrevious()) {
+									iterResourceMaps.previous();
+								}
+
+								break;
+							}
+						}
+
+						policy.getResources().put(lookupCache.getResourceName(xResource.getResdefid()), resource);
+					} else if (xResource.getPolicyid().compareTo(policy.getId()) > 0) {
+						if (iterResources.hasPrevious()) {
+							iterResources.previous();
+						}
+
+						break;
+					}
+				}
+			}
+
+			private void getPolicyItems(RangerPolicy policy) {
+				while (iterPolicyItems.hasNext()) {
+					XXPolicyItem xPolicyItem = iterPolicyItems.next();
+
+					if (xPolicyItem.getPolicyid().equals(policy.getId())) {
+						final RangerPolicyItem          policyItem;
+						final RangerDataMaskPolicyItem  dataMaskPolicyItem;
+						final RangerRowFilterPolicyItem rowFilterPolicyItem;
+
+						if (xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) {
+							dataMaskPolicyItem  = new RangerDataMaskPolicyItem();
+							rowFilterPolicyItem = null;
+							policyItem          = dataMaskPolicyItem;
+						} else if (xPolicyItem.getItemType() == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) {
+							dataMaskPolicyItem  = null;
+							rowFilterPolicyItem = new RangerRowFilterPolicyItem();
+							policyItem          = rowFilterPolicyItem;
+						} else {
+							dataMaskPolicyItem  = null;
+							rowFilterPolicyItem = null;
+							policyItem          = new RangerPolicyItem();
+						}
+
+						while (iterAccesses.hasNext()) {
+							XXPolicyItemAccess xAccess = iterAccesses.next();
+
+							if (xAccess.getPolicyitemid().equals(xPolicyItem.getId())) {
+								policyItem.getAccesses().add(new RangerPolicyItemAccess(lookupCache.getAccessType(xAccess.getType()), xAccess.getIsallowed()));
+							} else {
+								if (iterAccesses.hasPrevious()) {
+									iterAccesses.previous();
+								}
+
+								break;
+							}
+						}
+
+						while (iterUserPerms.hasNext()) {
+							XXPolicyItemUserPerm xUserPerm = iterUserPerms.next();
+
+							if (xUserPerm.getPolicyitemid().equals(xPolicyItem.getId())) {
+								String userName = lookupCache.getUserName(xUserPerm.getUserid());
+
+								if (userName != null) {
+									policyItem.getUsers().add(userName);
+								}
+							} else {
+								if (iterUserPerms.hasPrevious()) {
+									iterUserPerms.previous();
+								}
+
+								break;
+							}
+						}
+
+						while (iterGroupPerms.hasNext()) {
+							XXPolicyItemGroupPerm xGroupPerm = iterGroupPerms.next();
+
+							if (xGroupPerm.getPolicyitemid().equals(xPolicyItem.getId())) {
+								String groupName = lookupCache.getGroupName(xGroupPerm.getGroupid());
+
+								if (groupName != null) {
+									policyItem.getGroups().add(groupName);
+								}
+							} else {
+								if (iterGroupPerms.hasPrevious()) {
+									iterGroupPerms.previous();
+								}
+
+								break;
+							}
+						}
+
+						RangerPolicyItemCondition condition         = null;
+						Long                      prevConditionType = null;
+
+						while (iterConditions.hasNext()) {
+							XXPolicyItemCondition xCondition = iterConditions.next();
+
+							if (xCondition.getPolicyitemid().equals(xPolicyItem.getId())) {
+								if (!xCondition.getType().equals(prevConditionType)) {
+									condition = new RangerPolicyItemCondition();
+
+									condition.setType(lookupCache.getConditionType(xCondition.getType()));
+									condition.getValues().add(xCondition.getValue());
+
+									policyItem.getConditions().add(condition);
+
+									prevConditionType = xCondition.getType();
+								} else {
+									condition.getValues().add(xCondition.getValue());
+								}
+							} else {
+								if (iterConditions.hasPrevious()) {
+									iterConditions.previous();
+								}
+
+								break;
+							}
+						}
+
+						policyItem.setDelegateAdmin(xPolicyItem.getDelegateAdmin());
+
+						if (dataMaskPolicyItem != null) {
+							while (iterDataMaskInfos.hasNext()) {
+								XXPolicyItemDataMaskInfo xDataMaskInfo = iterDataMaskInfos.next();
+
+								if (xDataMaskInfo.getPolicyItemId().equals(xPolicyItem.getId())) {
+									dataMaskPolicyItem.setDataMaskInfo(new RangerPolicyItemDataMaskInfo(lookupCache.getDataMaskName(xDataMaskInfo.getType()), xDataMaskInfo.getConditionExpr(), xDataMaskInfo.getValueExpr()));
+								} else {
+									if (iterDataMaskInfos.hasPrevious()) {
+										iterDataMaskInfos.previous();
+									}
+
+									break;
+								}
+							}
+						}
+
+						if (rowFilterPolicyItem != null) {
+							while (iterRowFilterInfos.hasNext()) {
+								XXPolicyItemRowFilterInfo xRowFilterInfo = iterRowFilterInfos.next();
+
+								if (xRowFilterInfo.getPolicyItemId().equals(xPolicyItem.getId())) {
+									rowFilterPolicyItem.setRowFilterInfo(new RangerPolicyItemRowFilterInfo(xRowFilterInfo.getFilterExpr()));
+								} else {
+									if (iterRowFilterInfos.hasPrevious()) {
+										iterRowFilterInfos.previous();
+									}
+
+									break;
+								}
+							}
+						}
+
+						int itemType = xPolicyItem.getItemType() == null ? RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW : xPolicyItem.getItemType();
+
+						if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW) {
+							policy.getPolicyItems().add(policyItem);
+						} else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY) {
+							policy.getDenyPolicyItems().add(policyItem);
+						} else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS) {
+							policy.getAllowExceptions().add(policyItem);
+						} else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS) {
+							policy.getDenyExceptions().add(policyItem);
+						} else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK) {
+							policy.getDataMaskPolicyItems().add(dataMaskPolicyItem);
+						} else if (itemType == RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER) {
+							policy.getRowFilterPolicyItems().add(rowFilterPolicyItem);
+						} else { // unknown itemType
+							LOG.warn("RangerPolicyRetriever.getPolicy(policyId=" + policy.getId() + "): ignoring unknown policyItemType " + itemType);
+						}
+					} else if (xPolicyItem.getPolicyid().compareTo(policy.getId()) > 0) {
+						if (iterPolicyItems.hasPrevious()) {
+							iterPolicyItems.previous();
+						}
+
+						break;
+					}
+				}
+			}
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java
new file mode 100644
index 0000000..035e023
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/patch/PatchForUpdatingTagsJson_J10020.java
@@ -0,0 +1,789 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *	 http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Consolidates Ranger policy details into a JSON string and stores it into a
+ * column in x_policy table After running this patch Ranger policy can be
+ * completely read/saved into x_policy table and some related Ref tables (which
+ * maintain ID->String mapping for each policy).
+ *
+ */
+
+package org.apache.ranger.patch;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Map;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.Logger;
+import org.apache.ranger.authorization.utils.JsonUtils;
+import org.apache.ranger.authorization.utils.StringUtil;
+import org.apache.ranger.biz.ServiceDBStore;
+import org.apache.ranger.biz.TagDBStore;
+import org.apache.ranger.db.RangerDaoManager;
+import org.apache.ranger.entity.XXPortalUser;
+import org.apache.ranger.entity.XXResourceDef;
+import org.apache.ranger.entity.XXService;
+import org.apache.ranger.entity.XXServiceResource;
+import org.apache.ranger.entity.XXServiceResourceElement;
+import org.apache.ranger.entity.XXServiceResourceElementValue;
+import org.apache.ranger.entity.XXTag;
+import org.apache.ranger.entity.XXTagAttribute;
+import org.apache.ranger.entity.XXTagAttributeDef;
+import org.apache.ranger.entity.XXTagDef;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerService;
+import org.apache.ranger.plugin.model.RangerServiceResource;
+import org.apache.ranger.plugin.model.RangerTag;
+import org.apache.ranger.plugin.model.RangerTagDef;
+import org.apache.ranger.plugin.model.RangerValiditySchedule;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.apache.ranger.service.RangerServiceResourceService;
+import org.apache.ranger.service.RangerTagDefService;
+import org.apache.ranger.service.RangerTagService;
+import org.apache.ranger.util.CLIUtil;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.TransactionCallback;
+import org.springframework.transaction.support.TransactionTemplate;
+
+@Component
+public class PatchForUpdatingTagsJson_J10020 extends BaseLoader {
+
+    private static final Logger logger = Logger.getLogger(PatchForUpdatingTagsJson_J10020.class);
+
+    @Autowired
+    RangerDaoManager daoMgr;
+
+    @Autowired
+    ServiceDBStore svcStore;
+
+    @Autowired
+    TagDBStore tagStore;
+
+    @Autowired
+    @Qualifier(value = "transactionManager")
+    PlatformTransactionManager txManager;
+
+    @Autowired
+    RangerTagDefService tagDefService;
+
+    @Autowired
+    RangerTagService tagService;
+
+    @Autowired
+    RangerServiceResourceService serviceResourceService;
+
+    public static void main(String[] args) {
+        logger.info("main()");
+        try {
+            PatchForUpdatingTagsJson_J10020 loader = (PatchForUpdatingTagsJson_J10020) CLIUtil
+                    .getBean(PatchForUpdatingTagsJson_J10020.class);
+
+            loader.init();
+
+            while (loader.isMoreToProcess()) {
+                loader.load();
+            }
+
+            logger.info("Load complete. Exiting!!!");
+
+            System.exit(0);
+        } catch (Exception e) {
+            logger.error("Error loading", e);
+            System.exit(1);
+        }
+    }
+
+    @Override
+    public void init() throws Exception {
+        // Do Nothing
+    }
+
+    @Override
+    public void execLoad() {
+        logger.info("==> PatchForUpdatingTagsJson.execLoad()");
+
+        try {
+            updateRangerTagsTablesWithTagsJson();
+        } catch (Exception e) {
+            logger.error("Error while UpdateRangerTagsTablesWithTagsJson()", e);
+            System.exit(1);
+        }
+
+        logger.info("<== PatchForUpdatingTagsJson.execLoad()");
+    }
+
+    @Override
+    public void printStats() {
+        logger.info("Update Ranger Tags Tables with Json data ");
+    }
+
+    private void updateRangerTagsTablesWithTagsJson() throws Exception {
+        logger.info("==> updateRangerTagsTablesWithTagsJson() ");
+
+        List<RangerService> allServices = svcStore.getServices(new SearchFilter());
+
+        if (CollectionUtils.isNotEmpty(allServices)) {
+            for (RangerService service : allServices) {
+                XXService                   dbService        = daoMgr.getXXService().getById(service.getId());
+                RangerTagDBRetriever        tagsRetriever    = new RangerTagDBRetriever(daoMgr, txManager, dbService);
+                Map<Long, RangerTagDef>     tagDefs          = tagsRetriever.getTagDefs();
+                Map<Long, RangerTag>        tags             = tagsRetriever.getTags();
+                List<RangerServiceResource> serviceResources = tagsRetriever.getServiceResources();
+
+                if (MapUtils.isNotEmpty(tagDefs)) {
+                    logger.info("==> Port " + tagDefs.size() + " Tag Definitions for service(name=" + dbService.getName() + ")");
+
+                    for (Map.Entry<Long, RangerTagDef> entry : tagDefs.entrySet()) {
+                        RangerTagDef tagDef = entry.getValue();
+
+                        portTagDef(tagDef);
+                    }
+                }
+
+                if (MapUtils.isNotEmpty(tags)) {
+                    logger.info("==> Port " + tags.size() + " Tags for service(name=" + dbService.getName() + ")");
+
+                    for (Map.Entry<Long, RangerTag> entry : tags.entrySet()) {
+                        RangerTag tag = entry.getValue();
+
+                        portTag(tag);
+                    }
+                }
+
+                if (CollectionUtils.isNotEmpty(serviceResources)) {
+                    logger.info("==> Port " + serviceResources.size() + " Service Resources for service(name=" + dbService.getName() + ")");
+
+                    for (RangerServiceResource serviceResource : serviceResources) {
+                        portServiceResource(serviceResource);
+                    }
+                }
+            }
+        }
+
+        logger.info("<== updateRangerTagsTablesWithTagsJson() ");
+    }
+
+    private void portTagDef(RangerTagDef tagDef) {
+        tagDefService.update(tagDef);
+    }
+
+    private void portTag(RangerTag tag) {
+        tagService.update(tag);
+    }
+
+    private void portServiceResource(RangerServiceResource serviceResource) throws Exception {
+        serviceResourceService.update(serviceResource);
+        tagStore.refreshServiceResource(serviceResource.getId());
+    }
+
+    private class RangerTagDBRetriever {
+        final Log LOG = LogFactory.getLog(RangerTagDBRetriever.class);
+
+        private final RangerDaoManager                 daoMgr;
+        private final XXService                        xService;
+        private final RangerTagDBRetriever.LookupCache lookupCache;
+        private final PlatformTransactionManager       txManager;
+        private final TransactionTemplate              txTemplate;
+        private       List<RangerServiceResource>      serviceResources;
+        private       Map<Long, RangerTagDef>          tagDefs;
+        private       Map<Long, RangerTag>             tags;
+
+        RangerTagDBRetriever(final RangerDaoManager daoMgr, final PlatformTransactionManager txManager, final XXService xService) throws InterruptedException {
+            this.daoMgr      = daoMgr;
+            this.xService    = xService;
+            this.lookupCache = new RangerTagDBRetriever.LookupCache();
+            this.txManager   = txManager;
+
+            if (this.txManager != null) {
+                this.txTemplate = new TransactionTemplate(this.txManager);
+                this.txTemplate.setReadOnly(true);
+            } else {
+                this.txTemplate = null;
+            }
+
+            if (this.daoMgr != null && this.xService != null) {
+                if (this.txTemplate == null) {
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug("Load Tags in the same thread and using an existing transaction");
+                    }
+
+                    if (!initializeTagCache(xService)) {
+                        LOG.error("Failed to get tags for service:[" + xService.getName() + "] in the same thread and using an existing transaction");
+                    }
+                } else {
+                    if (LOG.isDebugEnabled()) {
+                        LOG.debug("Load Tags in a separate thread and using a new transaction");
+                    }
+
+                    RangerTagDBRetriever.TagLoaderThread t = new RangerTagDBRetriever.TagLoaderThread(txTemplate, xService);
+                    t.setDaemon(true);
+                    t.start();
+                    t.join();
+                }
+
+            }
+        }
+
+        List<RangerServiceResource> getServiceResources() {
+            return serviceResources;
+        }
+
+        Map<Long, RangerTagDef> getTagDefs() {
+            return tagDefs;
+        }
+
+        Map<Long, RangerTag> getTags() {
+            return tags;
+        }
+
+        private boolean initializeTagCache(XXService xService) {
+            boolean ret;
+            RangerTagDBRetriever.TagRetrieverServiceResourceContext serviceResourceContext  = new RangerTagDBRetriever.TagRetrieverServiceResourceContext(xService);
+            RangerTagDBRetriever.TagRetrieverTagDefContext          tagDefContext           = new RangerTagDBRetriever.TagRetrieverTagDefContext(xService);
+            RangerTagDBRetriever.TagRetrieverTagContext             tagContext              = new RangerTagDBRetriever.TagRetrieverTagContext(xService);
+
+            serviceResources = serviceResourceContext.getAllServiceResources();
+            tagDefs          = tagDefContext.getAllTagDefs();
+            tags             = tagContext.getAllTags();
+
+            ret = true;
+            return ret;
+        }
+
+        private <T> List<T> asList(T obj) {
+            List<T> ret = new ArrayList<>();
+
+            if (obj != null) {
+                ret.add(obj);
+            }
+
+            return ret;
+        }
+
+        private class LookupCache {
+            final Map<Long, String> userScreenNames = new HashMap<>();
+            final Map<Long, String> resourceDefs    = new HashMap<>();
+
+            String getUserScreenName(Long userId) {
+                String ret = null;
+
+                if (userId != null) {
+                    ret = userScreenNames.get(userId);
+
+                    if (ret == null) {
+                        XXPortalUser user = daoMgr.getXXPortalUser().getById(userId);
+
+                        if (user != null) {
+                            ret = user.getPublicScreenName();
+
+                            if (StringUtil.isEmpty(ret)) {
+                                ret = user.getFirstName();
+
+                                if (StringUtil.isEmpty(ret)) {
+                                    ret = user.getLoginId();
+                                } else {
+                                    if (!StringUtil.isEmpty(user.getLastName())) {
+                                        ret += (" " + user.getLastName());
+                                    }
+                                }
+                            }
+
+                            if (ret != null) {
+                                userScreenNames.put(userId, ret);
+                            }
+                        }
+                    }
+                }
+
+                return ret;
+            }
+
+            String getResourceName(Long resourceDefId) {
+                String ret = null;
+
+                if (resourceDefId != null) {
+                    ret = resourceDefs.get(resourceDefId);
+
+                    if (ret == null) {
+                        XXResourceDef xResourceDef = daoMgr.getXXResourceDef().getById(resourceDefId);
+
+                        if (xResourceDef != null) {
+                            ret = xResourceDef.getName();
+
+                            resourceDefs.put(resourceDefId, ret);
+                        }
+                    }
+                }
+
+                return ret;
+            }
+        }
+
+        private class TagLoaderThread extends Thread {
+            final TransactionTemplate txTemplate;
+            final XXService           xService;
+
+            TagLoaderThread(TransactionTemplate txTemplate, final XXService xService) {
+                this.txTemplate = txTemplate;
+                this.xService   = xService;
+            }
+
+            @Override
+            public void run() {
+                txTemplate.setReadOnly(true);
+                Boolean result = txTemplate.execute(new TransactionCallback<Boolean>() {
+                    @Override
+                    public Boolean doInTransaction(TransactionStatus status) {
+                        boolean ret = initializeTagCache(xService);
+
+                        if (!ret) {
+                            status.setRollbackOnly();
+                            LOG.error("Failed to get tags for service:[" + xService.getName() + "] in a new transaction");
+                        }
+                        return ret;
+                    }
+                });
+
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("transaction result:[" + result +"]");
+                }
+            }
+        }
+
+        private class TagRetrieverServiceResourceContext {
+            final XXService                                   service;
+            final ListIterator<XXServiceResource>             iterServiceResource;
+            final ListIterator<XXServiceResourceElement>      iterServiceResourceElement;
+            final ListIterator<XXServiceResourceElementValue> iterServiceResourceElementValue;
+
+            TagRetrieverServiceResourceContext(XXService xService) {
+                Long                                serviceId                     = xService == null ? null : xService.getId();
+                List<XXServiceResource>             xServiceResources             = daoMgr.getXXServiceResource().findByServiceId(serviceId);
+                List<XXServiceResourceElement>      xServiceResourceElements      = daoMgr.getXXServiceResourceElement().findTaggedResourcesInServiceId(serviceId);
+                List<XXServiceResourceElementValue> xServiceResourceElementValues = daoMgr.getXXServiceResourceElementValue().findTaggedResourcesInServiceId(serviceId);
+
+                this.service                         = xService;
+                this.iterServiceResource             = xServiceResources.listIterator();
+                this.iterServiceResourceElement      = xServiceResourceElements.listIterator();
+                this.iterServiceResourceElementValue = xServiceResourceElementValues.listIterator();
+
+            }
+
+            TagRetrieverServiceResourceContext(XXServiceResource xServiceResource, XXService xService) {
+                Long                                resourceId                    = xServiceResource == null ? null : xServiceResource.getId();
+                List<XXServiceResource>             xServiceResources             = asList(xServiceResource);
+                List<XXServiceResourceElement>      xServiceResourceElements      = daoMgr.getXXServiceResourceElement().findByResourceId(resourceId);
+                List<XXServiceResourceElementValue> xServiceResourceElementValues = daoMgr.getXXServiceResourceElementValue().findByResourceId(resourceId);
+
+                this.service                         = xService;
+                this.iterServiceResource             = xServiceResources.listIterator();
+                this.iterServiceResourceElement      = xServiceResourceElements.listIterator();
+                this.iterServiceResourceElementValue = xServiceResourceElementValues.listIterator();
+            }
+
+            List<RangerServiceResource> getAllServiceResources() {
+                List<RangerServiceResource> ret = new ArrayList<>();
+
+                while (iterServiceResource.hasNext()) {
+                    RangerServiceResource serviceResource = getNextServiceResource();
+
+                    if (serviceResource != null) {
+                        ret.add(serviceResource);
+                    }
+                }
+
+                if (!hasProcessedAll()) {
+                    LOG.warn("getAllServiceResources(): perhaps one or more serviceResources got updated during retrieval. Using fallback ... ");
+
+                    ret = getServiceResourcesBySecondary();
+                }
+
+                return ret;
+            }
+
+            RangerServiceResource getNextServiceResource() {
+                RangerServiceResource ret = null;
+
+                if (iterServiceResource.hasNext()) {
+                    XXServiceResource xServiceResource = iterServiceResource.next();
+
+                    if (xServiceResource != null) {
+                        ret = new RangerServiceResource();
+
+                        ret.setId(xServiceResource.getId());
+                        ret.setGuid(xServiceResource.getGuid());
+                        ret.setIsEnabled(xServiceResource.getIsEnabled());
+                        ret.setCreatedBy(lookupCache.getUserScreenName(xServiceResource.getAddedByUserId()));
+                        ret.setUpdatedBy(lookupCache.getUserScreenName(xServiceResource.getUpdatedByUserId()));
+                        ret.setCreateTime(xServiceResource.getCreateTime());
+                        ret.setUpdateTime(xServiceResource.getUpdateTime());
+                        ret.setVersion(xServiceResource.getVersion());
+                        ret.setResourceSignature(xServiceResource.getResourceSignature());
+                        ret.setServiceName(xService.getName());
+
+                        getServiceResourceElements(ret);
+                    }
+                }
+
+                return ret;
+            }
+
+            void getServiceResourceElements(RangerServiceResource serviceResource) {
+                while (iterServiceResourceElement.hasNext()) {
+                    XXServiceResourceElement xServiceResourceElement = iterServiceResourceElement.next();
+
+                    if (xServiceResourceElement.getResourceId().equals(serviceResource.getId())) {
+                        RangerPolicy.RangerPolicyResource resource = new RangerPolicy.RangerPolicyResource();
+
+                        resource.setIsExcludes(xServiceResourceElement.getIsExcludes());
+                        resource.setIsRecursive(xServiceResourceElement.getIsRecursive());
+
+                        while (iterServiceResourceElementValue.hasNext()) {
+                            XXServiceResourceElementValue xServiceResourceElementValue = iterServiceResourceElementValue.next();
+
+                            if (xServiceResourceElementValue.getResElementId().equals(xServiceResourceElement.getId())) {
+                                resource.getValues().add(xServiceResourceElementValue.getValue());
+                            } else {
+                                if (iterServiceResourceElementValue.hasPrevious()) {
+                                    iterServiceResourceElementValue.previous();
+                                }
+
+                                break;
+                            }
+                        }
+
+                        serviceResource.getResourceElements().put(lookupCache.getResourceName(xServiceResourceElement.getResDefId()), resource);
+                    } else if (xServiceResourceElement.getResourceId().compareTo(serviceResource.getId()) > 0) {
+                        if (iterServiceResourceElement.hasPrevious()) {
+                            iterServiceResourceElement.previous();
+                        }
+
+                        break;
+                    }
+                }
+            }
+
+            boolean hasProcessedAll() {
+                boolean moreToProcess = iterServiceResource.hasNext()
+                        || iterServiceResourceElement.hasNext()
+                        || iterServiceResourceElementValue.hasNext();
+
+                return !moreToProcess;
+            }
+
+            List<RangerServiceResource> getServiceResourcesBySecondary() {
+                List<RangerServiceResource> ret = null;
+
+                if (service != null) {
+                    List<XXServiceResource> xServiceResources = daoMgr.getXXServiceResource().findTaggedResourcesInServiceId(service.getId());
+
+                    if (CollectionUtils.isNotEmpty(xServiceResources)) {
+                        ret = new ArrayList<>(xServiceResources.size());
+
+                        for (XXServiceResource xServiceResource : xServiceResources) {
+                            RangerTagDBRetriever.TagRetrieverServiceResourceContext ctx = new RangerTagDBRetriever.TagRetrieverServiceResourceContext(xServiceResource, service);
+
+                            RangerServiceResource serviceResource = ctx.getNextServiceResource();
+
+                            if (serviceResource != null) {
+                                ret.add(serviceResource);
+                            }
+                        }
+                    }
+                }
+                return ret;
+            }
+        }
+
+        private class TagRetrieverTagDefContext {
+            final XXService                       service;
+            final ListIterator<XXTagDef>          iterTagDef;
+            final ListIterator<XXTagAttributeDef> iterTagAttributeDef;
+
+
+            TagRetrieverTagDefContext(XXService xService) {
+                Long                    serviceId         = xService == null ? null : xService.getId();
+                List<XXTagDef>          xTagDefs          = daoMgr.getXXTagDef().findByServiceId(serviceId);
+                List<XXTagAttributeDef> xTagAttributeDefs = daoMgr.getXXTagAttributeDef().findByServiceId(serviceId);
+
+                this.service             = xService;
+                this.iterTagDef          = xTagDefs.listIterator();
+                this.iterTagAttributeDef = xTagAttributeDefs.listIterator();
+            }
+
+            TagRetrieverTagDefContext(XXTagDef xTagDef, XXService xService) {
+                Long                    tagDefId          = xTagDef == null ? null : xTagDef.getId();
+                List<XXTagDef>          xTagDefs          = asList(xTagDef);
+                List<XXTagAttributeDef> xTagAttributeDefs = daoMgr.getXXTagAttributeDef().findByTagDefId(tagDefId);
+
+                this.service             = xService;
+                this.iterTagDef          = xTagDefs.listIterator();
+                this.iterTagAttributeDef = xTagAttributeDefs.listIterator();
+            }
+
+            Map<Long, RangerTagDef> getAllTagDefs() {
+                Map<Long, RangerTagDef> ret = new HashMap<>();
+
+                while (iterTagDef.hasNext()) {
+                    RangerTagDef tagDef = getNextTagDef();
+
+                    if (tagDef != null) {
+                        ret.put(tagDef.getId(), tagDef);
+                    }
+                }
+
+                if (!hasProcessedAllTagDefs()) {
+                    LOG.warn("getAllTagDefs(): perhaps one or more tag-definitions got updated during retrieval.  Using fallback ... ");
+
+                    ret = getTagDefsBySecondary();
+                }
+
+                return ret;
+            }
+
+            RangerTagDef getNextTagDef() {
+                RangerTagDef ret = null;
+
+                if (iterTagDef.hasNext()) {
+                    XXTagDef xTagDef = iterTagDef.next();
+
+                    if (xTagDef != null) {
+                        ret = new RangerTagDef();
+
+                        ret.setId(xTagDef.getId());
+                        ret.setGuid(xTagDef.getGuid());
+                        ret.setIsEnabled(xTagDef.getIsEnabled());
+                        ret.setCreatedBy(lookupCache.getUserScreenName(xTagDef.getAddedByUserId()));
+                        ret.setUpdatedBy(lookupCache.getUserScreenName(xTagDef.getUpdatedByUserId()));
+                        ret.setCreateTime(xTagDef.getCreateTime());
+                        ret.setUpdateTime(xTagDef.getUpdateTime());
+                        ret.setVersion(xTagDef.getVersion());
+                        ret.setName(xTagDef.getName());
+                        ret.setSource(xTagDef.getSource());
+
+                        getTagAttributeDefs(ret);
+                    }
+                }
+
+                return ret;
+            }
+
+            void getTagAttributeDefs(RangerTagDef tagDef) {
+                while (iterTagAttributeDef.hasNext()) {
+                    XXTagAttributeDef xTagAttributeDef = iterTagAttributeDef.next();
+
+                    if (xTagAttributeDef.getTagDefId().equals(tagDef.getId())) {
+                        RangerTagDef.RangerTagAttributeDef tagAttributeDef = new RangerTagDef.RangerTagAttributeDef();
+
+                        tagAttributeDef.setName(xTagAttributeDef.getName());
+                        tagAttributeDef.setType(xTagAttributeDef.getType());
+
+                        tagDef.getAttributeDefs().add(tagAttributeDef);
+                    } else if (xTagAttributeDef.getTagDefId().compareTo(tagDef.getId()) > 0) {
+                        if (iterTagAttributeDef.hasPrevious()) {
+                            iterTagAttributeDef.previous();
+                        }
+                        break;
+                    }
+                }
+            }
+
+            boolean hasProcessedAllTagDefs() {
+                boolean moreToProcess = iterTagAttributeDef.hasNext();
+
+                return !moreToProcess;
+            }
+
+            Map<Long, RangerTagDef> getTagDefsBySecondary() {
+                Map<Long, RangerTagDef> ret = null;
+
+                if (service != null) {
+                    List<XXTagDef> xTagDefs = daoMgr.getXXTagDef().findByServiceId(service.getId());
+
+                    if (CollectionUtils.isNotEmpty(xTagDefs)) {
+                        ret = new HashMap<>(xTagDefs.size());
+
+                        for (XXTagDef xTagDef : xTagDefs) {
+                            TagRetrieverTagDefContext ctx = new TagRetrieverTagDefContext(xTagDef, service);
+
+                            RangerTagDef tagDef = ctx.getNextTagDef();
+
+                            if (tagDef != null) {
+                                ret.put(tagDef.getId(), tagDef);
+                            }
+                        }
+                    }
+                }
+                return ret;
+            }
+        }
+
+        private class TagRetrieverTagContext {
+            final XXService                    service;
+            final ListIterator<XXTag>          iterTag;
+            final ListIterator<XXTagAttribute> iterTagAttribute;
+
+
+            TagRetrieverTagContext(XXService xService) {
+                Long                 serviceId      = xService == null ? null : xService.getId();
+                List<XXTag>          xTags          = daoMgr.getXXTag().findByServiceId(serviceId);
+                List<XXTagAttribute> xTagAttributes = daoMgr.getXXTagAttribute().findByServiceId(serviceId);
+
+                this.service          = xService;
+                this.iterTag          = xTags.listIterator();
+                this.iterTagAttribute = xTagAttributes.listIterator();
+
+            }
+
+            TagRetrieverTagContext(XXTag xTag, XXService xService) {
+                Long                 tagId          = xTag == null ? null : xTag.getId();
+                List<XXTag>          xTags          = asList(xTag);
+                List<XXTagAttribute> xTagAttributes = daoMgr.getXXTagAttribute().findByTagId(tagId);
+
+                this.service          = xService;
+                this.iterTag          = xTags.listIterator();
+                this.iterTagAttribute = xTagAttributes.listIterator();
+            }
+
+
+            Map<Long, RangerTag> getAllTags() {
+                Map<Long, RangerTag> ret = new HashMap<>();
+
+                while (iterTag.hasNext()) {
+                    RangerTag tag = getNextTag();
+
+                    if (tag != null) {
+                        ret.put(tag.getId(), tag);
+                    }
+                }
+
+                if (!hasProcessedAllTags()) {
+                    LOG.warn("getAllTags(): perhaps one or more tags got updated during retrieval. Using fallback ... ");
+
+                    ret = getTagsBySecondary();
+                }
+
+                return ret;
+            }
+
+            RangerTag getNextTag() {
+                RangerTag ret = null;
+
+                if (iterTag.hasNext()) {
+                    XXTag xTag = iterTag.next();
+
+                    if (xTag != null) {
+                        ret = new RangerTag();
+
+                        ret.setId(xTag.getId());
+                        ret.setGuid(xTag.getGuid());
+                        ret.setOwner(xTag.getOwner());
+                        ret.setCreatedBy(lookupCache.getUserScreenName(xTag.getAddedByUserId()));
+                        ret.setUpdatedBy(lookupCache.getUserScreenName(xTag.getUpdatedByUserId()));
+                        ret.setCreateTime(xTag.getCreateTime());
+                        ret.setUpdateTime(xTag.getUpdateTime());
+                        ret.setVersion(xTag.getVersion());
+
+                        Map<String, String> mapOfOptions = JsonUtils.jsonToMapStringString(xTag.getOptions());
+
+                        if (MapUtils.isNotEmpty(mapOfOptions)) {
+                            String validityPeriodsStr = mapOfOptions.get(RangerTag.OPTION_TAG_VALIDITY_PERIODS);
+
+                            if (StringUtils.isNotEmpty(validityPeriodsStr)) {
+                                List<RangerValiditySchedule> validityPeriods = JsonUtils.jsonToRangerValiditySchedule(validityPeriodsStr);
+
+                                ret.setValidityPeriods(validityPeriods);
+                            }
+                        }
+
+                        Map<Long, RangerTagDef> tagDefs = getTagDefs();
+                        if (tagDefs != null) {
+                            RangerTagDef tagDef = tagDefs.get(xTag.getType());
+                            if (tagDef != null) {
+                                ret.setType(tagDef.getName());
+                            }
+                        }
+
+                        getTagAttributes(ret);
+                    }
+                }
+
+                return ret;
+            }
+
+            void getTagAttributes(RangerTag tag) {
+                while (iterTagAttribute.hasNext()) {
+                    XXTagAttribute xTagAttribute = iterTagAttribute.next();
+
+                    if (xTagAttribute.getTagId().equals(tag.getId())) {
+                        String attributeName = xTagAttribute.getName();
+                        String attributeValue = xTagAttribute.getValue();
+
+                        tag.getAttributes().put(attributeName, attributeValue);
+                    } else if (xTagAttribute.getTagId().compareTo(tag.getId()) > 0) {
+                        if (iterTagAttribute.hasPrevious()) {
+                            iterTagAttribute.previous();
+                        }
+                        break;
+                    }
+                }
+            }
+
+            boolean hasProcessedAllTags() {
+                boolean moreToProcess = iterTagAttribute.hasNext();
+
+                return !moreToProcess;
+            }
+
+            Map<Long, RangerTag> getTagsBySecondary() {
+                Map<Long, RangerTag> ret = null;
+
+                if (service != null) {
+                    List<XXTag> xTags = daoMgr.getXXTag().findByServiceId(service.getId());
+
+                    if (CollectionUtils.isNotEmpty(xTags)) {
+                        ret = new HashMap<>(xTags.size());
+
+                        for (XXTag xTag : xTags) {
+                            TagRetrieverTagContext ctx = new TagRetrieverTagContext(xTag, service);
+
+                            RangerTag tag = ctx.getNextTag();
+
+                            if (tag != null) {
+                                ret.put(tag.getId(), tag);
+                            }
+                        }
+                    }
+                }
+                return ret;
+            }
+        }
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
index 97b8d71..c513548 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/ServiceREST.java
@@ -101,8 +101,8 @@ import org.apache.ranger.plugin.policyengine.RangerPolicyEngineCacheForEngineOpt
 import org.apache.ranger.plugin.policyengine.RangerPolicyEngineImpl;
 import org.apache.ranger.plugin.policyengine.RangerPolicyEngineOptions;
 import org.apache.ranger.plugin.service.ResourceLookupContext;
-import org.apache.ranger.plugin.store.PList;
 import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil;
+import org.apache.ranger.plugin.store.PList;
 import org.apache.ranger.plugin.store.ServiceStore;
 import org.apache.ranger.plugin.util.GrantRevokeRequest;
 import org.apache.ranger.plugin.util.RangerAccessRequestUtil;
@@ -1515,10 +1515,11 @@ public class ServiceREST {
 				String serviceName    = request.getParameter(PARAM_SERVICE_NAME);
 				String policyName     = request.getParameter(PARAM_POLICY_NAME);
 				String updateIfExists = request.getParameter(PARAM_UPDATE_IF_EXISTS);
-				
-				if (serviceName == null && policyName == null && updateIfExists != null && updateIfExists.equalsIgnoreCase("true")){
-					serviceName    = (String) request.getAttribute(PARAM_SERVICE_NAME);
-					policyName     = (String) request.getAttribute(PARAM_POLICY_NAME);
+
+				if (serviceName == null && policyName == null && updateIfExists != null
+						&& updateIfExists.equalsIgnoreCase("true")) {
+					serviceName = (String) request.getAttribute(PARAM_SERVICE_NAME);
+					policyName = (String) request.getAttribute(PARAM_POLICY_NAME);
 				}
 
 				if(StringUtils.isNotEmpty(serviceName)) {
@@ -1529,7 +1530,7 @@ public class ServiceREST {
 					policy.setName(StringUtils.trim(policyName));
 				}
 
-                                if(updateIfExists != null && Boolean.valueOf(updateIfExists)) {
+				if (updateIfExists != null && Boolean.valueOf(updateIfExists)) {
 					RangerPolicy existingPolicy = null;
 					try {
 						if(StringUtils.isNotEmpty(policy.getGuid())) {
@@ -2413,7 +2414,7 @@ public class ServiceREST {
 										validator.validate(rangerPolicy.getId(), Action.DELETE);
 										ensureAdminAccess(rangerPolicy);
                                                                                 bizUtil.blockAuditorRoleUser();
-										svcStore.deletePolicy(rangerPolicy);
+										svcStore.deletePolicy(rangerPolicy.getId());
 										totalDeletedPilicies = totalDeletedPilicies + 1;
 										if (LOG.isDebugEnabled()) {
 											LOG.debug("Policy " + rangerPolicy.getName() + " deleted successfully." );
@@ -3149,7 +3150,7 @@ public class ServiceREST {
 								ret.addAll(listToFilter);
 							}
 						} else if (isServiceAdminUser) {
-                                ret.addAll(listToFilter);
+							ret.addAll(listToFilter);
 						}
 
 						continue;
@@ -3552,4 +3553,4 @@ public class ServiceREST {
                         }
                 }
         }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java b/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java
index e6a519a..fe1883d 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerAuditFields.java
@@ -23,7 +23,7 @@ import org.apache.ranger.entity.XXDBBase;
 import org.springframework.stereotype.Component;
 
 @Component
-public class RangerAuditFields {
+public class RangerAuditFields<T extends XXDBBase> {
 
 	public <T extends XXDBBase, PARENT extends XXDBBase> T populateAuditFields(T xObj, PARENT parentObj) {
 		xObj.setCreateTime(parentObj.getCreateTime());

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java
index 8d42165..6ab12ad 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerPolicyServiceBase.java
@@ -17,7 +17,6 @@
 
 package org.apache.ranger.service;
 
-import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.ranger.authorization.utils.JsonUtils;
 import org.apache.ranger.common.GUIDUtil;
@@ -30,12 +29,10 @@ import org.apache.ranger.common.SortField.SORT_ORDER;
 import org.apache.ranger.entity.XXPolicyBase;
 import org.apache.ranger.entity.XXService;
 import org.apache.ranger.plugin.model.RangerPolicy;
-import org.apache.ranger.plugin.model.RangerValiditySchedule;
 import org.apache.ranger.plugin.util.SearchFilter;
 import org.springframework.beans.factory.annotation.Autowired;
 
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 
 public abstract class RangerPolicyServiceBase<T extends XXPolicyBase, V extends RangerPolicy> extends
@@ -58,18 +55,20 @@ public abstract class RangerPolicyServiceBase<T extends XXPolicyBase, V extends
 				"XXService xSvc", "xSvc.id = obj.service"));
 		searchFields
 				.add(new SearchField(SearchFilter.IS_ENABLED, "obj.isEnabled", DATA_TYPE.BOOLEAN, SEARCH_TYPE.FULL));
-		searchFields.add(new SearchField(SearchFilter.IS_RECURSIVE,"xPolRes.isRecursive",DATA_TYPE.BOOLEAN,SEARCH_TYPE.FULL,
-				"XXPolicyResource xPolRes","obj.id=xPolRes.policyId"));
+		//might need updation
+		/*searchFields.add(new SearchField(SearchFilter.IS_RECURSIVE,"xPolRes.isRecursive",DATA_TYPE.BOOLEAN,SEARCH_TYPE.FULL,
+				"XXPolicyResource xPolRes","obj.id=xPolRes.policyId"));*/
 		searchFields.add(new SearchField(SearchFilter.POLICY_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
 		searchFields.add(new SearchField(SearchFilter.POLICY_NAME, "obj.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL));
 		searchFields.add(new SearchField(SearchFilter.GUID, "obj.guid", DATA_TYPE.STRING, SEARCH_TYPE.FULL));
 		searchFields.add(new SearchField(SearchFilter.USER, "xUser.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL,
-				"XXUser xUser, XXPolicyItem xPolItem, XXPolicyItemUserPerm userPerm", "obj.id = xPolItem.policyId "
-						+ "and userPerm.policyItemId = xPolItem.id and xUser.id = userPerm.userId"));
+				"XXUser xUser, XXPolicyRefUser refUser", "obj.id = refUser.policyId "
+						+ "and xUser.id = refUser.userId"));
 		searchFields.add(new SearchField(SearchFilter.GROUP, "xGrp.name", DATA_TYPE.STRING, SEARCH_TYPE.FULL,
-				"XXGroup xGrp, XXPolicyItem xPolItem, XXPolicyItemGroupPerm grpPerm", "obj.id = xPolItem.policyId "
-						+ "and grpPerm.policyItemId = xPolItem.id and xGrp.id = grpPerm.groupId"));
-		searchFields.add(new SearchField(SearchFilter.POL_RESOURCE, "resMap.value", DATA_TYPE.STRING,
+				"XXGroup xGrp , XXPolicyRefGroup refGroup", "obj.id = refGroup.policyId "
+						+ "and xGrp.id = refGroup.groupId"));
+		//might need updation
+		/*searchFields.add(new SearchField(SearchFilter.POL_RESOURCE, "resMap.value", DATA_TYPE.STRING,
 				SEARCH_TYPE.PARTIAL, "XXPolicyResourceMap resMap, XXPolicyResource polRes",
 				"resMap.resourceId = polRes.id and polRes.policyId = obj.id"));
                 /*searchFields.add(new SearchField(SearchFilter.POLICY_LABELS_PARTIAL, "obj.label_name", DATA_TYPE.STRING,
@@ -118,9 +117,11 @@ public abstract class RangerPolicyServiceBase<T extends XXPolicyBase, V extends
 			options.remove(OPTION_POLICY_VALIDITY_SCHEDULES);
 		}
 
-        xObj.setOptions(JsonUtils.mapToJson(options));
+		xObj.setOptions(JsonUtils.mapToJson(options));
 
-        return xObj;
+		xObj.setPolicyText(JsonUtils.objectToJson(vObj));
+
+		return xObj;
 	}
 
 	@Override
@@ -137,20 +138,16 @@ public abstract class RangerPolicyServiceBase<T extends XXPolicyBase, V extends
 		vObj.setIsEnabled(xObj.getIsEnabled());
 		vObj.setIsAuditEnabled(xObj.getIsAuditEnabled());
 
-		Map<String, Object> options = JsonUtils.jsonToObject(xObj.getOptions(), Map.class);
-
-		if (MapUtils.isNotEmpty(options)) {
-			String optionPolicyValiditySchedule = (String)options.remove(OPTION_POLICY_VALIDITY_SCHEDULES);
+		String policyText = xObj.getPolicyText();
 
-			if (StringUtils.isNotBlank(optionPolicyValiditySchedule)) {
-				List<RangerValiditySchedule> validitySchedules = JsonUtils.jsonToRangerValiditySchedule(optionPolicyValiditySchedule);
+		RangerPolicy ret = JsonUtils.jsonToObject(policyText, RangerPolicy.class);
 
-				vObj.setValiditySchedules(validitySchedules);
-			}
+		if (ret != null) {
+			vObj.setOptions(ret.getOptions());
+			vObj.setValiditySchedules(ret.getValiditySchedules());
+			vObj.setPolicyLabels(ret.getPolicyLabels());
 		}
 
-		vObj.setOptions(options);
-
 		return vObj;
 	}
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java
index 5cbe47a..9b543ef 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceDefServiceBase.java
@@ -62,7 +62,7 @@ public abstract class RangerServiceDefServiceBase<T extends XXServiceDefBase, V
 	private static final String OPTION_RESOURCE_IS_VALID_LEAF            = "__isValidLeaf";
 
 	@Autowired
-	RangerAuditFields rangerAuditFields;
+	RangerAuditFields<?> rangerAuditFields;
 
 	@Autowired
 	JSONUtil jsonUtil;


[8/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/postgres/optimized/current/ranger_core_db_postgres.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/postgres/optimized/current/ranger_core_db_postgres.sql b/security-admin/db/postgres/optimized/current/ranger_core_db_postgres.sql
index bad32ef..a123911 100644
--- a/security-admin/db/postgres/optimized/current/ranger_core_db_postgres.sql
+++ b/security-admin/db/postgres/optimized/current/ranger_core_db_postgres.sql
@@ -465,6 +465,7 @@ is_enabled BOOLEAN DEFAULT '0' NOT NULL,
 is_audit_enabled BOOLEAN DEFAULT '0' NOT NULL,
 policy_options VARCHAR(4000) DEFAULT NULL NULL,
 policy_priority INT DEFAULT 0 NOT NULL,
+policy_text TEXT DEFAULT NULL NULL,
 primary key(id),
 CONSTRAINT x_policy_uk_name_service UNIQUE(name,service),
 CONSTRAINT x_policy_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
@@ -933,6 +934,7 @@ version BIGINT DEFAULT NULL NULL,
 name VARCHAR(255) NOT NULL,
 source VARCHAR(128) DEFAULT NULL NULL,
 is_enabled BOOLEAN DEFAULT '0' NOT NULL,
+tag_attrs_def_text TEXT DEFAULT NULL NULL,
 PRIMARY KEY (id),
 CONSTRAINT x_tag_def_UK_guid UNIQUE (guid),
 CONSTRAINT x_tag_def_UK_name UNIQUE (name),
@@ -955,6 +957,7 @@ version BIGINT DEFAULT NULL NULL,
 type BIGINT NOT NULL,
 owned_by SMALLINT DEFAULT 0 NOT NULL,
 policy_options VARCHAR(4000) DEFAULT NULL NULL,
+tag_attrs_text TEXT DEFAULT NULL NULL,
 primary key (id),
 CONSTRAINT x_tag_UK_guid UNIQUE (guid),
 CONSTRAINT x_tag_FK_type FOREIGN KEY (type) REFERENCES x_tag_def (id),
@@ -976,6 +979,8 @@ version BIGINT DEFAULT NULL NULL,
 service_id BIGINT NOT NULL,
 resource_signature VARCHAR(128) DEFAULT NULL NULL,
 is_enabled BOOLEAN DEFAULT '1' NOT NULL,
+service_resource_elements_text TEXT DEFAULT NULL NULL,
+tags_text TEXT DEFAULT NULL NULL,
 primary key (id),
 CONSTRAINT x_service_res_UK_guid UNIQUE (guid),
 CONSTRAINT x_service_res_FK_service_id FOREIGN KEY (service_id) REFERENCES x_service (id),
@@ -983,63 +988,6 @@ CONSTRAINT x_service_res_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_p
 CONSTRAINT x_service_res_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
 );
 
-DROP TABLE IF EXISTS x_service_resource_element CASCADE;
-DROP SEQUENCE IF EXISTS x_service_resource_element_seq;
-CREATE SEQUENCE x_service_resource_element_seq;
-CREATE TABLE x_service_resource_element(
-id BIGINT DEFAULT nextval('x_service_resource_element_seq'::regclass),
-create_time TIMESTAMP DEFAULT NULL NULL,
-update_time TIMESTAMP DEFAULT NULL NULL,
-added_by_id BIGINT DEFAULT NULL NULL,
-upd_by_id BIGINT DEFAULT NULL NULL,
-res_id BIGINT NOT NULL,
-res_def_id BIGINT NOT NULL,
-is_excludes BOOLEAN DEFAULT '0' NOT NULL,
-is_recursive BOOLEAN DEFAULT '0' NOT NULL,
-primary key (id),
-CONSTRAINT x_srvc_res_el_FK_res_def_id FOREIGN KEY (res_def_id) REFERENCES x_resource_def (id),
-CONSTRAINT x_srvc_res_el_FK_res_id FOREIGN KEY (res_id) REFERENCES x_service_resource (id),
-CONSTRAINT x_srvc_res_el_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_srvc_res_el_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
-
-DROP TABLE IF EXISTS x_tag_attr_def CASCADE;
-DROP SEQUENCE IF EXISTS x_tag_attr_def_seq;
-CREATE SEQUENCE x_tag_attr_def_seq;
-CREATE TABLE x_tag_attr_def(
-id BIGINT DEFAULT nextval('x_tag_attr_def_seq'::regclass),
-create_time TIMESTAMP DEFAULT NULL NULL,
-update_time TIMESTAMP DEFAULT NULL NULL,
-added_by_id BIGINT DEFAULT NULL NULL,
-upd_by_id BIGINT DEFAULT NULL NULL,
-tag_def_id BIGINT NOT NULL,
-name VARCHAR(255) NOT NULL,
-type VARCHAR(50) NOT NULL,
-primary key (id),
-CONSTRAINT x_tag_attr_def_FK_tag_def_id FOREIGN KEY (tag_def_id) REFERENCES x_tag_def (id),
-CONSTRAINT x_tag_attr_def_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_tag_attr_def_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
-
-
-DROP TABLE IF EXISTS x_tag_attr CASCADE;
-DROP SEQUENCE IF EXISTS x_tag_attr_seq;
-CREATE SEQUENCE x_tag_attr_seq;
-CREATE TABLE x_tag_attr(
-id BIGINT DEFAULT nextval('x_tag_attr_seq'::regclass),
-create_time TIMESTAMP DEFAULT NULL NULL,
-update_time TIMESTAMP DEFAULT NULL NULL,
-added_by_id BIGINT DEFAULT NULL NULL,
-upd_by_id BIGINT DEFAULT NULL NULL,
-tag_id BIGINT NOT NULL,
-name VARCHAR(255) NOT NULL,
-value VARCHAR(512) DEFAULT NULL NULL,
-primary key (id),
-CONSTRAINT x_tag_attr_FK_tag_id FOREIGN KEY (tag_id) REFERENCES x_tag (id),
-CONSTRAINT x_tag_attr_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_tag_attr_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
-
 DROP TABLE IF EXISTS x_tag_resource_map CASCADE;
 DROP SEQUENCE IF EXISTS x_tag_resource_map_seq;
 CREATE SEQUENCE x_tag_resource_map_seq;
@@ -1060,24 +1008,6 @@ CONSTRAINT x_tag_res_map_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES x_p
 CONSTRAINT x_tag_res_map_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
 );
 
-DROP TABLE IF EXISTS x_service_resource_element_val CASCADE;
-DROP SEQUENCE IF EXISTS x_service_res_el_val_seq;
-CREATE SEQUENCE x_service_res_el_val_seq;
-CREATE TABLE x_service_resource_element_val(
-id BIGINT DEFAULT nextval('x_service_res_el_val_seq'::regclass),
-create_time TIMESTAMP DEFAULT NULL NULL,
-update_time TIMESTAMP DEFAULT NULL NULL,
-added_by_id BIGINT DEFAULT NULL NULL,
-upd_by_id BIGINT DEFAULT NULL NULL,
-res_element_id BIGINT NOT NULL,
-value VARCHAR(1024) NOT NULL,
-sort_order SMALLINT DEFAULT '0' NULL,
-primary key (id),
-CONSTRAINT x_srvc_res_el_val_FK_res_el_id FOREIGN KEY (res_element_id) REFERENCES x_service_resource_element (id),
-CONSTRAINT x_srvc_res_el_val_FK_add_by_id FOREIGN KEY (added_by_id) REFERENCES x_portal_user (id),
-CONSTRAINT x_srvc_res_el_val_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES x_portal_user (id)
-);
-
 DROP TABLE IF EXISTS x_policy_item_datamask;
 DROP SEQUENCE IF EXISTS x_policy_item_datamask_seq;
 DROP TABLE IF EXISTS x_datamask_type_def;
@@ -1231,6 +1161,133 @@ session_id varchar(255) DEFAULT NULL,
 primary key (id)
 );
 
+DROP TABLE IF EXISTS x_policy_ref_resource CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_resource_seq;
+CREATE SEQUENCE x_policy_ref_resource_seq;
+CREATE TABLE x_policy_ref_resource(
+id BIGINT DEFAULT nextval('x_policy_ref_resource_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+resource_def_id BIGINT NOT NULL,
+resource_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_res_UK_polId_resDefId UNIQUE (policy_id, resource_def_id),
+CONSTRAINT x_p_ref_res_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_res_FK_resource_def_id FOREIGN KEY(resource_def_id) REFERENCES x_resource_def(id),
+CONSTRAINT x_p_ref_res_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_res_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_access_type CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_access_type_seq;
+CREATE SEQUENCE x_policy_ref_access_type_seq;
+CREATE TABLE x_policy_ref_access_type(
+id BIGINT DEFAULT nextval('x_policy_ref_access_type_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+access_def_id BIGINT NOT NULL,
+access_type_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_acc_UK_polId_accDefId UNIQUE(policy_id, access_def_id),
+CONSTRAINT x_p_ref_acc_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_acc_FK_acc_def_id FOREIGN KEY(access_def_id) REFERENCES x_access_type_def(id),
+CONSTRAINT x_p_ref_acc_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_acc_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_condition CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_condition_seq;
+CREATE SEQUENCE x_policy_ref_condition_seq;
+CREATE TABLE x_policy_ref_condition(
+id BIGINT DEFAULT nextval('x_policy_ref_condition_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+condition_def_id BIGINT NOT NULL,
+condition_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_cond_UK_polId_cDefId UNIQUE(policy_id, condition_def_id),
+CONSTRAINT x_p_ref_cond_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_cond_FK_cond_def_id FOREIGN KEY(condition_def_id) REFERENCES x_policy_condition_def(id),
+CONSTRAINT x_p_ref_cond_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_cond_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_datamask_type CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_datamask_type_seq;
+CREATE SEQUENCE x_policy_ref_datamask_type_seq;
+CREATE TABLE x_policy_ref_datamask_type(
+id BIGINT DEFAULT nextval('x_policy_ref_datamask_type_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+datamask_def_id BIGINT NOT NULL,
+datamask_type_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_dmk_UK_polId_dDefId UNIQUE(policy_id, datamask_def_id),
+CONSTRAINT x_p_ref_dmk_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_dmk_FK_dmk_def_id FOREIGN KEY(datamask_def_id) REFERENCES x_datamask_type_def(id),
+CONSTRAINT x_p_ref_dmk_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_dmk_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_user CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_user_seq;
+CREATE SEQUENCE x_policy_ref_user_seq;
+CREATE TABLE x_policy_ref_user(
+id BIGINT DEFAULT nextval('x_policy_ref_user_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+user_id BIGINT NOT NULL,
+user_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_usr_UK_polId_userId UNIQUE(policy_id, user_id),
+CONSTRAINT x_p_ref_usr_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_usr_FK_user_id FOREIGN KEY(user_id) REFERENCES x_user(id),
+CONSTRAINT x_p_ref_usr_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_usr_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_group CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_group_seq;
+CREATE SEQUENCE x_policy_ref_group_seq;
+CREATE TABLE x_policy_ref_group(
+id BIGINT DEFAULT nextval('x_policy_ref_group_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+group_id BIGINT NOT NULL,
+group_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_grp_UK_polId_grpId UNIQUE(policy_id, group_id),
+CONSTRAINT x_p_ref_grp_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_grp_FK_group_id FOREIGN KEY(group_id) REFERENCES x_group(id),
+CONSTRAINT x_p_ref_grp_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_grp_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+
 CREATE INDEX xa_access_audit_added_by_id ON xa_access_audit(added_by_id);
 CREATE INDEX xa_access_audit_upd_by_id ON xa_access_audit(upd_by_id);
 CREATE INDEX xa_access_audit_cr_time ON xa_access_audit(create_time);
@@ -1340,21 +1397,10 @@ CREATE INDEX x_tag_IDX_added_by_id ON x_tag(added_by_id);
 CREATE INDEX x_tag_IDX_upd_by_id ON x_tag(upd_by_id);
 CREATE INDEX x_service_res_IDX_added_by_id ON x_service_resource(added_by_id);
 CREATE INDEX x_service_res_IDX_upd_by_id ON x_service_resource(upd_by_id);
-CREATE INDEX x_srvc_res_el_IDX_added_by_id ON x_service_resource_element(added_by_id);
-CREATE INDEX x_srvc_res_el_IDX_upd_by_id ON x_service_resource_element(upd_by_id);
-CREATE INDEX x_tag_attr_def_IDX_tag_def_id ON x_tag_attr_def(tag_def_id);
-CREATE INDEX x_tag_attr_def_IDX_added_by_id ON x_tag_attr_def(added_by_id);
-CREATE INDEX x_tag_attr_def_IDX_upd_by_id ON x_tag_attr_def(upd_by_id);
-CREATE INDEX x_tag_attr_IDX_tag_id ON x_tag_attr(tag_id);
-CREATE INDEX x_tag_attr_IDX_added_by_id ON x_tag_attr(added_by_id);
-CREATE INDEX x_tag_attr_IDX_upd_by_id ON x_tag_attr(upd_by_id);
 CREATE INDEX x_tag_res_map_IDX_tag_id ON x_tag_resource_map(tag_id);
 CREATE INDEX x_tag_res_map_IDX_res_id ON x_tag_resource_map(res_id);
 CREATE INDEX x_tag_res_map_IDX_added_by_id ON x_tag_resource_map(added_by_id);
 CREATE INDEX x_tag_res_map_IDX_upd_by_id ON x_tag_resource_map(upd_by_id);
-CREATE INDEX x_srvc_res_el_val_IDX_resel_id ON x_service_resource_element_val(res_element_id);
-CREATE INDEX x_srvc_res_el_val_IDX_addby_id ON x_service_resource_element_val(added_by_id);
-CREATE INDEX x_srvc_res_el_val_IDX_updby_id ON x_service_resource_element_val(upd_by_id);
 CREATE INDEX x_service_config_def_IDX_def_id ON x_service_config_def(def_id);
 CREATE INDEX x_resource_def_IDX_def_id ON x_resource_def(def_id);
 CREATE INDEX x_access_type_def_IDX_def_id ON x_access_type_def(def_id);
@@ -1376,8 +1422,6 @@ CREATE INDEX x_policy_item_user_perm_IDX_user_id ON x_policy_item_user_perm(user
 CREATE INDEX x_policy_item_group_perm_IDX_policy_item_id ON x_policy_item_group_perm(policy_item_id);
 CREATE INDEX x_policy_item_group_perm_IDX_group_id ON x_policy_item_group_perm(group_id);
 CREATE INDEX x_service_resource_IDX_service_id ON x_service_resource(service_id);
-CREATE INDEX x_service_resource_element_IDX_res_id ON x_service_resource_element(res_id);
-CREATE INDEX x_service_resource_element_IDX_res_def_id ON x_service_resource_element(res_def_id);
 CREATE INDEX x_datamask_type_def_IDX_def_id ON x_datamask_type_def(def_id);
 CREATE INDEX x_policy_item_datamask_IDX_policy_item_id ON x_policy_item_datamask(policy_item_id);
 CREATE INDEX x_policy_item_rowfilter_IDX_policy_item_id ON x_policy_item_rowfilter(policy_item_id);
@@ -1434,6 +1478,9 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('031',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('032',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('033',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('034',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('035',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('036',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('DB_PATCHES',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 INSERT INTO x_user_module_perm (user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (1,3,current_timestamp,current_timestamp,1,1,1);
 INSERT INTO x_user_module_perm (user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (1,1,current_timestamp,current_timestamp,1,1,1);
@@ -1471,7 +1518,8 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10014',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10015',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10016',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
-INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10018',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10019',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10020',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('JAVA_PATCHES',current_timestamp,'Ranger 1.0.0',current_timestamp,'localhost','Y');
 
 DROP VIEW IF EXISTS vx_trx_log;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/postgres/patches/035-update-schema-for-x-policy.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/postgres/patches/035-update-schema-for-x-policy.sql b/security-admin/db/postgres/patches/035-update-schema-for-x-policy.sql
new file mode 100644
index 0000000..cb87cd0
--- /dev/null
+++ b/security-admin/db/postgres/patches/035-update-schema-for-x-policy.sql
@@ -0,0 +1,197 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+DROP TABLE IF EXISTS x_policy_ref_resource CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_resource_seq;
+CREATE SEQUENCE x_policy_ref_resource_seq;
+CREATE TABLE x_policy_ref_resource(
+id BIGINT DEFAULT nextval('x_policy_ref_resource_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+resource_def_id BIGINT NOT NULL,
+resource_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_res_UK_polId_resDefId UNIQUE (policy_id, resource_def_id),
+CONSTRAINT x_p_ref_res_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_res_FK_resource_def_id FOREIGN KEY(resource_def_id) REFERENCES x_resource_def(id),
+CONSTRAINT x_p_ref_res_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_res_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_access_type CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_access_type_seq;
+CREATE SEQUENCE x_policy_ref_access_type_seq;
+CREATE TABLE x_policy_ref_access_type(
+id BIGINT DEFAULT nextval('x_policy_ref_access_type_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+access_def_id BIGINT NOT NULL,
+access_type_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_acc_UK_polId_accDefId UNIQUE(policy_id, access_def_id),
+CONSTRAINT x_p_ref_acc_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_acc_FK_acc_def_id FOREIGN KEY(access_def_id) REFERENCES x_access_type_def(id),
+CONSTRAINT x_p_ref_acc_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_acc_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_condition CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_condition_seq;
+CREATE SEQUENCE x_policy_ref_condition_seq;
+CREATE TABLE x_policy_ref_condition(
+id BIGINT DEFAULT nextval('x_policy_ref_condition_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+condition_def_id BIGINT NOT NULL,
+condition_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_cond_UK_polId_cDefId UNIQUE(policy_id, condition_def_id),
+CONSTRAINT x_p_ref_cond_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_cond_FK_cond_def_id FOREIGN KEY(condition_def_id) REFERENCES x_policy_condition_def(id),
+CONSTRAINT x_p_ref_cond_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_cond_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_datamask_type CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_datamask_type_seq;
+CREATE SEQUENCE x_policy_ref_datamask_type_seq;
+CREATE TABLE x_policy_ref_datamask_type(
+id BIGINT DEFAULT nextval('x_policy_ref_datamask_type_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+datamask_def_id BIGINT NOT NULL,
+datamask_type_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_dmk_UK_polId_dDefId UNIQUE(policy_id, datamask_def_id),
+CONSTRAINT x_p_ref_dmk_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_dmk_FK_dmk_def_id FOREIGN KEY(datamask_def_id) REFERENCES x_datamask_type_def(id),
+CONSTRAINT x_p_ref_dmk_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_dmk_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_user CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_user_seq;
+CREATE SEQUENCE x_policy_ref_user_seq;
+CREATE TABLE x_policy_ref_user(
+id BIGINT DEFAULT nextval('x_policy_ref_user_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+user_id BIGINT NOT NULL,
+user_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_usr_UK_polId_userId UNIQUE(policy_id, user_id),
+CONSTRAINT x_p_ref_usr_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_usr_FK_user_id FOREIGN KEY(user_id) REFERENCES x_user(id),
+CONSTRAINT x_p_ref_usr_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_usr_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+DROP TABLE IF EXISTS x_policy_ref_group CASCADE;
+DROP SEQUENCE IF EXISTS x_policy_ref_group_seq;
+CREATE SEQUENCE x_policy_ref_group_seq;
+CREATE TABLE x_policy_ref_group(
+id BIGINT DEFAULT nextval('x_policy_ref_group_seq'::regclass),
+guid VARCHAR(1024) DEFAULT NULL NULL,
+create_time TIMESTAMP DEFAULT NULL NULL,
+update_time TIMESTAMP DEFAULT NULL NULL,
+added_by_id BIGINT DEFAULT NULL NULL,
+upd_by_id BIGINT DEFAULT NULL NULL,
+policy_id BIGINT NOT NULL,
+group_id BIGINT NOT NULL,
+group_name varchar(4000) DEFAULT NULL,
+primary key(id),
+CONSTRAINT x_p_ref_grp_UK_polId_grpId UNIQUE(policy_id, group_id),
+CONSTRAINT x_p_ref_grp_FK_policy_id FOREIGN KEY(policy_id) REFERENCES x_policy(id),
+CONSTRAINT x_p_ref_grp_FK_group_id FOREIGN KEY(group_id) REFERENCES x_group(id),
+CONSTRAINT x_p_ref_grp_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES x_portal_user(id),
+CONSTRAINT x_p_ref_grp_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES x_portal_user(id)
+);
+commit;
+select 'delimiter start';
+CREATE OR REPLACE FUNCTION add_x_policy_json()
+RETURNS void AS $$
+DECLARE
+ v_column_exists integer := 0;
+BEGIN
+  select count(*) into v_column_exists from pg_attribute where attrelid in(select oid from pg_class where relname='x_policy') and attname='policy_text';
+   IF v_column_exists = 0 THEN
+     ALTER TABLE x_policy ADD COLUMN policy_text TEXT DEFAULT NULL NULL;
+   END IF;
+END;
+$$ LANGUAGE plpgsql;
+select 'delimiter end';
+
+select add_x_policy_json();
+select 'delimiter end';
+
+select 'delimiter start';
+CREATE OR REPLACE FUNCTION remove_foreign_key(objName varchar(4000))
+RETURNS void AS $$
+declare
+ tableName VARCHAR(256);
+ constraintName VARCHAR(512);
+ query varchar(4000);
+ curs CURSOR FOR SELECT table_name,constraint_name from information_schema.key_column_usage where constraint_catalog=current_catalog and table_name=objName and position_in_unique_constraint notnull;
+begin
+  OPEN curs;
+  loop
+	FETCH curs INTO tableName,constraintName;
+	EXIT WHEN NOT FOUND;
+	query :='ALTER TABLE ' || objName || ' drop constraint ' || constraintName;
+	execute query;
+  end loop;
+  close curs;
+END;
+$$ LANGUAGE plpgsql;
+select 'delimiter end';
+
+CREATE OR REPLACE FUNCTION removekeys()
+RETURNS void AS
+$$
+BEGIN
+	perform remove_foreign_key('x_policy_item');
+	perform remove_foreign_key('x_policy_item_access');
+	perform remove_foreign_key('x_policy_item_condition');
+	perform remove_foreign_key('x_policy_item_datamask');
+	perform remove_foreign_key('x_policy_item_group_perm');
+	perform remove_foreign_key('x_policy_resource');
+	perform remove_foreign_key('x_policy_resource_map');
+	perform remove_foreign_key('x_policy_item_user_perm');
+	perform remove_foreign_key('x_policy_item_rowfilter');
+END;
+$$ LANGUAGE plpgsql;
+select removekeys();
+
+select 'delimiter end';
+

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/postgres/patches/036-denormalize-tag-tables.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/postgres/patches/036-denormalize-tag-tables.sql b/security-admin/db/postgres/patches/036-denormalize-tag-tables.sql
new file mode 100644
index 0000000..e5ed272
--- /dev/null
+++ b/security-admin/db/postgres/patches/036-denormalize-tag-tables.sql
@@ -0,0 +1,79 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+-- function denormalize_tag_tables()
+select 'delimiter start';
+CREATE OR REPLACE FUNCTION denormalize_tag_tables()
+RETURNS void AS $$
+DECLARE
+ v_column_exists integer := 0;
+BEGIN
+ select count(*) into v_column_exists from pg_attribute where attrelid in(select oid from pg_class where relname='x_tag_def') and attname='tag_attrs_def_text';
+ IF v_column_exists = 0 THEN
+  ALTER TABLE x_tag_def ADD COLUMN tag_attrs_def_text TEXT DEFAULT NULL NULL;
+ END IF;
+  select count(*) into v_column_exists from pg_attribute where attrelid in(select oid from pg_class where relname='x_tag') and attname='tag_attrs_text';
+ IF v_column_exists = 0 THEN
+  ALTER TABLE x_tag ADD COLUMN tag_attrs_text TEXT DEFAULT NULL NULL;
+ END IF;
+  select count(*) into v_column_exists from pg_attribute where attrelid in(select oid from pg_class where relname='x_service_resource') and attname='service_resource_elements_text';
+ IF v_column_exists = 0 THEN
+  ALTER TABLE x_service_resource ADD COLUMN service_resource_elements_text TEXT DEFAULT NULL NULL;
+ END IF;
+   select count(*) into v_column_exists from pg_attribute where attrelid in(select oid from pg_class where relname='x_service_resource') and attname='tags_text';
+ IF v_column_exists = 0 THEN
+  ALTER TABLE x_service_resource ADD COLUMN tags_text TEXT DEFAULT NULL NULL;
+ END IF;
+END;
+$$ LANGUAGE plpgsql;
+select 'delimiter end';
+
+select denormalize_tag_tables();
+select 'delimiter end';
+
+select 'delimiter start';
+CREATE OR REPLACE FUNCTION remove_foreign_key(objName varchar(4000))
+RETURNS void AS $$
+declare
+ tableName VARCHAR(256);
+ constraintName VARCHAR(512);
+ query varchar(4000);
+ curs CURSOR FOR SELECT table_name,constraint_name from information_schema.key_column_usage where constraint_catalog=current_catalog and table_name=objName and position_in_unique_constraint notnull;
+begin
+  OPEN curs;
+  loop
+	FETCH curs INTO tableName,constraintName;
+	EXIT WHEN NOT FOUND;
+	query :='ALTER TABLE ' || objName || ' drop constraint ' || constraintName;
+	execute query;
+  end loop;
+  close curs;
+END;
+$$ LANGUAGE plpgsql;
+select 'delimiter end';
+
+CREATE OR REPLACE FUNCTION removekeys()
+RETURNS void AS
+$$
+BEGIN
+	perform remove_foreign_key('x_tag_attr_def');
+	perform remove_foreign_key('x_tag_attr');
+	perform remove_foreign_key('x_service_resource_element');
+	perform remove_foreign_key('x_service_resource_element_val');
+END;
+$$ LANGUAGE plpgsql;
+select removekeys();
+
+select 'delimiter end';

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/sqlanywhere/optimized/current/ranger_core_db_sqlanywhere.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/sqlanywhere/optimized/current/ranger_core_db_sqlanywhere.sql b/security-admin/db/sqlanywhere/optimized/current/ranger_core_db_sqlanywhere.sql
index 9482992..142302a 100644
--- a/security-admin/db/sqlanywhere/optimized/current/ranger_core_db_sqlanywhere.sql
+++ b/security-admin/db/sqlanywhere/optimized/current/ranger_core_db_sqlanywhere.sql
@@ -343,6 +343,7 @@ create table dbo.x_policy (
 	is_audit_enabled tinyint DEFAULT 0 NOT NULL,
 	policy_options varchar(4000) DEFAULT NULL NULL,
 	policy_priority int DEFAULT 0 NOT NULL,
+	policy_text text DEFAULT NULL NULL,
 	CONSTRAINT x_policy_PK_id PRIMARY KEY CLUSTERED(id),
 	CONSTRAINT x_policy_UK_name_service UNIQUE NONCLUSTERED (name,service)
 )
@@ -678,6 +679,7 @@ CREATE TABLE dbo.x_tag_def(
 	name varchar(255) NOT NULL,
 	source varchar(128) DEFAULT NULL NULL,
 	is_enabled tinyint DEFAULT 0 NOT NULL,
+	tag_attrs_def_text text DEFAULT NULL NULL,
 	CONSTRAINT x_tag_def_PK_id PRIMARY KEY CLUSTERED(id),
 	CONSTRAINT x_tag_def_UK_guid UNIQUE NONCLUSTERED (guid),
 	CONSTRAINT x_tag_def_UK_name UNIQUE NONCLUSTERED (name)
@@ -694,6 +696,7 @@ CREATE TABLE dbo.x_tag(
 	type bigint NOT NULL,
 	owned_by smallint DEFAULT 0 NOT NULL,
 	policy_options varchar(4000) DEFAULT NULL NULL,
+	tag_attrs_text text DEFAULT NULL NULL,
 	CONSTRAINT x_tag_PK_id PRIMARY KEY CLUSTERED(id),
 	CONSTRAINT x_tag_UK_guid UNIQUE NONCLUSTERED (guid)
 )
@@ -709,47 +712,12 @@ CREATE TABLE dbo.x_service_resource(
 	service_id bigint NOT NULL,
 	resource_signature varchar(128) DEFAULT NULL NULL,
 	is_enabled tinyint DEFAULT 1 NOT NULL,
+	service_resource_elements_text text DEFAULT NULL NULL,
+	tags_text text DEFAULT NULL NULL,
 	CONSTRAINT x_service_res_PK_id PRIMARY KEY CLUSTERED(id),
 	CONSTRAINT x_service_res_UK_guid UNIQUE NONCLUSTERED (guid)
 )
 GO
-CREATE TABLE dbo.x_service_resource_element(
-	id bigint IDENTITY NOT NULL,
-	create_time datetime DEFAULT NULL NULL,
-	update_time datetime DEFAULT NULL NULL,
-	added_by_id bigint DEFAULT NULL NULL,
-	upd_by_id bigint DEFAULT NULL NULL,
-	res_id bigint NOT NULL,
-	res_def_id bigint NOT NULL,
-	is_excludes tinyint DEFAULT 0 NOT NULL,
-	is_recursive tinyint DEFAULT 0 NOT NULL,
-	CONSTRAINT x_srvc_res_el_PK_id PRIMARY KEY CLUSTERED(id)
-)
-GO
-CREATE TABLE dbo.x_tag_attr_def(
-	id bigint IDENTITY NOT NULL,
-	create_time datetime DEFAULT NULL NULL,
-	update_time datetime DEFAULT NULL NULL,
-	added_by_id bigint DEFAULT NULL NULL,
-	upd_by_id bigint DEFAULT NULL NULL,
-	tag_def_id bigint NOT NULL,
-	name varchar(255) NOT NULL,
-	type varchar(50) NOT NULL,
-	CONSTRAINT x_tag_attr_def_PK_id PRIMARY KEY CLUSTERED(id)
-)
-GO
-CREATE TABLE dbo.x_tag_attr(
-	id bigint IDENTITY NOT NULL,
-	create_time datetime DEFAULT NULL NULL,
-	update_time datetime DEFAULT NULL NULL,
-	added_by_id bigint DEFAULT NULL NULL,
-	upd_by_id bigint DEFAULT NULL NULL,
-	tag_id bigint NOT NULL,
-	name varchar(255) NOT NULL,
-	value varchar(512) DEFAULT NULL NULL,
-	CONSTRAINT x_tag_attr_PK_id PRIMARY KEY CLUSTERED(id)
-)
-GO
 CREATE TABLE dbo.x_tag_resource_map(
 	id bigint IDENTITY NOT NULL,
 	guid varchar(64) NOT NULL,
@@ -763,18 +731,6 @@ CREATE TABLE dbo.x_tag_resource_map(
 	CONSTRAINT x_tag_res_map_UK_guid UNIQUE NONCLUSTERED (guid)
 )
 GO
-CREATE TABLE dbo.x_service_resource_element_val(
-	id bigint IDENTITY NOT NULL,
-	create_time datetime DEFAULT NULL NULL,
-	update_time datetime DEFAULT NULL NULL,
-	added_by_id bigint DEFAULT NULL NULL,
-	upd_by_id bigint DEFAULT NULL NULL,
-	res_element_id bigint NOT NULL,
-	value varchar(1024) NOT NULL,
-	sort_order tinyint DEFAULT 0  NULL,
-	CONSTRAINT x_srvc_res_el_val_PK_id PRIMARY KEY CLUSTERED(id)
-)
-GO
 CREATE TABLE dbo.x_datamask_type_def(
 	id bigint IDENTITY NOT NULL,
 	guid varchar(64) DEFAULT NULL NULL,
@@ -886,6 +842,90 @@ CREATE TABLE dbo.x_ugsync_audit_info(
         CONSTRAINT x_ugsync_audit_info_PK_id PRIMARY KEY CLUSTERED(id)
 )
 GO
+create table dbo.x_policy_ref_resource (
+	id bigint IDENTITY NOT NULL,
+	guid varchar(1024) DEFAULT NULL NULL,
+	create_time datetime DEFAULT NULL NULL,
+	update_time datetime DEFAULT NULL NULL,
+	added_by_id bigint DEFAULT NULL NULL,
+	upd_by_id bigint DEFAULT NULL NULL,
+	policy_id bigint NOT NULL,
+	resource_def_id bigint NOT NULL,
+	resource_name varchar(4000) DEFAULT NULL NULL,
+	CONSTRAINT x_policy_ref_res_PK_id PRIMARY KEY CLUSTERED(id),
+	CONSTRAINT x_p_ref_res_UK_polId_resDefId UNIQUE NONCLUSTERED (policy_id, resource_def_id)
+)
+GO
+create table dbo.x_policy_ref_access_type (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        access_def_id bigint NOT NULL,
+        access_type_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_acc_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_acc_UK_polId_accDefId UNIQUE NONCLUSTERED (policy_id, access_def_id)
+)
+GO
+create table dbo.x_policy_ref_condition (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        condition_def_id bigint NOT NULL,
+        condition_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_cond_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_cond_UK_polId_cDefId UNIQUE NONCLUSTERED (policy_id, condition_def_id)
+)
+GO
+create table dbo.x_policy_ref_datamask_type (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        datamask_def_id bigint NOT NULL,
+        datamask_type_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_dmk_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_dmk_UK_polId_dDefId UNIQUE NONCLUSTERED (policy_id, datamask_def_id)
+)
+GO
+create table dbo.x_policy_ref_user (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        user_id bigint NOT NULL,
+        user_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_user_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_usr_UK_polId_userId UNIQUE NONCLUSTERED (policy_id, user_id)
+)
+GO
+create table dbo.x_policy_ref_group (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        group_id bigint NOT NULL,
+        group_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_group_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_grp_UK_polId_grpId UNIQUE NONCLUSTERED (policy_id, group_id)
+)
+GO
 
 ALTER TABLE dbo.x_asset ADD CONSTRAINT x_asset_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user(id)
 GO
@@ -1123,26 +1163,6 @@ ALTER TABLE dbo.x_service_resource ADD CONSTRAINT x_service_res_FK_upd_by_id FOR
 GO
 ALTER TABLE dbo.x_service_resource ADD CONSTRAINT x_service_res_FK_service_id FOREIGN KEY(service_id) REFERENCES dbo.x_service (id)
 GO
-ALTER TABLE dbo.x_service_resource_element ADD CONSTRAINT x_srvc_res_el_FK_res_def_id FOREIGN KEY(res_def_id) REFERENCES dbo.x_resource_def (id)
-GO
-ALTER TABLE dbo.x_service_resource_element ADD CONSTRAINT x_srvc_res_el_FK_res_id FOREIGN KEY(res_id) REFERENCES dbo.x_service_resource (id)
-GO
-ALTER TABLE dbo.x_service_resource_element ADD CONSTRAINT x_srvc_res_el_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
-GO
-ALTER TABLE dbo.x_service_resource_element ADD CONSTRAINT x_srvc_res_el_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
-GO
-ALTER TABLE dbo.x_tag_attr_def ADD CONSTRAINT x_tag_attr_def_FK_tag_def_id FOREIGN KEY(tag_def_id) REFERENCES dbo.x_tag_def (id)
-GO
-ALTER TABLE dbo.x_tag_attr_def ADD CONSTRAINT x_tag_attr_def_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
-GO
-ALTER TABLE dbo.x_tag_attr_def ADD CONSTRAINT x_tag_attr_def_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
-GO
-ALTER TABLE dbo.x_tag_attr ADD CONSTRAINT x_tag_attr_FK_tag_id FOREIGN KEY(tag_id) REFERENCES dbo.x_tag (id)
-GO
-ALTER TABLE dbo.x_tag_attr ADD CONSTRAINT x_tag_attr_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
-GO
-ALTER TABLE dbo.x_tag_attr ADD CONSTRAINT x_tag_attr_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
-GO
 ALTER TABLE dbo.x_tag_resource_map ADD CONSTRAINT x_tag_res_map_FK_tag_id FOREIGN KEY(tag_id) REFERENCES dbo.x_tag (id)
 GO
 ALTER TABLE dbo.x_tag_resource_map ADD CONSTRAINT x_tag_res_map_FK_res_id FOREIGN KEY(res_id) REFERENCES dbo.x_service_resource (id)
@@ -1151,12 +1171,6 @@ ALTER TABLE dbo.x_tag_resource_map ADD CONSTRAINT x_tag_res_map_FK_added_by_id F
 GO
 ALTER TABLE dbo.x_tag_resource_map ADD CONSTRAINT x_tag_res_map_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
 GO
-ALTER TABLE dbo.x_service_resource_element_val ADD CONSTRAINT x_srvc_res_el_val_FK_res_el_id FOREIGN KEY(res_element_id) REFERENCES dbo.x_service_resource_element (id)
-GO
-ALTER TABLE dbo.x_service_resource_element_val ADD CONSTRAINT x_srvc_res_el_val_FK_add_by_id FOREIGN KEY(added_by_id) REFERENCES dbo.x_portal_user (id)
-GO
-ALTER TABLE dbo.x_service_resource_element_val ADD CONSTRAINT x_srvc_res_el_val_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
-GO
 ALTER TABLE dbo.x_service ADD CONSTRAINT x_service_FK_tag_service FOREIGN KEY(tag_service) REFERENCES dbo.x_service (id)
 GO
 ALTER TABLE dbo.x_datamask_type_def ADD CONSTRAINT x_datamask_type_def_FK_def_id FOREIGN KEY(def_id) REFERENCES dbo.x_service_def (id)
@@ -1193,7 +1207,55 @@ ALTER TABLE dbo.x_policy_label_map ADD CONSTRAINT x_policy_label_map_FK_policy_i
 GO
 ALTER TABLE dbo.x_policy_label_map ADD CONSTRAINT x_policy_label_map_FK_policy_label_id FOREIGN KEY (policy_label_id) REFERENCES dbo.x_policy_label (id)
 GO
-ALTER TABLE dbo.x_policy_label_map ADD CONSTRAINT [x_policy_label_map$x_policy_label_map_pid_plid] UNIQUE (policy_id, policy_label_id)
+ALTER TABLE dbo.x_policy_label_map ADD CONSTRAINT x_policy_label_map$x_policy_label_map_pid_plid UNIQUE (policy_id, policy_label_id)
+GO
+ALTER TABLE dbo.x_policy_ref_resource ADD CONSTRAINT x_policy_ref_resource_FK_policy_id FOREIGN KEY (policy_id) REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_ref_resource ADD CONSTRAINT x_policy_ref_resource_FK_resource_def_id FOREIGN KEY (resource_def_id) REFERENCES dbo.x_resource_def (id)
+GO
+ALTER TABLE dbo.x_policy_ref_resource ADD CONSTRAINT x_policy_ref_resource_FK_added_by FOREIGN KEY (added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_resource ADD CONSTRAINT x_policy_ref_resource_FK_upd_by FOREIGN KEY (upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_access_type ADD CONSTRAINT x_policy_ref_access_type_FK_policy_id FOREIGN KEY (policy_id) REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_ref_access_type ADD CONSTRAINT x_policy_ref_access_type_FK_access_def_id FOREIGN KEY (access_def_id) REFERENCES dbo.x_access_type_def (id)
+GO
+ALTER TABLE dbo.x_policy_ref_access_type ADD CONSTRAINT x_policy_ref_access_type_FK_added_by FOREIGN KEY (added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_access_type ADD CONSTRAINT x_policy_ref_access_type_FK_upd_by FOREIGN KEY (upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_condition ADD CONSTRAINT x_policy_ref_condition_FK_policy_id FOREIGN KEY (policy_id) REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_ref_condition ADD CONSTRAINT x_policy_ref_condition_FK_condition_def_id FOREIGN KEY (condition_def_id) REFERENCES dbo.x_policy_condition_def (id)
+GO
+ALTER TABLE dbo.x_policy_ref_condition ADD CONSTRAINT x_policy_ref_condition_FK_added_by FOREIGN KEY (added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_condition ADD CONSTRAINT x_policy_ref_condition_FK_upd_by FOREIGN KEY (upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_datamask_type ADD CONSTRAINT x_policy_ref_datamask_type_FK_policy_id FOREIGN KEY (policy_id) REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_ref_datamask_type ADD CONSTRAINT x_policy_ref_datamask_type_FK_datamask_def_id FOREIGN KEY (datamask_def_id) REFERENCES dbo.x_datamask_type_def (id)
+GO
+ALTER TABLE dbo.x_policy_ref_datamask_type ADD CONSTRAINT x_policy_ref_datamask_type_FK_added_by FOREIGN KEY (added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_datamask_type ADD CONSTRAINT x_policy_ref_datamask_type_FK_upd_by FOREIGN KEY (upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_user ADD CONSTRAINT x_policy_ref_user_FK_policy_id FOREIGN KEY (policy_id) REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_ref_user ADD CONSTRAINT x_policy_ref_user_FK_user_id FOREIGN KEY (user_id) REFERENCES dbo.x_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_user ADD CONSTRAINT x_policy_ref_user_FK_added_by FOREIGN KEY (added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_user ADD CONSTRAINT x_policy_ref_user_FK_upd_by FOREIGN KEY (upd_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_group ADD CONSTRAINT x_policy_ref_group_FK_policy_id FOREIGN KEY (policy_id) REFERENCES dbo.x_policy (id)
+GO
+ALTER TABLE dbo.x_policy_ref_group ADD CONSTRAINT x_policy_ref_group_FK_group_id FOREIGN KEY (group_id) REFERENCES dbo.x_group (id)
+GO
+ALTER TABLE dbo.x_policy_ref_group ADD CONSTRAINT x_policy_ref_group_FK_added_by FOREIGN KEY (added_by_id) REFERENCES dbo.x_portal_user (id)
+GO
+ALTER TABLE dbo.x_policy_ref_group ADD CONSTRAINT x_policy_ref_group_FK_upd_by FOREIGN KEY (upd_by_id) REFERENCES dbo.x_portal_user (id)
 GO
 CREATE NONCLUSTERED INDEX x_asset_cr_time ON dbo.x_asset(create_time ASC)
 GO
@@ -1415,22 +1477,6 @@ CREATE NONCLUSTERED INDEX x_service_res_IDX_added_by_id ON dbo.x_service_resourc
 GO
 CREATE NONCLUSTERED INDEX x_service_res_IDX_upd_by_id ON dbo.x_service_resource(upd_by_id ASC)
 GO
-CREATE NONCLUSTERED INDEX x_srvc_res_el_IDX_added_by_id ON dbo.x_service_resource_element(added_by_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_srvc_res_el_IDX_upd_by_id ON dbo.x_service_resource_element(upd_by_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_tag_attr_def_IDX_tag_def_id ON dbo.x_tag_attr_def(tag_def_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_tag_attr_def_IDX_added_by_id ON dbo.x_tag_attr_def(added_by_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_tag_attr_def_IDX_upd_by_id ON dbo.x_tag_attr_def(upd_by_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_tag_attr_IDX_tag_id ON dbo.x_tag_attr(tag_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_tag_attr_IDX_added_by_id ON dbo.x_tag_attr(added_by_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_tag_attr_IDX_upd_by_id ON dbo.x_tag_attr(upd_by_id ASC)
-GO
 CREATE NONCLUSTERED INDEX x_tag_res_map_IDX_tag_id ON dbo.x_tag_resource_map(tag_id ASC)
 GO
 CREATE NONCLUSTERED INDEX x_tag_res_map_IDX_res_id ON dbo.x_tag_resource_map(res_id ASC)
@@ -1439,12 +1485,6 @@ CREATE NONCLUSTERED INDEX x_tag_res_map_IDX_added_by_id ON dbo.x_tag_resource_ma
 GO
 CREATE NONCLUSTERED INDEX x_tag_res_map_IDX_upd_by_id ON dbo.x_tag_resource_map(upd_by_id ASC)
 GO
-CREATE NONCLUSTERED INDEX x_srvc_res_el_val_IDX_resel_id ON dbo.x_service_resource_element_val(res_element_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_srvc_res_el_val_IDX_addby_id ON dbo.x_service_resource_element_val(added_by_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_srvc_res_el_val_IDX_updby_id ON dbo.x_service_resource_element_val(upd_by_id ASC)
-GO
 CREATE NONCLUSTERED INDEX x_service_config_def_IDX_def_id ON dbo.x_service_config_def(def_id ASC)
 GO
 CREATE NONCLUSTERED INDEX x_resource_def_IDX_def_id ON dbo.x_resource_def(def_id ASC)
@@ -1487,10 +1527,6 @@ CREATE NONCLUSTERED INDEX x_policy_item_group_perm_IDX_group_id ON dbo.x_policy_
 GO
 CREATE NONCLUSTERED INDEX x_service_resource_IDX_service_id ON dbo.x_service_resource(service_id ASC)
 GO
-CREATE NONCLUSTERED INDEX x_service_resource_element_IDX_res_id ON dbo.x_service_resource_element(res_id ASC)
-GO
-CREATE NONCLUSTERED INDEX x_service_resource_element_IDX_res_def_id ON dbo.x_service_resource_element(res_def_id ASC)
-GO
 CREATE NONCLUSTERED INDEX x_datamask_type_def_IDX_def_id ON dbo.x_datamask_type_def(def_id ASC)
 GO
 CREATE NONCLUSTERED INDEX x_policy_item_datamask_IDX_policy_item_id ON dbo.x_policy_item_datamask(policy_item_id ASC)
@@ -1589,6 +1625,12 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 GO
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('033',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 GO
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('034',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+GO
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('035',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+GO
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('036',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+GO
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('DB_PATCHES',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 GO
 INSERT INTO x_user_module_perm (user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) VALUES (1,3,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,1,1,1);
@@ -1661,9 +1703,11 @@ INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active
 GO
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10015',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 GO
-INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10016,CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10016',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+GO
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10019',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 GO
-INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10018,CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
+INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('J10020',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 GO
 INSERT INTO x_db_version_h (version,inst_at,inst_by,updated_at,updated_by,active) VALUES ('JAVA_PATCHES',CURRENT_TIMESTAMP,'Ranger 1.0.0',CURRENT_TIMESTAMP,'localhost','Y');
 GO

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/sqlanywhere/patches/035-update-schema-for-x-policy.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/sqlanywhere/patches/035-update-schema-for-x-policy.sql b/security-admin/db/sqlanywhere/patches/035-update-schema-for-x-policy.sql
new file mode 100644
index 0000000..24d072f
--- /dev/null
+++ b/security-admin/db/sqlanywhere/patches/035-update-schema-for-x-policy.sql
@@ -0,0 +1,180 @@
+
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+GO
+create table dbo.x_policy_ref_resource (
+	id bigint IDENTITY NOT NULL,
+	guid varchar(1024) DEFAULT NULL NULL,
+	create_time datetime DEFAULT NULL NULL,
+	update_time datetime DEFAULT NULL NULL,
+	added_by_id bigint DEFAULT NULL NULL,
+	upd_by_id bigint DEFAULT NULL NULL,
+	policy_id bigint NOT NULL,
+	resource_def_id bigint NOT NULL,
+	resource_name varchar(4000) DEFAULT NULL NULL,
+	CONSTRAINT x_policy_ref_res_PK_id PRIMARY KEY CLUSTERED(id),
+	CONSTRAINT x_p_ref_res_UK_polId_resDefId UNIQUE NONCLUSTERED (policy_id, resource_def_id)
+)
+GO
+
+create table dbo.x_policy_ref_access_type (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        access_def_id bigint NOT NULL,
+        access_type_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_acc_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_acc_UK_polId_accDefId UNIQUE NONCLUSTERED (policy_id, access_def_id)
+)
+GO
+
+create table dbo.x_policy_ref_condition (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        condition_def_id bigint NOT NULL,
+        condition_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_cond_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_cond_UK_polId_cDefId UNIQUE NONCLUSTERED (policy_id, condition_def_id)
+)
+GO
+
+create table dbo.x_policy_ref_datamask_type (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        datamask_def_id bigint NOT NULL,
+        datamask_type_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_dmk_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_dmk_UK_polId_dDefId UNIQUE NONCLUSTERED (policy_id, datamask_def_id)
+)
+GO
+
+create table dbo.x_policy_ref_user (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        user_id bigint NOT NULL,
+        user_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_user_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_usr_UK_polId_userId UNIQUE NONCLUSTERED (policy_id, user_id)
+)
+GO
+
+create table dbo.x_policy_ref_group (
+        id bigint IDENTITY NOT NULL,
+        guid varchar(1024) DEFAULT NULL NULL,
+        create_time datetime DEFAULT NULL NULL,
+        update_time datetime DEFAULT NULL NULL,
+        added_by_id bigint DEFAULT NULL NULL,
+        upd_by_id bigint DEFAULT NULL NULL,
+        policy_id bigint NOT NULL,
+        group_id bigint NOT NULL,
+        group_name varchar(4000) DEFAULT NULL NULL,
+        CONSTRAINT x_policy_ref_group_PK_id PRIMARY KEY CLUSTERED(id),
+		CONSTRAINT x_p_ref_grp_UK_polId_grpId UNIQUE NONCLUSTERED (policy_id, group_id)
+)
+GO
+
+IF NOT EXISTS(select * from SYS.SYSCOLUMNS where tname = 'x_policy' and cname='policy_text') THEN
+	ALTER TABLE dbo.x_policy ADD (policy_text text DEFAULT NULL NULL);
+END IF;
+GO
+
+IF EXISTS (
+    SELECT  1
+    FROM    sysobjects
+    WHERE   NAME = 'removeForeignKeyConstraint'
+    AND     TYPE = 'P'
+)
+BEGIN
+    drop procedure dbo.removeForeignKeyConstraint
+END
+GO
+
+CREATE PROCEDURE dbo.removeForeignKeyConstraint (IN table_name varchar(100))
+AS
+BEGIN
+        DECLARE @stmt VARCHAR(300)
+        DECLARE cur CURSOR FOR
+                select 'alter table dbo.' + table_name + ' drop constraint ' + role
+                from SYS.SYSFOREIGNKEYS
+                where foreign_creator ='dbo' and foreign_tname = table_name
+
+        OPEN cur WITH HOLD
+                fetch cur into @stmt
+                if (@@sqlstatus = 2)
+                BEGIN
+                        close cur
+                        DEALLOCATE CURSOR cur
+                END
+
+                WHILE (@@sqlstatus = 0)
+                BEGIN
+
+                        execute(@stmt)
+                        fetch cur into @stmt
+                END
+        close cur
+        DEALLOCATE CURSOR cur
+
+END
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_item')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_item_access')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_item_condition')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_item_datamask')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_item_group_perm')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_item_user_perm')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_item_rowfilter')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_resource')
+GO
+
+call dbo.removeForeignKeyConstraint('x_policy_resource_map')
+GO
+
+
+exit

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/db/sqlanywhere/patches/036-denormalize-tag-tables.sql
----------------------------------------------------------------------
diff --git a/security-admin/db/sqlanywhere/patches/036-denormalize-tag-tables.sql b/security-admin/db/sqlanywhere/patches/036-denormalize-tag-tables.sql
new file mode 100644
index 0000000..1fdbfaa
--- /dev/null
+++ b/security-admin/db/sqlanywhere/patches/036-denormalize-tag-tables.sql
@@ -0,0 +1,71 @@
+-- Licensed to the Apache Software Foundation (ASF) under one or more
+-- contributor license agreements.  See the NOTICE file distributed with
+-- this work for additional information regarding copyright ownership.
+-- The ASF licenses this file to You under the Apache License, Version 2.0
+-- (the "License"); you may not use this file except in compliance with
+-- the License.  You may obtain a copy of the License at
+--
+--     http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+
+IF NOT EXISTS(select * from SYS.SYSCOLUMNS where tname = 'x_tag_def' and cname = 'tag_attrs_def_text') THEN
+		ALTER TABLE dbo.x_tag_def ADD tag_attrs_def_text text DEFAULT NULL NULL;
+END IF;
+IF NOT EXISTS(select * from SYS.SYSCOLUMNS where tname = 'x_tag' and cname = 'tag_attrs_text') THEN
+		ALTER TABLE dbo.x_tag ADD tag_attrs_text text DEFAULT NULL NULL;
+END IF;
+IF NOT EXISTS(select * from SYS.SYSCOLUMNS where tname = 'x_service_resource' and cname = 'service_resource_elements_text') THEN
+		ALTER TABLE dbo.x_service_resource ADD service_resource_elements_text text DEFAULT NULL NULL;
+END IF;
+IF NOT EXISTS(select * from SYS.SYSCOLUMNS where tname = 'x_service_resource' and cname = 'tags_text') THEN
+		ALTER TABLE dbo.x_service_resource ADD tags_text text DEFAULT NULL NULL;
+END IF;
+GO
+
+CREATE PROCEDURE dbo.removeTagForeignKeyConstraint (IN table_name varchar(100))
+AS
+BEGIN
+        DECLARE @stmt VARCHAR(300)
+        DECLARE cur CURSOR FOR
+                select 'alter table dbo.' + table_name + ' drop constraint ' + role
+                from SYS.SYSFOREIGNKEYS
+                where foreign_creator ='dbo' and foreign_tname = table_name
+
+        OPEN cur WITH HOLD
+                fetch cur into @stmt
+                if (@@sqlstatus = 2)
+                BEGIN
+                        close cur
+                        DEALLOCATE CURSOR cur
+                END
+
+                WHILE (@@sqlstatus = 0)
+                BEGIN
+
+                        execute(@stmt)
+                        fetch cur into @stmt
+                END
+        close cur
+        DEALLOCATE CURSOR cur
+
+END
+GO
+
+call dbo.removeTagForeignKeyConstraint('x_tag_attr_def')
+GO
+
+call dbo.removeTagForeignKeyConstraint('x_tag_attr')
+GO
+
+call dbo.removeTagForeignKeyConstraint('x_service_resource_element')
+GO
+
+call dbo.removeTagForeignKeyConstraint('x_service_resource_element_val')
+GO
+
+exit


[2/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java
index d725680..f0cb8f4 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceService.java
@@ -19,113 +19,167 @@
 
 package org.apache.ranger.service;
 
+import java.lang.reflect.Type;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
+import com.google.gson.reflect.TypeToken;
 import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.utils.JsonUtils;
+import org.apache.ranger.biz.RangerTagDBRetriever;
 import org.apache.ranger.common.SearchField;
 import org.apache.ranger.common.SearchField.DATA_TYPE;
 import org.apache.ranger.common.SearchField.SEARCH_TYPE;
 import org.apache.ranger.entity.XXServiceResource;
+import org.apache.ranger.plugin.model.RangerPolicy;
 import org.apache.ranger.plugin.model.RangerServiceResource;
+import org.apache.ranger.plugin.model.RangerTag;
 import org.apache.ranger.plugin.util.SearchFilter;
 import org.springframework.stereotype.Service;
 
 @Service
 public class RangerServiceResourceService extends RangerServiceResourceServiceBase<XXServiceResource, RangerServiceResource> {
 
-	private boolean serviceUpdateNeeded = true;
+    private static final Log LOG = LogFactory.getLog(RangerServiceResourceService.class);
 
-	public RangerServiceResourceService() {
-		searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
-		searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_ID, "obj.serviceId", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
-		searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_SIGNATURE, "obj.resourceSignature", DATA_TYPE.STRING, SEARCH_TYPE.FULL));
-	}
+    private boolean serviceUpdateNeeded = true;
 
-	@Override
-	protected void validateForCreate(RangerServiceResource vObj) {
+    public static final Type subsumedDataType   = new TypeToken<Map<String, RangerPolicy.RangerPolicyResource>>() {}.getType();
+    public static final Type duplicatedDataType = new TypeToken<List<RangerTag>>() {}.getType();
 
-	}
+    public RangerServiceResourceService() {
+        searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_ID, "obj.id", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
+        searchFields.add(new SearchField(SearchFilter.TAG_SERVICE_ID, "obj.serviceId", DATA_TYPE.INTEGER, SEARCH_TYPE.FULL));
+        searchFields.add(new SearchField(SearchFilter.TAG_RESOURCE_SIGNATURE, "obj.resourceSignature", DATA_TYPE.STRING, SEARCH_TYPE.FULL));
+    }
 
-	@Override
-	protected void validateForUpdate(RangerServiceResource vObj, XXServiceResource entityObj) {
-		if (StringUtils.equals(entityObj.getGuid(), vObj.getGuid()) &&
-				StringUtils.equals(entityObj.getResourceSignature(), vObj.getResourceSignature())) {
-			serviceUpdateNeeded = false;
-		} else {
-			serviceUpdateNeeded = true;
-		}
-	}
+    @Override
+    protected void validateForCreate(RangerServiceResource vObj) {
 
-	@Override
-	public RangerServiceResource postUpdate(XXServiceResource resource) {
-		RangerServiceResource ret = super.postUpdate(resource);
+    }
 
-		if (serviceUpdateNeeded) {
-			daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForServiceResourceUpdate(resource.getId(), resource.getUpdateTime());
-		}
+    @Override
+    protected void validateForUpdate(RangerServiceResource vObj, XXServiceResource entityObj) {
+        if (StringUtils.equals(entityObj.getGuid(), vObj.getGuid()) &&
+                StringUtils.equals(entityObj.getResourceSignature(), vObj.getResourceSignature())) {
+            serviceUpdateNeeded = false;
+        } else {
+            serviceUpdateNeeded = true;
+        }
+    }
 
-		return ret;
-	}
+    @Override
+    public RangerServiceResource postUpdate(XXServiceResource resource) {
+        RangerServiceResource ret = super.postUpdate(resource);
 
-	public RangerServiceResource getPopulatedViewObject(XXServiceResource xObj) {
-		return populateViewBean(xObj);
-	}
+        if (serviceUpdateNeeded) {
+            daoMgr.getXXServiceVersionInfo().updateServiceVersionInfoForServiceResourceUpdate(resource.getId(), resource.getUpdateTime());
+        }
 
-	public RangerServiceResource getServiceResourceByGuid(String guid) {
-		RangerServiceResource ret = null;
+        return ret;
+    }
 
-		XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByGuid(guid);
-		
-		if(xxServiceResource != null) {
-			ret = populateViewBean(xxServiceResource);
-		}
+    public RangerServiceResource getPopulatedViewObject(XXServiceResource xObj) {
+        return populateViewBean(xObj);
+    }
 
-		return ret;
-	}
+    public RangerServiceResource getServiceResourceByGuid(String guid) {
+        RangerServiceResource ret = null;
 
-	public List<RangerServiceResource> getByServiceId(Long serviceId) {
-		List<RangerServiceResource> ret = new ArrayList<RangerServiceResource>();
+        XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByGuid(guid);
 
-		List<XXServiceResource> xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId);
+        if (xxServiceResource != null) {
+            ret = populateViewBean(xxServiceResource);
+        }
 
-		if(CollectionUtils.isNotEmpty(xxServiceResources)) {
-			for(XXServiceResource xxServiceResource : xxServiceResources) {
-				RangerServiceResource serviceResource = populateViewBean(xxServiceResource);
+        return ret;
+    }
 
-				ret.add(serviceResource);
-			}
-		}
+    public List<RangerServiceResource> getByServiceId(Long serviceId) {
+        List<RangerServiceResource> ret = new ArrayList<RangerServiceResource>();
 
-		return ret;
-	}
+        List<XXServiceResource> xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId);
 
-	public RangerServiceResource getByServiceAndResourceSignature(Long serviceId, String resourceSignature) {
-		RangerServiceResource ret = null;
+        if (CollectionUtils.isNotEmpty(xxServiceResources)) {
+            for (XXServiceResource xxServiceResource : xxServiceResources) {
+                RangerServiceResource serviceResource = populateViewBean(xxServiceResource);
 
-		XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByServiceAndResourceSignature(serviceId, resourceSignature);
-		
-		if(xxServiceResource != null) {
-			ret = populateViewBean(xxServiceResource);
-		}
+                ret.add(serviceResource);
+            }
+        }
 
-		return ret;
-	}
+        return ret;
+    }
 
-	public List<RangerServiceResource> getTaggedResourcesInServiceId(Long serviceId) {
-		List<RangerServiceResource> ret = new ArrayList<RangerServiceResource>();
+    public RangerServiceResource getByServiceAndResourceSignature(Long serviceId, String resourceSignature) {
+        RangerServiceResource ret = null;
 
-		List<XXServiceResource> xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId);
-		
-		if(CollectionUtils.isNotEmpty(xxServiceResources)) {
-			for(XXServiceResource xxServiceResource : xxServiceResources) {
-				RangerServiceResource serviceResource = populateViewBean(xxServiceResource);
+        XXServiceResource xxServiceResource = daoMgr.getXXServiceResource().findByServiceAndResourceSignature(serviceId, resourceSignature);
 
-				ret.add(serviceResource);
-			}
-		}
+        if (xxServiceResource != null) {
+            ret = populateViewBean(xxServiceResource);
+        }
 
-		return ret;
-	}
+        return ret;
+    }
+
+    public List<RangerServiceResource> getTaggedResourcesInServiceId(Long serviceId) {
+        List<RangerServiceResource> ret = new ArrayList<RangerServiceResource>();
+
+        List<XXServiceResource> xxServiceResources = daoMgr.getXXServiceResource().findByServiceId(serviceId);
+
+        if (CollectionUtils.isNotEmpty(xxServiceResources)) {
+            for (XXServiceResource xxServiceResource : xxServiceResources) {
+                RangerServiceResource serviceResource = populateViewBean(xxServiceResource);
+
+                ret.add(serviceResource);
+            }
+        }
+
+        return ret;
+    }
+
+    @Override
+    protected XXServiceResource mapViewToEntityBean(RangerServiceResource serviceResource, XXServiceResource xxServiceResource, int operationContext) {
+        XXServiceResource ret = super.mapViewToEntityBean(serviceResource, xxServiceResource, operationContext);
+        if (MapUtils.isNotEmpty(serviceResource.getResourceElements())) {
+            String serviceResourceElements = JsonUtils.mapToJson(serviceResource.getResourceElements());
+            if (StringUtils.isNotEmpty(serviceResourceElements)) {
+                ret.setServiceResourceElements(serviceResourceElements);
+            } else {
+                LOG.info("Empty string representing serviceResourceElements in [" + ret + "]!!");
+            }
+        }
+
+        return ret;
+    }
+
+    @Override
+    protected RangerServiceResource mapEntityToViewBean(RangerServiceResource serviceResource, XXServiceResource xxServiceResource) {
+        RangerServiceResource ret = super.mapEntityToViewBean(serviceResource, xxServiceResource);
+        if (StringUtils.isNotEmpty(xxServiceResource.getServiceResourceElements())) {
+            Map<String, RangerPolicy.RangerPolicyResource> serviceResourceElements =
+                RangerTagDBRetriever.gsonBuilder.fromJson(xxServiceResource.getServiceResourceElements(), RangerServiceResourceService.subsumedDataType);
+            if (MapUtils.isNotEmpty(serviceResourceElements)) {
+                ret.setResourceElements(serviceResourceElements);
+            } else {
+                LOG.info("Empty serviceResourceElement in [" + ret + "]!!");
+            }
+        } else {
+            LOG.info("Empty string representing serviceResourceElements in [" + xxServiceResource + "]!!");
+        }
+
+        return ret;
+    }
+
+    @Override
+    Map<String, RangerPolicy.RangerPolicyResource> getServiceResourceElements(XXServiceResource xxServiceResource) {
+        return new HashMap<>();
+    }
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java
index 6af682a..329d3ee 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerServiceResourceServiceBase.java
@@ -73,26 +73,31 @@ public abstract class RangerServiceResourceServiceBase<T extends XXServiceResour
 
 		vObj.setServiceName(xService.getName());
 
-		List<XXServiceResourceElement> resElementList = daoMgr.getXXServiceResourceElement().findByResourceId(xObj.getId());
-		Map<String, RangerPolicy.RangerPolicyResource> resourceElements = new HashMap<String, RangerPolicy.RangerPolicyResource>();
+		Map<String, RangerPolicy.RangerPolicyResource> resourceElements = getServiceResourceElements(xObj);
 
-		for (XXServiceResourceElement resElement : resElementList) {
-			List<String> resValueMapList = daoMgr.getXXServiceResourceElementValue().findValuesByResElementId(resElement.getId());
+		vObj.setResourceElements(resourceElements);
 
-			XXResourceDef xResDef = daoMgr.getXXResourceDef().getById(resElement.getResDefId());
+		return vObj;
+	}
 
-			RangerPolicyResource policyRes = new RangerPolicyResource();
-			policyRes.setIsExcludes(resElement.getIsExcludes());
-			policyRes.setIsRecursive(resElement.getIsRecursive());
-			policyRes.setValues(resValueMapList);
+	Map<String, RangerPolicyResource> getServiceResourceElements(T xObj) {
+        List<XXServiceResourceElement> resElementList = daoMgr.getXXServiceResourceElement().findByResourceId(xObj.getId());
+        Map<String, RangerPolicy.RangerPolicyResource> resourceElements = new HashMap<String, RangerPolicy.RangerPolicyResource>();
 
-			resourceElements.put(xResDef.getName(), policyRes);
-		}
+        for (XXServiceResourceElement resElement : resElementList) {
+            List<String> resValueMapList = daoMgr.getXXServiceResourceElementValue().findValuesByResElementId(resElement.getId());
 
-		vObj.setResourceElements(resourceElements);
+            XXResourceDef xResDef = daoMgr.getXXResourceDef().getById(resElement.getResDefId());
 
-		return vObj;
-	}
+            RangerPolicyResource policyRes = new RangerPolicyResource();
+            policyRes.setIsExcludes(resElement.getIsExcludes());
+            policyRes.setIsRecursive(resElement.getIsRecursive());
+            policyRes.setValues(resValueMapList);
+
+            resourceElements.put(xResDef.getName(), policyRes);
+        }
+        return resourceElements;
+    }
 
 	public PList<V> searchServiceResources(SearchFilter searchFilter) {
 		PList<V> retList = new PList<V>();

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java
index 82eb252..10c73f0 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefService.java
@@ -23,6 +23,8 @@ import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.commons.collections.CollectionUtils;
+import org.apache.ranger.authorization.utils.JsonUtils;
+import org.apache.ranger.biz.RangerTagDBRetriever;
 import org.apache.ranger.common.SearchField;
 import org.apache.ranger.common.SearchField.DATA_TYPE;
 import org.apache.ranger.common.SearchField.SEARCH_TYPE;
@@ -102,5 +104,27 @@ public class RangerTagDefService extends RangerTagDefServiceBase<XXTagDef, Range
 
 		return ret;
 	}
+
+    @Override
+    protected RangerTagDef mapEntityToViewBean(RangerTagDef vObj, XXTagDef xObj) {
+        super.mapEntityToViewBean(vObj, xObj);
+
+        List<RangerTagDef.RangerTagAttributeDef> attributeDefs = RangerTagDBRetriever.gsonBuilder.fromJson(xObj.getTagAttrDefs(), RangerTagDBRetriever.subsumedDataType);
+        vObj.setAttributeDefs(attributeDefs);
+
+        return vObj;
+    }
+
+    @Override
+    protected XXTagDef mapViewToEntityBean(RangerTagDef vObj, XXTagDef xObj, int OPERATION_CONTEXT) {
+        super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT);
+        xObj.setTagAttrDefs(JsonUtils.listToJson(vObj.getAttributeDefs()));
+        return xObj;
+    }
+
+    @Override
+    public List<RangerTagDef.RangerTagAttributeDef> getAttributeDefForTagDef(XXTagDef xtagDef) {
+        return new ArrayList<>();
+    }
 	
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java
index 408358c..929a4b0 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagDefServiceBase.java
@@ -40,7 +40,7 @@ public abstract class RangerTagDefServiceBase<T extends XXTagDef, V extends Rang
 	GUIDUtil guidUtil;
 
 	@Autowired
-	RangerAuditFields rangerAuditFields;
+	RangerAuditFields<?> rangerAuditFields;
 	
 	@Autowired
 	RangerConfigUtil configUtil;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java b/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java
index 28b9115..2fa8830 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/RangerTagService.java
@@ -19,13 +19,21 @@
 
 package org.apache.ranger.service;
 
+import java.lang.reflect.Type;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
+import com.google.gson.reflect.TypeToken;
 import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.ranger.authorization.utils.JsonUtils;
+import org.apache.ranger.biz.RangerTagDBRetriever;
 import org.apache.ranger.common.SearchField;
 import org.apache.ranger.common.SearchField.DATA_TYPE;
 import org.apache.ranger.common.SearchField.SEARCH_TYPE;
+import org.apache.ranger.entity.XXServiceResource;
 import org.apache.ranger.entity.XXTag;
 import org.apache.ranger.plugin.model.RangerTag;
 import org.apache.ranger.plugin.util.SearchFilter;
@@ -35,6 +43,8 @@ import org.springframework.stereotype.Service;
 @Service
 public class RangerTagService extends RangerTagServiceBase<XXTag, RangerTag> {
 
+	public static final Type subsumedDataType = new TypeToken<Map<String, String>>() {}.getType();
+
 	public RangerTagService() {
 		searchFields.add(new SearchField(SearchFilter.TAG_ID, "obj.id", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
 		searchFields.add(new SearchField(SearchFilter.TAG_DEF_ID, "obj.type", SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
@@ -95,13 +105,12 @@ public class RangerTagService extends RangerTagServiceBase<XXTag, RangerTag> {
 	public List<RangerTag> getTagsForResourceId(Long resourceId) {
 		List<RangerTag> ret = new ArrayList<RangerTag>();
 
-		List<XXTag> xxTags = daoMgr.getXXTag().findForResourceId(resourceId);
-		
-		if(CollectionUtils.isNotEmpty(xxTags)) {
-			for(XXTag xxTag : xxTags) {
-				RangerTag tag = populateViewBean(xxTag);
+		XXServiceResource serviceResourceEntity = daoMgr.getXXServiceResource().getById(resourceId);
 
-				ret.add(tag);
+		if (serviceResourceEntity != null) {
+			String tagsText = serviceResourceEntity.getTags();
+			if (StringUtils.isNotEmpty(tagsText)) {
+				ret = RangerTagDBRetriever.gsonBuilder.fromJson(tagsText, RangerServiceResourceService.duplicatedDataType);
 			}
 		}
 
@@ -111,13 +120,12 @@ public class RangerTagService extends RangerTagServiceBase<XXTag, RangerTag> {
 	public List<RangerTag> getTagsForResourceGuid(String resourceGuid) {
 		List<RangerTag> ret = new ArrayList<RangerTag>();
 
-		List<XXTag> xxTags = daoMgr.getXXTag().findForResourceGuid(resourceGuid);
-		
-		if(CollectionUtils.isNotEmpty(xxTags)) {
-			for(XXTag xxTag : xxTags) {
-				RangerTag tag = populateViewBean(xxTag);
+		XXServiceResource serviceResourceEntity = daoMgr.getXXServiceResource().findByGuid(resourceGuid);
 
-				ret.add(tag);
+		if (serviceResourceEntity != null) {
+			String tagsText = serviceResourceEntity.getTags();
+			if (StringUtils.isNotEmpty(tagsText)) {
+				ret = RangerTagDBRetriever.gsonBuilder.fromJson(tagsText, RangerServiceResourceService.duplicatedDataType);
 			}
 		}
 
@@ -139,4 +147,25 @@ public class RangerTagService extends RangerTagServiceBase<XXTag, RangerTag> {
 
 		return ret;
 	}
+
+    @Override
+    protected RangerTag mapEntityToViewBean(RangerTag vObj, XXTag xObj) {
+        super.mapEntityToViewBean(vObj, xObj);
+
+        Map<String, String> attributes = RangerTagDBRetriever.gsonBuilder.fromJson(xObj.getTagAttrs(), RangerTagService.subsumedDataType);
+        vObj.setAttributes(attributes);
+        return vObj;
+    }
+
+    @Override
+    protected XXTag mapViewToEntityBean(RangerTag vObj, XXTag xObj, int OPERATION_CONTEXT) {
+        super.mapViewToEntityBean(vObj, xObj, OPERATION_CONTEXT);
+        xObj.setTagAttrs(JsonUtils.mapToJson(vObj.getAttributes()));
+        return xObj;
+    }
+
+    @Override
+    public Map<String, String> getAttributesForTag(XXTag xTag) {
+        return new HashMap<>();
+    }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java b/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java
index c96878d..5f5b5c4 100644
--- a/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java
+++ b/security-admin/src/main/java/org/apache/ranger/service/XPortalUserService.java
@@ -269,18 +269,10 @@ public class XPortalUserService extends
 		//0.6
 		daoManager.getXXTagDef().updateUserIDReference("added_by_id", xXPortalUserId);
 		daoManager.getXXTagDef().updateUserIDReference("upd_by_id", xXPortalUserId);
-		daoManager.getXXTagAttributeDef().updateUserIDReference("added_by_id", xXPortalUserId);
-		daoManager.getXXTagAttributeDef().updateUserIDReference("upd_by_id", xXPortalUserId);
 		daoManager.getXXServiceResource().updateUserIDReference("added_by_id", xXPortalUserId);
 		daoManager.getXXServiceResource().updateUserIDReference("upd_by_id", xXPortalUserId);
-		daoManager.getXXServiceResourceElement().updateUserIDReference("added_by_id", xXPortalUserId);
-		daoManager.getXXServiceResourceElement().updateUserIDReference("upd_by_id", xXPortalUserId);
-		daoManager.getXXServiceResourceElementValue().updateUserIDReference("added_by_id", xXPortalUserId);
-		daoManager.getXXServiceResourceElementValue().updateUserIDReference("upd_by_id", xXPortalUserId);
 		daoManager.getXXTag().updateUserIDReference("added_by_id", xXPortalUserId);
 		daoManager.getXXTag().updateUserIDReference("upd_by_id", xXPortalUserId);
-		daoManager.getXXTagAttribute().updateUserIDReference("added_by_id", xXPortalUserId);
-		daoManager.getXXTagAttribute().updateUserIDReference("upd_by_id", xXPortalUserId);
 		daoManager.getXXTagResourceMap().updateUserIDReference("added_by_id", xXPortalUserId);
 		daoManager.getXXTagResourceMap().updateUserIDReference("upd_by_id", xXPortalUserId);
 	}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/resources/META-INF/jpa_named_queries.xml
----------------------------------------------------------------------
diff --git a/security-admin/src/main/resources/META-INF/jpa_named_queries.xml b/security-admin/src/main/resources/META-INF/jpa_named_queries.xml
index cdf6ba6..be51592 100644
--- a/security-admin/src/main/resources/META-INF/jpa_named_queries.xml
+++ b/security-admin/src/main/resources/META-INF/jpa_named_queries.xml
@@ -244,22 +244,11 @@
 		</query>
 	</named-query>
 
-	<named-query name="XXUser.findByPolicyItemId">
-		<query>select obj.name from XXUser obj, XXPolicyItemUserPerm polItemUser 
-		where polItemUser.policyItemId = :polItemId and polItemUser.userId = obj.id </query>
-	</named-query>
-
 	<named-query name="XXUser.findByPortalUserId">
 		<query>select obj from XXUser obj, XXPortalUser portalUser where portalUser.id = :portalUserId and 
 		obj.name = portalUser.loginId</query>
 	</named-query>
 
-	<named-query name="XXGroup.findByPolicyItemId">
-		<query>select obj.name from XXGroup obj, XXPolicyItemGroupPerm polItemGrp 
-		where polItemGrp.policyItemId = :polItemId and polItemGrp.groupId = obj.id </query>
-	</named-query>
-
-
 	<!-- XXPolicyItem -->
 	<named-query name="XXPolicyItem.findByPolicyId">
 		<query>select obj from XXPolicyItem obj
@@ -388,18 +377,6 @@
 		<query>select obj from XXPolicyConditionDef obj where obj.defId = :serviceDefId and obj.name = :name order by obj.order</query>
 	</named-query>
 
-	<named-query name="XXPolicyConditionDef.findByPolicyItemId">
-		<query>select obj from XXPolicyConditionDef obj, XXPolicyItemCondition xPolItemCond 
-		where xPolItemCond.policyItemId = :polItemId and obj.id = xPolItemCond.type order by obj.order</query>
-	</named-query>
-
-	<named-query name="XXPolicyConditionDef.findByPolicyItemIdAndName">
-		<query>select obj from XXPolicyConditionDef obj, XXPolicyItemCondition xPolItemCond 
-				where xPolItemCond.policyItemId = :polItemId and obj.name = :name 
-				and obj.id = xPolItemCond.type order by obj.order 
-		</query>
-	</named-query>
-
 	<!-- XXContextEnricherDef -->
 	<named-query name="XXContextEnricherDef.findByServiceDefId">
 		<query>select obj from XXContextEnricherDef obj where obj.defId = :serviceDefId order by obj.order</query>
@@ -511,10 +488,6 @@
 	</named-query>
 
 	<!-- XXPolicyResource -->
-	<named-query name="XXPolicyResource.findByResDefIdAndPolicyId">
-		<query>select obj from XXPolicyResource obj where 
-				obj.policyId = :polId and obj.resDefId = :resDefId</query>
-	</named-query>
 
 	<named-query name="XXPolicyResource.findByPolicyId">
 		<query>select obj from XXPolicyResource obj
@@ -533,11 +506,6 @@
 	<named-query name="XXPolicyResource.findByResDefId">
 		<query>select obj from XXPolicyResource obj where obj.resDefId = :resDefId</query>
 	</named-query>
-	
-	<!-- XXPolicyResourceMap -->
-	<named-query name="XXPolicyResourceMap.findByPolicyResId">
-		<query>select obj from XXPolicyResourceMap obj where obj.resourceId = :polResId order by obj.order</query>
-	</named-query>
 
 	<named-query name="XXPolicyResourceMap.findByPolicyId">
 		<query>select obj from XXPolicyResourceMap obj, XXPolicyResource res
@@ -556,13 +524,6 @@
 	</named-query>
 
 	<!-- XXPolicyItemAccess -->
-	<named-query name="XXPolicyItemAccess.findByPolicyItemId">
-		<query>select obj from XXPolicyItemAccess obj where obj.policyItemId = :polItemId order by obj.order</query>
-	</named-query>
-	
-	<named-query name="XXPolicyItemAccess.findByType">
-		<query>select obj from XXPolicyItemAccess obj where obj.type = :type</query>
-	</named-query>
 
 	<named-query name="XXPolicyItemAccess.findByPolicyId">
 		<query>select obj from XXPolicyItemAccess obj, XXPolicyItem item
@@ -579,21 +540,214 @@
 		        order by item.policyId, obj.policyItemId, obj.order
 		</query>
 	</named-query>
-	
-	<!-- XXPolicyItemCondition -->
-	<named-query name="XXPolicyItemCondition.findByPolicyItemId">
-		<query>select obj from XXPolicyItemCondition obj where obj.policyItemId = :polItemId order by obj.order</query>
+
+	<!-- XXPolicyRefAccessType -->
+	<named-query name="XXPolicyRefAccessType.findByPolicyId">
+		<query>select obj from XXPolicyRefAccessType obj where obj.policyId = :policyId </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefAccessType.findByAccessTypeDefId">
+		<query>select obj from XXPolicyRefAccessType obj where obj.accessDefId = :accessDefId</query>
+	</named-query>
+
+	<!-- XXPolicyRefCondition -->
+	<named-query name="XXPolicyRefCondition.findByPolicyId">
+		<query>select obj from XXPolicyRefCondition obj where obj.policyId = :policyId </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefCondition.findByConditionName">
+		<query>select obj from XXPolicyRefCondition obj where obj.conditionName = :conditionName</query>
+	</named-query>
+
+	<!-- XXPolicyRefGroup -->
+	<named-query name="XXPolicyRefGroup.findByPolicyId">
+		<query>select obj from XXPolicyRefGroup obj where obj.policyId = :policyId </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefGroup.findByGroupName">
+		<query>select obj from XXPolicyRefGroup obj where obj.groupName = :groupName</query>
+	</named-query>
+
+<!-- 	new queries -->
+	<named-query name="XXPolicyRefGroup.findByGroupIdAndPolicyId">
+		<query>select obj from XXPolicyRefGroup obj where obj.groupId = :groupId and obj.policyId = :policyId </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefCondition.findByConditionDefIdAndPolicyId">
+		<query>select obj from XXPolicyRefCondition obj where obj.conditionDefId = :conditionDefId and obj.policyId = :policyId </query>
+	</named-query>
+	<named-query name="XXPolicyRefCondition.findByConditionDefId">
+		<query>select obj from XXPolicyRefCondition obj where obj.conditionDefId = :conditionDefId </query>
+	</named-query>
+
+	<named-query name="XXUser.findUpdatedUserNames">
+		<query>select distinct obj from XXUser obj, XXPolicyRefUser ref where ref.policyId   = :policyId and ref.userId    = obj.id
+		and ref.userName != obj.name</query>
+	</named-query>
+
+	<named-query name="XXAccessTypeDef.findUpdatedAccessDefNames">
+		<query>select distinct obj from XXAccessTypeDef obj, XXPolicyRefAccessType ref where ref.policyId   = :policyId and ref.accessDefId    = obj.id
+		and ref.accessTypeName != obj.name</query>
+	</named-query>
+
+	<named-query name="XXDataMaskTypeDef.findUpdatedDataMaskDefNames">
+		<query>select distinct obj from XXDataMaskTypeDef obj, XXPolicyRefDataMaskType ref where ref.policyId   = :policyId and ref.dataMaskDefId    = obj.id
+		and ref.dataMaskTypeName != obj.name</query>
+	</named-query>
+
+	<named-query name="XXResourceDef.findUpdatedResourceDefNames">
+		<query>select distinct obj from XXResourceDef obj, XXPolicyRefResource ref where ref.policyId   = :policyId and ref.resourceDefId    = obj.id
+		and ref.resourceName != obj.name</query>
+	</named-query>
+
+    <named-query name="XXPolicyRefGroup.findUpdatedGroupNamesByPolicy">
+        <query>select groupRef.policyId, groupRef.groupName, grp.name
+            from XXPolicyRefGroup groupRef, XXGroup grp
+            where groupRef.policyId    = :policy
+            and groupRef.groupId       = grp.id
+            and groupRef.groupName    != grp.name
+        </query>
+    </named-query>
+
+	<named-query name="XXPolicyRefGroup.findUpdatedGroupNamesByService">
+		<query>select groupRef.policyId, groupRef.groupName, grp.name
+		    from XXPolicy policy, XXPolicyRefGroup groupRef, XXGroup grp
+		    where policy.service       = :service
+		    and groupRef.policyId      = policy.id
+		    and groupRef.groupId       = grp.id
+		    and groupRef.groupName    != grp.name
+        </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefUser.findUpdatedUserNamesByPolicy">
+        <query>select userRef.policyId, userRef.userName, user.name
+            from XXPolicyRefUser userRef, XXUser user
+            where userRef.policyId    = :policy
+            and userRef.userId       = user.id
+            and userRef.userName    != user.name
+        </query>
+    </named-query>
+
+	<named-query name="XXPolicyRefUser.findUpdatedUserNamesByService">
+		<query>select userRef.policyId, userRef.userName, user.name
+		    from XXPolicy policy, XXPolicyRefUser userRef, XXUser user
+		    where policy.service       = :service
+		    and userRef.policyId      = policy.id
+		    and userRef.userId       = user.id
+		    and userRef.userName    != user.name
+        </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefAccessType.findUpdatedAccessNamesByPolicy">
+        <query>select accessRef.policyId, accessRef.accessTypeName, accessDef.name
+            from XXPolicyRefAccessType accessRef, XXAccessTypeDef accessDef
+            where accessRef.policyId    = :policy
+            and accessRef.accessDefId       = accessDef.id
+            and accessRef.accessTypeName    != accessDef.name
+        </query>
+    </named-query>
+
+	<named-query name="XXPolicyRefAccessType.findUpdatedAccessNamesByService">
+		<query>select accessRef.policyId, accessRef.accessTypeName, accessDef.name
+            from  XXPolicy policy, XXPolicyRefAccessType accessRef, XXAccessTypeDef accessDef
+		    where policy.service       = :service
+		    and accessRef.policyId      = policy.id
+		    and accessRef.accessDefId       = accessDef.id
+            and accessRef.accessTypeName    != accessDef.name
+        </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefResource.findUpdatedResourceNamesByPolicy">
+		<query>select resourceRef.policyId, resourceRef.resourceName, resourceDef.name
+            from XXPolicyRefResource resourceRef, XXResourceDef resourceDef
+		    where resourceRef.policyId     = :policy
+		    and resourceRef.resourceDefId       = resourceDef.id
+            and resourceRef.resourceName    != resourceDef.name
+        </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefResource.findUpdatedResourceNamesByService">
+		<query>select resourceRef.policyId, resourceRef.resourceName, resourceDef.name
+            from  XXPolicy policy, XXPolicyRefResource resourceRef, XXResourceDef resourceDef
+		    where policy.service       = :service
+		    and resourceRef.policyId      = policy.id
+		    and resourceRef.resourceDefId       = resourceDef.id
+            and resourceRef.resourceName    != resourceDef.name
+        </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByPolicy">
+	        <query>select dataMaskRef.policyId, dataMaskRef.dataMaskTypeName, dMaskDef.name
+	            from XXPolicyRefDataMaskType dataMaskRef, XXDataMaskTypeDef dMaskDef
+	            where dataMaskRef.policyId    = :policy
+	            and dataMaskRef.dataMaskDefId       = dMaskDef.id
+	            and dataMaskRef.dataMaskTypeName    != dMaskDef.name
+	        </query>
+	    </named-query>
+
+	<named-query name="XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByService">
+		<query>select dataMaskRef.policyId, dataMaskRef.dataMaskTypeName, dMaskDef.name
+		    from XXPolicy policy, XXPolicyRefDataMaskType dataMaskRef, XXDataMaskTypeDef dMaskDef
+		    where policy.service       = :service
+		    and dataMaskRef.policyId      = policy.id
+		    and dataMaskRef.dataMaskDefId       = dMaskDef.id
+		    and dataMaskRef.dataMaskTypeName    != dMaskDef.name
+	    </query>
+	</named-query>
+
+    <named-query name="XXPolicyRefCondition.findUpdatedConditionNamesByPolicy">
+        <query>select conditionRef.policyId, conditionRef.conditionName, condDef.name
+            from XXPolicyRefCondition conditionRef, XXPolicyConditionDef condDef
+            where conditionRef.policyId    = :policy
+            and conditionRef.conditionDefId       = condDef.id
+            and conditionRef.conditionName    != condDef.name
+        </query>
+    </named-query>
+
+	<named-query name="XXPolicyRefCondition.findUpdatedConditionNamesByService">
+		<query>select conditionRef.policyId, conditionRef.conditionName, condDef.name
+		    from XXPolicy policy, XXPolicyRefCondition conditionRef, XXPolicyConditionDef condDef
+		    where policy.service       = :service
+		    and conditionRef.policyId      = policy.id
+		    and conditionRef.conditionDefId       = condDef.id
+		    and conditionRef.conditionName    != condDef.name
+        </query>
+	</named-query>
+<!-- end -->
+
+	<!-- XXPolicyRefDataMaskType -->
+	<named-query name="XXPolicyRefDataMaskType.findByPolicyId">
+		<query>select obj from XXPolicyRefDataMaskType obj where obj.policyId = :policyId </query>
+	</named-query>
+
+	<named-query name="XXPolicyRefDataMaskType.findByDataMaskTypeName">
+		<query>select obj from XXPolicyRefDataMaskType obj where obj.dataMaskTypeName = :dataMaskTypeName</query>
+	</named-query>
+
+	<!-- XXPolicyRefResource -->
+	<named-query name="XXPolicyRefResource.findByPolicyId">
+		<query>select obj from XXPolicyRefResource obj where obj.policyId = :policyId </query>
 	</named-query>
 
-	<named-query name="XXPolicyItemCondition.findByPolicyItemAndDefId">
-		<query>select obj from XXPolicyItemCondition obj where 
-				obj.policyItemId = :polItemId and obj.type = :polCondDefId order by obj.order</query>
+	<named-query name="XXPolicyRefResource.findByResourceDefId">
+		<query>select obj from XXPolicyRefResource obj where obj.resourceDefId = :resourceDefId</query>
 	</named-query>
 
-	<named-query name="XXPolicyItemCondition.findByPolicyConditionDefId">
-		<query>select obj from XXPolicyItemCondition obj where obj.type = :polCondDefId</query>
+	<!-- XXPolicyRefUser -->
+	<named-query name="XXPolicyRefUser.findByPolicyId">
+		<query>select obj from XXPolicyRefUser obj where obj.policyId = :policyId </query>
 	</named-query>
 
+	<named-query name="XXPolicyRefUser.findByUserName">
+		<query>select obj from XXPolicyRefUser obj where obj.userName = :userName</query>
+	</named-query>
+
+	<named-query name="XXPolicyRefUser.findByUserId">
+		<query>select obj from XXPolicyRefUser obj where obj.userId = :userId</query>
+	</named-query>
+
+	<!-- XXPolicyItemCondition -->
+
 	<named-query name="XXPolicyItemCondition.findByPolicyId">
 		<query>select obj from XXPolicyItemCondition obj, XXPolicyItem item
 		        where obj.policyItemId = item.id
@@ -611,9 +765,6 @@
 	</named-query>
 	
 	<!-- XXPolicyItemGroupPerm -->
-	<named-query name="XXPolicyItemGroupPerm.findByPolicyItemId">
-		<query>select obj from XXPolicyItemGroupPerm obj where obj.policyItemId = :polItemId order by obj.order</query>
-	</named-query>
 
 	<named-query name="XXPolicyItemGroupPerm.findByPolicyId">
 		<query>select obj from XXPolicyItemGroupPerm obj, XXPolicyItem item
@@ -632,9 +783,6 @@
 	</named-query>
 
 	<!-- XXPolicyItemUserPerm -->
-	<named-query name="XXPolicyItemUserPerm.findByPolicyItemId">
-		<query>select obj from XXPolicyItemUserPerm obj where obj.policyItemId = :polItemId order by obj.order</query>
-	</named-query>
 
 	<named-query name="XXPolicyItemUserPerm.findByPolicyId">
 		<query>select obj from XXPolicyItemUserPerm obj, XXPolicyItem item
@@ -653,9 +801,6 @@
 	</named-query>
 
 	<!-- XXPolicyItemDataMaskInfo -->
-	<named-query name="XXPolicyItemDataMaskInfo.findByPolicyItemId">
-		<query>select obj from XXPolicyItemDataMaskInfo obj where obj.policyItemId = :polItemId</query>
-	</named-query>
 
 	<named-query name="XXPolicyItemDataMaskInfo.findByPolicyId">
 		<query>select obj from XXPolicyItemDataMaskInfo obj, XXPolicyItem item
@@ -673,14 +818,7 @@
 		</query>
 	</named-query>
 
-	<named-query name="XXPolicyItemDataMaskInfo.findByType">
-		<query>select obj from XXPolicyItemDataMaskInfo obj where obj.type = :type</query>
-	</named-query>
-
 	<!-- XXPolicyItemRowFilterInfo -->
-	<named-query name="XXPolicyItemRowFilterInfo.findByPolicyItemId">
-		<query>select obj from XXPolicyItemRowFilterInfo obj where obj.policyItemId = :polItemId</query>
-	</named-query>
 
 	<named-query name="XXPolicyItemRowFilterInfo.findByPolicyId">
 		<query>select obj from XXPolicyItemRowFilterInfo obj, XXPolicyItem item
@@ -855,20 +993,6 @@
 		</query>
 	</named-query>
 
-	<named-query name="XXServiceResourceElement.findForServicePlugin">
-		<query>
-			select obj from XXServiceResourceElement obj where obj.resourceId in
-			(select serviceRes.id from XXServiceResource serviceRes, XXService service where service.id = :serviceId and service.tagService is not null and serviceRes.serviceId = service.id and serviceRes.id in
-			(select tagResMap.resourceId from XXTagResourceMap tagResMap, XXTag tag, XXTagDef tagDef
-			where tagResMap.tagId = tag.id and tag.type = tagDef.id and tagDef.name in
-			(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-			where policy.service = service.tagService and policy.isEnabled = TRUE and policyRes.policyId = policy.id and policyResMap.resourceId = policyRes.id)
-			)
-			)
-			order by obj.resourceId, obj.id
-		</query>
-	</named-query>
-
 	<named-query name="XXServiceResourceElement.findByServiceId">
 		<query>select obj from XXServiceResourceElement obj where obj.resourceId in
 					(select serviceresource.id from XXServiceResource serviceresource where serviceresource.serviceId = :serviceId)
@@ -893,20 +1017,6 @@
 		</query>
 	</named-query>
 
-	<named-query name="XXServiceResourceElementValue.findForServicePlugin">
-		<query>
-			select obj from XXServiceResourceElementValue obj, XXServiceResourceElement serviceResElem where obj.resElementId = serviceResElem.id and
-			serviceResElem.resourceId in
-			(select serviceRes.id from XXServiceResource serviceRes, XXService service where service.id = :serviceId and service.tagService is not null and serviceRes.serviceId = service.id and serviceRes.id in
-			(select tagResMap.resourceId from XXTagResourceMap tagResMap, XXTag tag, XXTagDef tagDef
-			where tagResMap.tagId = tag.id and tag.type = tagDef.id and tagDef.name in
-			(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-			where policy.service = service.tagService and policy.isEnabled = TRUE and policyRes.policyId = policy.id and policyResMap.resourceId = policyRes.id)
-			)
-			)
-			order by serviceResElem.resourceId, serviceResElem.id
-		</query>
-	</named-query>
 	<named-query name="XXServiceResourceElementValue.findByServiceId">
 		<query>select obj from XXServiceResourceElementValue obj, XXServiceResourceElement resElem where obj.resElementId = resElem.id and resElem.resourceId in
 			(select res.id from XXServiceResource res where res.serviceId = :serviceId)
@@ -954,19 +1064,6 @@
 				order by obj.resourceId</query>
 	</named-query>
 
-	<named-query name="XXTagResourceMap.findForServicePlugin">
-		<query>
-			select obj from XXTagResourceMap obj, XXService service, XXServiceResource serviceRes where service.id = :serviceId and service.tagService is not null
-			and obj.resourceId = serviceRes.id and serviceRes.serviceId = :serviceId
-			and obj.tagId in
-			(select tag.id from XXTag tag, XXTagDef tagDef where tag.type = tagDef.id and tagDef.name in
-			(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-			where policy.service = service.tagService and policy.isEnabled = TRUE and policyRes.policyId = policy.id and policyResMap.resourceId = policyRes.id)
-			)
-			order by obj.resourceId
-		</query>
-	</named-query>
-
 	<named-query name="XXTagResourceMap.getTagIdsForResourceId">
 		<query>select obj.tagId from XXTagResourceMap obj
 				where obj.resourceId = :resourceId order by obj.id
@@ -980,22 +1077,14 @@
 	<named-query name="XXTagDef.findByName">
 		<query>select obj from XXTagDef obj where obj.name = :name</query>
 	</named-query>
-	
-	<named-query name="XXTagDef.findByServiceId">
-		<query>select obj from XXTagDef obj where obj.id in
-				(select tag.type from XXTag tag, XXTagResourceMap tagRes, XXServiceResource resource where tag.id = tagRes.tagId and tagRes.resourceId = resource.id and resource.serviceId = :serviceId)
-				order by obj.id
-		</query>
-	</named-query>
 
-	<named-query name="XXTagDef.findForServicePlugin">
-		<query>select obj from XXTagDef obj, XXService service where service.id = :serviceId and service.tagService is not null and
-			obj.name in
-			(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-			where policy.service = service.tagService and policyRes.policyId = policy.id and policy.isEnabled = TRUE and policyResMap.resourceId = policyRes.id)
+	<named-query name="XXTagDef.findByServiceId">
+		<query>select obj.id, obj.guid, obj.version, obj.isEnabled, obj.name, obj.source, obj.tagAttrDefs from XXTagDef obj where obj.id in
+			(select tag.type from XXTag tag, XXTagResourceMap tagRes, XXServiceResource resource where tag.id = tagRes.tagId and tagRes.resourceId = resource.id and resource.serviceId = :serviceId)
 			order by obj.id
 		</query>
 	</named-query>
+
 	<named-query name="XXTagDef.findByResourceId">
 		<query>select obj from XXTagDef obj where obj.id in
 			(select tag.type from XXTag tag, XXTagResourceMap tagRes where tag.id = tagRes.tagId and tagRes.resourceId = :resourceId)
@@ -1017,16 +1106,6 @@
 			order by obj.tagDefId
 		</query>
 	</named-query>
-	<named-query name="XXTagAttributeDef.findForServicePlugin">
-		<query>select obj from XXTagAttributeDef obj where obj.tagDefId in
-			(select tagDef.id from XXTagDef tagDef, XXService service where service.id = :serviceId and service.tagService is not null and
-			tagDef.name in
-			(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-			where policy.service = service.tagService and policy.isEnabled = TRUE and policyRes.policyId = policy.id and policyResMap.resourceId = policyRes.id)
-			)
-			order by obj.tagDefId
-		</query>
-	</named-query>
 	<named-query name="XXTagAttributeDef.findByResourceId">
 		<query>select obj from XXTagAttributeDef obj where obj.tagDefId in
 			(select tag.type from XXTag tag, XXTagResourceMap tagRes where tag.id = tagRes.tagId and tagRes.resourceId = :resourceId)
@@ -1062,16 +1141,6 @@
 		</query>
 	</named-query>
 
-	<named-query name="XXTag.findForServicePlugin">
-		<query>
-			select obj from XXTag obj, XXTagDef tagDef, XXService service where service.id = :serviceId and service.tagService is not null and
-			obj.type = tagDef.id and tagDef.name in
-			(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-			where policy.service = service.tagService and policy.isEnabled = TRUE and policyRes.policyId = policy.id and policyResMap.resourceId = policyRes.id)
-			order by obj.id
-		</query>
-	</named-query>
-
 	<named-query name="XXTag.findByServiceIdAndOwner">
 		<query>select obj from XXTag obj where obj.owner = :owner and obj.id in
 			(select tagRes.tagId from XXTagResourceMap tagRes, XXServiceResource resource where tagRes.resourceId = resource.id and resource.serviceId = :serviceId)
@@ -1106,18 +1175,6 @@
 		</query>
 	</named-query>
 
-	<named-query name="XXTagAttribute.findForServicePlugin">
-		<query>
-			select obj from XXTagAttribute obj where obj.tagId in
-			(select tag.id from XXTag tag, XXTagDef tagDef, XXService service where service.id = :serviceId and service.tagService is not null and
-			tag.type = tagDef.id and tagDef.name in
-			(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-			where policy.service = service.tagService and policy.isEnabled = TRUE and policyRes.policyId = policy.id and policyResMap.resourceId = policyRes.id)
-			)
-			order by obj.tagId
-		</query>
-	</named-query>
-
 	<named-query name="XXServiceResource.findByGuid">
 		<query>select obj from XXServiceResource obj where obj.guid = :guid</query>
 	</named-query>
@@ -1129,9 +1186,9 @@
 	</named-query>
 
 	<named-query name="XXServiceResource.findTaggedResourcesInServiceId">
-		<query>select obj from XXServiceResource obj where obj.serviceId = :serviceId and obj.id in
-					(select tagResMap.resourceId from XXTagResourceMap tagResMap)
-				order by obj.id
+		<query>select obj.id, obj.guid, obj.version, obj.isEnabled, obj.resourceSignature, obj.serviceId, obj.serviceResourceElements, obj.tags from XXServiceResource obj where obj.serviceId = :serviceId and obj.id in
+            (select tagResMap.resourceId from XXTagResourceMap tagResMap)
+            order by obj.id
 		</query>
 	</named-query>
 
@@ -1141,18 +1198,6 @@
 		</query>
 	</named-query>
 
-	<named-query name="XXServiceResource.findForServicePlugin">
-		<query>
-			select obj from XXServiceResource obj, XXService service where service.id = :serviceId and service.tagService is not null and obj.serviceId = service.id and obj.id in
-				(select tagResMap.resourceId from XXTagResourceMap tagResMap, XXTag tag, XXTagDef tagDef
-					where tagResMap.tagId = tag.id and tag.type = tagDef.id and tagDef.name in
-						(select policyResMap.value from XXPolicyResourceMap policyResMap, XXPolicyResource policyRes, XXPolicy policy
-							where policy.service = service.tagService and policy.isEnabled = TRUE and policyRes.policyId = policy.id and policyResMap.resourceId = policyRes.id)
-				)
-			order by obj.id
-		</query>
-	</named-query>
-
 	<named-query name="XXServiceResource.findByServiceAndResourceSignature">
 		<query>select obj from XXServiceResource obj where obj.serviceId = :serviceId and obj.resourceSignature = :resourceSignature</query>
 	</named-query>
@@ -1182,12 +1227,12 @@
 		</query>
 	</named-query>
 	<named-query name="XXPolicy.findByUserId">
-		<query>select obj from XXPolicy obj, XXPolicyItem polItem,XXPolicyItemUserPerm polItemUserPerm where 
-		 obj.id = polItem.policyId and polItem.id = polItemUserPerm.policyItemId and polItemUserPerm.userId = :userId</query>
+		<query>select obj from XXPolicy obj, XXPolicyRefUser ref where
+		 obj.id = ref.policyId and ref.userId = :userId</query>
 	</named-query>
 	<named-query name="XXPolicy.findByGroupId">
-		<query>select obj from XXPolicy obj, XXPolicyItem polItem,XXPolicyItemGroupPerm polItemGroupPerm where 
-		 obj.id = polItem.policyId and polItem.id = polItemGroupPerm.policyItemId and polItemGroupPerm.groupId = :groupId</query>
+		<query>select obj from XXPolicy obj, XXPolicyRefGroup ref where
+		 obj.id = ref.policyId and ref.groupId = :groupId</query>
 	</named-query>
 	<named-query name="XXAccessAudit.getMaxIdOfXXAccessAudit">
 		<query>select max(obj.id) from XXAccessAudit obj</query>

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java
----------------------------------------------------------------------
diff --git a/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java b/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java
index c9db90a..bf19efd 100644
--- a/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java
+++ b/security-admin/src/test/java/org/apache/ranger/biz/TestServiceDBStore.java
@@ -22,8 +22,8 @@ import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Map.Entry;
 
+import org.apache.commons.collections.ListUtils;
 import org.apache.ranger.common.ContextUtil;
 import org.apache.ranger.common.RESTErrorUtil;
 import org.apache.ranger.common.RangerFactory;
@@ -47,7 +47,6 @@ import org.apache.ranger.plugin.model.RangerServiceDef.RangerEnumDef;
 import org.apache.ranger.plugin.model.RangerServiceDef.RangerPolicyConditionDef;
 import org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef;
 import org.apache.ranger.plugin.model.RangerServiceDef.RangerServiceConfigDef;
-//import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil;
 import org.apache.ranger.plugin.store.PList;
 import org.apache.ranger.plugin.store.ServicePredicateUtil;
 import org.apache.ranger.plugin.util.SearchFilter;
@@ -67,6 +66,7 @@ import org.apache.ranger.view.RangerServiceDefList;
 import org.apache.ranger.view.RangerServiceList;
 import org.apache.ranger.view.VXGroupList;
 import org.apache.ranger.view.VXString;
+import org.apache.ranger.view.VXUser;
 import org.apache.ranger.view.VXUserList;
 import org.junit.Assert;
 import org.junit.FixMethodOrder;
@@ -130,13 +130,16 @@ public class TestServiceDBStore {
 	@Mock
 	ServicePredicateUtil predicateUtil;
 
+    @Mock
+    PolicyRefUpdater policyRefUpdater;
+
 	@Mock
 	XGroupService xGroupService;
 	
 	
 	@Mock
 	RESTErrorUtil restErrorUtil;
-	
+
 	@Mock
 	AssetMgr assetMgr;
 
@@ -154,6 +157,22 @@ public class TestServiceDBStore {
 				.getCurrentUserSession();
 		currentUserSession.setUserAdmin(true);
 	}
+	
+	private XXAccessTypeDef rangerKmsAccessTypes(String accessTypeName, int itemId) {
+		XXAccessTypeDef accessTypeDefObj = new XXAccessTypeDef();
+		accessTypeDefObj.setAddedByUserId(Id);
+		accessTypeDefObj.setCreateTime(new Date());
+		accessTypeDefObj.setDefid(Long.valueOf(itemId));
+		accessTypeDefObj.setId(Long.valueOf(itemId));
+		accessTypeDefObj.setItemId(Long.valueOf(itemId));
+		accessTypeDefObj.setLabel(accessTypeName);
+		accessTypeDefObj.setName(accessTypeName);
+		accessTypeDefObj.setOrder(null);
+		accessTypeDefObj.setRbkeylabel(null);
+		accessTypeDefObj.setUpdatedByUserId(Id);
+		accessTypeDefObj.setUpdateTime(new Date());
+		return accessTypeDefObj;
+	}
 
 	private RangerServiceDef rangerServiceDef() {
 		List<RangerServiceConfigDef> configs = new ArrayList<RangerServiceConfigDef>();
@@ -224,6 +243,28 @@ public class TestServiceDBStore {
 
 		return rangerService;
 	}
+	
+	private RangerService rangerKMSService() {
+		Map<String, String> configs = new HashMap<String, String>();
+		configs.put("username", "servicemgr");
+		configs.put("password", "servicemgr");
+		configs.put("provider", "kmsurl");
+		
+		RangerService rangerService = new RangerService();
+		rangerService.setId(Id);
+		rangerService.setConfigs(configs);
+		rangerService.setCreateTime(new Date());
+		rangerService.setDescription("service kms policy");
+		rangerService.setGuid("1427365526516_835_1");
+		rangerService.setIsEnabled(true);
+		rangerService.setName("KMS_1");
+		rangerService.setPolicyUpdateTime(new Date());
+		rangerService.setType("7");
+		rangerService.setUpdatedBy("Admin");
+		rangerService.setUpdateTime(new Date());
+		
+		return rangerService;
+	}
 
 	private RangerPolicy rangerPolicy() {
 		List<RangerPolicyItemAccess> accesses = new ArrayList<RangerPolicyItemAccess>();
@@ -531,14 +572,19 @@ public class TestServiceDBStore {
 
 	@Test
 	public void test13deleteServiceDef() throws Exception {
+		setup();
 		XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
 		XXDataMaskTypeDefDao xDataMaskDefDao = Mockito.mock(XXDataMaskTypeDefDao.class);
 		XXAccessTypeDefDao xAccessTypeDefDao = Mockito
 				.mock(XXAccessTypeDefDao.class);
 		XXAccessTypeDefGrantsDao xAccessTypeDefGrantsDao = Mockito
 				.mock(XXAccessTypeDefGrantsDao.class);
-		XXPolicyItemAccessDao xPolicyItemAccessDao = Mockito
-				.mock(XXPolicyItemAccessDao.class);
+		XXPolicyRefAccessTypeDao xPolicyRefAccessTypeDao = Mockito
+				.mock(XXPolicyRefAccessTypeDao.class);
+		XXPolicyRefConditionDao xPolicyRefConditionDao  = Mockito
+				.mock(XXPolicyRefConditionDao.class);
+		XXPolicyRefResourceDao xPolicyRefResourceDao = Mockito
+				.mock(XXPolicyRefResourceDao.class);
 		XXContextEnricherDefDao xContextEnricherDefDao = Mockito
 				.mock(XXContextEnricherDefDao.class);
 		XXEnumDefDao xEnumDefDao = Mockito.mock(XXEnumDefDao.class);
@@ -546,13 +592,7 @@ public class TestServiceDBStore {
 				.mock(XXEnumElementDefDao.class);
 		XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito
 				.mock(XXPolicyConditionDefDao.class);
-		XXPolicyItemConditionDao xPolicyItemConditionDao = Mockito
-				.mock(XXPolicyItemConditionDao.class);
 		XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class);
-		XXPolicyResourceDao xPolicyResourceDao = Mockito
-				.mock(XXPolicyResourceDao.class);
-		XXPolicyResourceMapDao xPolicyResourceMapDao = Mockito
-				.mock(XXPolicyResourceMapDao.class);
 		XXServiceConfigDefDao xServiceConfigDefDao = Mockito
 				.mock(XXServiceConfigDefDao.class);
 
@@ -783,6 +823,40 @@ public class TestServiceDBStore {
 		policyItemUserPermObj.setUserId(Id);
 		policyItemUserPermList.add(policyItemUserPermObj);
 
+		List<XXPolicyRefAccessType> policyRefAccessTypeList = new ArrayList<XXPolicyRefAccessType>();
+		XXPolicyRefAccessType policyRefAccessType = new XXPolicyRefAccessType();
+		policyRefAccessType.setId(Id);
+		policyRefAccessType.setAccessTypeName("myAccessType");
+		policyRefAccessType.setPolicyId(Id);
+		policyRefAccessType.setCreateTime(new Date());
+		policyRefAccessType.setUpdateTime(new Date());
+		policyRefAccessType.setAddedByUserId(Id);
+		policyRefAccessType.setUpdatedByUserId(Id);
+		policyRefAccessTypeList.add(policyRefAccessType);
+
+		List<XXPolicyRefCondition> policyRefConditionsList = new ArrayList<XXPolicyRefCondition>();
+		XXPolicyRefCondition policyRefCondition = new XXPolicyRefCondition();
+		policyRefCondition.setId(Id);
+		policyRefCondition.setAddedByUserId(Id);
+		policyRefCondition.setConditionDefId(Id);
+		policyRefCondition.setConditionName("myConditionName");
+		policyRefCondition.setPolicyId(Id);
+		policyRefCondition.setUpdatedByUserId(Id);
+		policyRefCondition.setCreateTime(new Date());
+		policyRefCondition.setUpdateTime(new Date());
+		policyRefConditionsList.add(policyRefCondition);
+
+		List<XXPolicyRefResource> policyRefResourcesList = new ArrayList<XXPolicyRefResource>();
+		XXPolicyRefResource policyRefResource = new XXPolicyRefResource();
+		policyRefResource.setAddedByUserId(Id);
+		policyRefResource.setCreateTime(new Date());
+		policyRefResource.setId(Id);
+		policyRefResource.setPolicyId(Id);
+		policyRefResource.setResourceDefId(Id);
+		policyRefResource.setUpdateTime(new Date());
+		policyRefResource.setResourceName("myresourceName");
+		policyRefResourcesList.add(policyRefResource);
+
 		XXUser xUser = new XXUser();
 		xUser.setAddedByUserId(Id);
 		xUser.setCreateTime(new Date());
@@ -795,6 +869,18 @@ public class TestServiceDBStore {
 		xUser.setUpdatedByUserId(Id);
 		xUser.setUpdateTime(new Date());
 
+		Mockito.when(daoManager.getXXPolicyRefAccessType()).thenReturn(xPolicyRefAccessTypeDao);
+		Mockito.when(xPolicyRefAccessTypeDao.findByAccessTypeDefId(Id)).thenReturn(policyRefAccessTypeList);
+		Mockito.when(xPolicyRefAccessTypeDao.remove(policyRefAccessType)).thenReturn(true);
+
+		Mockito.when(daoManager.getXXPolicyRefCondition()).thenReturn(xPolicyRefConditionDao);
+		Mockito.when(xPolicyRefConditionDao.findByConditionDefId(Id)).thenReturn(policyRefConditionsList);
+		Mockito.when(xPolicyRefConditionDao.remove(policyRefCondition)).thenReturn(true);
+
+		Mockito.when(daoManager.getXXPolicyRefResource()).thenReturn(xPolicyRefResourceDao);
+		Mockito.when(xPolicyRefResourceDao.findByResourceDefID(Id)).thenReturn(policyRefResourcesList);
+		Mockito.when(xPolicyRefResourceDao.remove(policyRefResource)).thenReturn(true);
+
 		Mockito.when(serviceDefService.read(Id)).thenReturn(rangerServiceDef);
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.findByServiceDefId(serviceDefId)).thenReturn(null);
@@ -811,11 +897,6 @@ public class TestServiceDBStore {
 				xAccessTypeDefGrantsDao.findByATDId(accessTypeDefObj.getId()))
 				.thenReturn(accessTypeDefGrantslist);
 
-		Mockito.when(daoManager.getXXPolicyItemAccess()).thenReturn(
-				xPolicyItemAccessDao);
-		Mockito.when(xPolicyItemAccessDao.findByType(accessTypeDefObj.getId()))
-				.thenReturn(policyItemAccessList);
-
 		Mockito.when(daoManager.getXXContextEnricherDef()).thenReturn(
 				xContextEnricherDefDao);
 		Mockito.when(xContextEnricherDefDao.findByServiceDefId(serviceDefId))
@@ -835,28 +916,10 @@ public class TestServiceDBStore {
 		Mockito.when(xPolicyConditionDefDao.findByServiceDefId(serviceDefId))
 				.thenReturn(xConditionDefList);
 
-		Mockito.when(daoManager.getXXPolicyItemCondition()).thenReturn(
-				xPolicyItemConditionDao);
-		Mockito.when(
-				xPolicyItemConditionDao
-						.findByPolicyConditionDefId(policyConditionDefObj
-								.getId())).thenReturn(policyItemConditionList);
-
 		Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao);
 		Mockito.when(xResourceDefDao.findByServiceDefId(serviceDefId))
 				.thenReturn(resDefList);
 
-		Mockito.when(daoManager.getXXPolicyResource()).thenReturn(
-				xPolicyResourceDao);
-		Mockito.when(xPolicyResourceDao.findByResDefId(resourceDef.getId()))
-				.thenReturn(policyResourceList);
-
-		Mockito.when(daoManager.getXXPolicyResourceMap()).thenReturn(
-				xPolicyResourceMapDao);
-		Mockito.when(
-				xPolicyResourceMapDao.findByPolicyResId(policyResource.getId()))
-				.thenReturn(policyResourceMapList);
-
 		Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(
 				xServiceConfigDefDao);
 		Mockito.when(xServiceConfigDefDao.findByServiceDefId(serviceDefId))
@@ -1058,8 +1121,6 @@ public class TestServiceDBStore {
 	public void test20updateService() throws Exception {
 		XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
 		XXService xService = Mockito.mock(XXService.class);
-		//XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class);
-		//XXServiceVersionInfo xServiceVersionInfo = Mockito.mock(XXServiceVersionInfo.class);
 		XXServiceConfigMapDao xServiceConfigMapDao = Mockito
 				.mock(XXServiceConfigMapDao.class);
 		XXServiceConfigDefDao xServiceConfigDefDao = Mockito
@@ -1136,10 +1197,6 @@ public class TestServiceDBStore {
 		Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(
 				rangerService);
 
-		//Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao);
-		//Mockito.when(xServiceVersionInfoDao.findByServiceId(Id)).thenReturn(xServiceVersionInfo);
-		//Mockito.when(xServiceVersionInfoDao.update(xServiceVersionInfo)).thenReturn(xServiceVersionInfo);
-
 		RangerService dbRangerService = serviceDBStore
 				.updateService(rangerService, options);
 		Assert.assertNotNull(dbRangerService);
@@ -1158,31 +1215,16 @@ public class TestServiceDBStore {
 
 	@Test
 	public void test21deleteService() throws Exception {
+		setup();
 		XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class);
 		XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
 		XXService xService = Mockito.mock(XXService.class);
-		//XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class);
-		//XXServiceVersionInfo xServiceVersionInfo = Mockito.mock(XXServiceVersionInfo.class);
-		XXPolicyItemDao xPolicyItemDao = Mockito.mock(XXPolicyItemDao.class);
-		XXPolicyItemDataMaskInfoDao xxPolicyItemDataMaskInfoDao = Mockito.mock(XXPolicyItemDataMaskInfoDao.class);
-		XXPolicyItemRowFilterInfoDao xxPolicyItemRowFilterInfoDao = Mockito.mock(XXPolicyItemRowFilterInfoDao.class);
-                XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class);
-		XXPolicyItemConditionDao xPolicyItemConditionDao = Mockito
-				.mock(XXPolicyItemConditionDao.class);
-		XXPolicyItemGroupPermDao xPolicyItemGroupPermDao = Mockito
-				.mock(XXPolicyItemGroupPermDao.class);
-		XXPolicyItemUserPermDao xPolicyItemUserPermDao = Mockito
-				.mock(XXPolicyItemUserPermDao.class);
-		XXPolicyItemAccessDao xPolicyItemAccessDao = Mockito
-				.mock(XXPolicyItemAccessDao.class);
-		XXPolicyResourceDao xPolicyResourceDao = Mockito
-				.mock(XXPolicyResourceDao.class);
-		XXPolicyResourceMapDao xPolicyResourceMapDao = Mockito
-				.mock(XXPolicyResourceMapDao.class);
 		XXServiceConfigMapDao xServiceConfigMapDao = Mockito
 				.mock(XXServiceConfigMapDao.class);
+		XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class);
 
-		RangerService rangerService = rangerService();
+
+        RangerService rangerService = rangerService();
 		RangerPolicy rangerPolicy = rangerPolicy();
 		String name = "HDFS_1-1-20150316062453";
 
@@ -1224,9 +1266,6 @@ public class TestServiceDBStore {
 		policyItem.setUpdateTime(new Date());
 		policyItemList.add(policyItem);
 
-		//List<XXPolicyItemDataMaskInfo> policyItemDataMaskInfoList = new ArrayList<XXPolicyItemDataMaskInfo>();
-		//List<XXPolicyItemRowFilterInfo> policyItemRowFilterInfoList = new ArrayList<XXPolicyItemRowFilterInfo>();
-
 		List<XXPolicyItemCondition> policyItemConditionList = new ArrayList<XXPolicyItemCondition>();
 		XXPolicyItemCondition policyItemCondition = new XXPolicyItemCondition();
 		policyItemCondition.setAddedByUserId(Id);
@@ -1329,54 +1368,6 @@ public class TestServiceDBStore {
 		Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(
 				rangerService);
 
-		//Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao);
-		//Mockito.when(xServiceVersionInfoDao.findByServiceId(Id)).thenReturn(xServiceVersionInfo);
-		//Mockito.when(xServiceVersionInfoDao.update(xServiceVersionInfo)).thenReturn(xServiceVersionInfo);
-
-		Mockito.when(daoManager.getXXPolicyItem()).thenReturn(xPolicyItemDao);
-		Mockito.when(xPolicyItemDao.findByPolicyId(policyItem.getId()))
-				.thenReturn(policyItemList);
-
-		Mockito.when(daoManager.getXXPolicyItemDataMaskInfo()).thenReturn(xxPolicyItemDataMaskInfoDao);
-		//Mockito.when(xxPolicyItemDataMaskInfoDao.findByPolicyItemId(policyItem.getId())).thenReturn(policyItemDataMaskInfoList);
-
-		Mockito.when(daoManager.getXXPolicyItemRowFilterInfo()).thenReturn(xxPolicyItemRowFilterInfoDao);
-		//Mockito.when(xxPolicyItemRowFilterInfoDao.findByPolicyItemId(policyItem.getId())).thenReturn(policyItemRowFilterInfoList);
-
-		Mockito.when(daoManager.getXXPolicyItemCondition()).thenReturn(
-				xPolicyItemConditionDao);
-		/*Mockito.when(
-				xPolicyItemConditionDao.findByPolicyItemId(policyItemCondition
-						.getId())).thenReturn(policyItemConditionList);
-		*/
-		Mockito.when(daoManager.getXXPolicyItemGroupPerm()).thenReturn(
-				xPolicyItemGroupPermDao);
-		/*Mockito.when(
-				xPolicyItemGroupPermDao.findByPolicyItemId(policyItem.getId()))
-				.thenReturn(policyItemGroupPermList);
-		*/
-		Mockito.when(daoManager.getXXPolicyItemUserPerm()).thenReturn(
-				xPolicyItemUserPermDao);
-		/*Mockito.when(xPolicyItemUserPermDao.findByPolicyItemId(Id)).thenReturn(
-				policyItemUserPermList);*/
-
-		Mockito.when(daoManager.getXXPolicyItemAccess()).thenReturn(
-				xPolicyItemAccessDao);
-		/*Mockito.when(
-				xPolicyItemAccessDao.findByPolicyItemId(policyItemAccess
-						.getId())).thenReturn(policyItemAccessList);
-		*/
-		Mockito.when(daoManager.getXXPolicyResource()).thenReturn(
-				xPolicyResourceDao);
-		Mockito.when(xPolicyResourceDao.findByPolicyId(policyResource.getId()))
-				.thenReturn(policyResourceList);
-
-		Mockito.when(daoManager.getXXPolicyResourceMap()).thenReturn(
-				xPolicyResourceMapDao);
-		/*Mockito.when(
-				xPolicyResourceMapDao.findByPolicyResId(policyResourceMap
-						.getId())).thenReturn(policyResourceMapList);
-		*/
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.getById(Id)).thenReturn(xService);
 
@@ -1389,12 +1380,14 @@ public class TestServiceDBStore {
 		Mockito.when(
 				xServiceConfigMapDao.findByServiceId(rangerService.getId()))
 				.thenReturn(xConfMapList);
-
-                Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao);
-                /*Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(xxPolicyLabelMapList);*/
+		Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao);
+		Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST);
 
 		Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true);
-		serviceDBStore.deleteService(Id);
+        Mockito.when(policyRefUpdater.cleanupRefTables(rangerPolicy)).thenReturn(true);
+
+        serviceDBStore.deleteService(Id);
+		Mockito.verify(svcService).delete(rangerService);
 	}
 
 	@Test
@@ -1520,16 +1513,13 @@ public class TestServiceDBStore {
 	}
 
 	@Test
-	public void tess26createPolicy() throws Exception {
+	public void test26createPolicy() throws Exception {
 		setup();
 		XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class);
 		XXPolicy xPolicy = Mockito.mock(XXPolicy.class);
 		XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class);
 		XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
-		//XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class);
 		XXService xService = Mockito.mock(XXService.class);
-		//XXServiceVersionInfo xServiceVersionInfo = Mockito.mock(XXServiceVersionInfo.class);
-		XXPolicyItemDao xPolicyItemDao = Mockito.mock(XXPolicyItemDao.class);
 
 		XXServiceDef xServiceDef = serviceDef();
 		Map<String, String> configs = new HashMap<String, String>();
@@ -1684,9 +1674,6 @@ public class TestServiceDBStore {
 
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.findByName(name)).thenReturn(xService);
-		//Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao);
-		//Mockito.when(xServiceVersionInfoDao.findByServiceId(Id)).thenReturn(xServiceVersionInfo);
-		//Mockito.when(xServiceVersionInfoDao.update(xServiceVersionInfo)).thenReturn(xServiceVersionInfo);
 
 		Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(
 				rangerService);
@@ -1701,15 +1688,8 @@ public class TestServiceDBStore {
 				rangerPolicy);
 
 		Mockito.when(daoManager.getXXPolicy()).thenReturn(xPolicyDao);
-		Mockito.when(xPolicyDao.getById(Id)).thenReturn(xPolicy);
-
-		Mockito.when(
-				rangerAuditFields.populateAuditFields(
-						Mockito.isA(XXPolicyItem.class),
-						Mockito.isA(XXPolicy.class))).thenReturn(xPolicyItem);
-		Mockito.when(daoManager.getXXPolicyItem()).thenReturn(xPolicyItemDao);
-		Mockito.when(xPolicyItemDao.create(xPolicyItem))
-				.thenReturn(xPolicyItem);
+		Mockito.when(xPolicyDao.getById(Id)).thenReturn(xPolicy);Mockito.doNothing().when(policyRefUpdater).createNewPolMappingForRefTable(rangerPolicy, xPolicy, xServiceDef);
+		Mockito.when(policyService.getPopulatedViewObject(xPolicy)).thenReturn(rangerPolicy);
 
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.getById(Id)).thenReturn(xService);
@@ -1721,61 +1701,12 @@ public class TestServiceDBStore {
 				.mock(RangerPolicyResourceSignature.class);
 		Mockito.when(factory.createPolicyResourceSignature(rangerPolicy))
 				.thenReturn(signature);
-
-		XXResourceDefDao xResourceDefDao = Mockito.mock(XXResourceDefDao.class);
-		XXResourceDef xResourceDef = Mockito.mock(XXResourceDef.class);
-		XXPolicyResourceDao xPolicyResourceDao = Mockito
-				.mock(XXPolicyResourceDao.class);
-		XXPolicyConditionDefDao xPolicyConditionDefDao = Mockito
-				.mock(XXPolicyConditionDefDao.class);
-		Mockito.when(daoManager.getXXResourceDef()).thenReturn(xResourceDefDao);
-		Mockito.when(xResourceDefDao.findByNameAndPolicyId(policyName, Id))
-				.thenReturn(xResourceDef);
-
-		Mockito.when(
-				rangerAuditFields.populateAuditFields(
-						Mockito.isA(XXPolicyResource.class),
-						Mockito.isA(XXPolicy.class))).thenReturn(
-				xPolicyResource);
-		Mockito.when(daoManager.getXXPolicyResource()).thenReturn(
-				xPolicyResourceDao);
-		Mockito.when(xPolicyResourceDao.create(xPolicyResource)).thenReturn(
-				xPolicyResource);
-
-		Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(
-				xPolicyConditionDefDao);
-		Mockito.when(
-				xPolicyConditionDefDao.findByServiceDefIdAndName(Id,
-						policyItemCondition.getType())).thenReturn(
-				policyConditionDefObj);
-		for (Entry<String, RangerPolicyResource> resource : policyResource
-				.entrySet()) {
-			Mockito.when(daoManager.getXXResourceDef()).thenReturn(
-					xResourceDefDao);
-			Mockito.when(
-					xResourceDefDao.findByNameAndPolicyId(resource.getKey(),
-							rangerPolicy.getId())).thenReturn(xResourceDef);
-		}
-
-		Mockito.when(daoManager.getXXPolicyConditionDef()).thenReturn(
-				xPolicyConditionDefDao);
-		Mockito.when(
-				xPolicyConditionDefDao.findByServiceDefIdAndName(
-						xServiceDef.getId(), policyItemCondition.getType()))
-				.thenReturn(policyConditionDefObj);
 		Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true);
 
-		//RangerTransactionSynchronizationAdapter spy = Mockito.spy(transactionSynchronizationAdapter);
-		//Mockito.doNothing().when(spy).executeOnTransactionCommit(Mockito.any(Runnable.class));
-
 		RangerPolicy dbRangerPolicy = serviceDBStore.createPolicy(rangerPolicy);
-		Assert.assertNull(dbRangerPolicy);
-		Assert.assertEquals(Id, rangerPolicy.getId());
-		Mockito.verify(daoManager).getXXServiceDef();
-		Mockito.verify(policyService).create(rangerPolicy);
-		Mockito.verify(rangerAuditFields).populateAuditFields(
-				Mockito.isA(XXPolicyItem.class), Mockito.isA(XXPolicy.class));
-		Mockito.verify(daoManager).getXXPolicyItem();
+
+		Assert.assertNotNull(dbRangerPolicy);
+		Assert.assertEquals(Id, dbRangerPolicy.getId());
 	}
 
 	@Test
@@ -1816,18 +1747,10 @@ public class TestServiceDBStore {
 		XXPolicyDao xPolicyDao = Mockito.mock(XXPolicyDao.class);
 		XXPolicy xPolicy = Mockito.mock(XXPolicy.class);
 		XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
-                XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class);
 		XXService xService = Mockito.mock(XXService.class);
-		//XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class);
 		XXServiceDefDao xServiceDefDao = Mockito.mock(XXServiceDefDao.class);
 		XXServiceDef xServiceDef = Mockito.mock(XXServiceDef.class);
-		//XXServiceVersionInfo xServiceVersionInfo = Mockito.mock(XXServiceVersionInfo.class);
-		XXPolicyResourceDao xPolicyResourceDao = Mockito
-				.mock(XXPolicyResourceDao.class);
-		XXPolicyResourceMapDao xPolicyResourceMapDao = Mockito
-				.mock(XXPolicyResourceMapDao.class);
-		XXPolicyItemDao xPolicyItemDao = Mockito.mock(XXPolicyItemDao.class);
-		XXPolicyItem xPolicyItem = Mockito.mock(XXPolicyItem.class);
+		XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class);
 
 		RangerService rangerService = rangerService();
 
@@ -1859,8 +1782,6 @@ public class TestServiceDBStore {
 		policyResourceMap.setValue("1L");
 		policyResourceMapList.add(policyResourceMap);
 
-                List<XXPolicyLabelMap> xxPolicyLabelMapList = new ArrayList<>();
-
 		List<XXServiceConfigDef> xServiceConfigDefList = new ArrayList<XXServiceConfigDef>();
 		XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef();
 		serviceConfigDefObj.setId(Id);
@@ -1888,10 +1809,6 @@ public class TestServiceDBStore {
 		Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(
 				rangerService);
 
-		//Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao);
-		//Mockito.when(xServiceVersionInfoDao.findByServiceId(Id)).thenReturn(xServiceVersionInfo);
-		//Mockito.when(xServiceVersionInfoDao.update(xServiceVersionInfo)).thenReturn(xServiceVersionInfo);
-
 		Mockito.when(daoManager.getXXServiceDef()).thenReturn(xServiceDefDao);
 		Mockito.when(xServiceDefDao.findByName(rangerService.getType()))
 				.thenReturn(xServiceDef);
@@ -1902,24 +1819,6 @@ public class TestServiceDBStore {
 		Mockito.when(xPolicyDao.getById(rangerPolicy.getId())).thenReturn(
 				xPolicy);
 
-		Mockito.when(daoManager.getXXPolicyResource()).thenReturn(
-				xPolicyResourceDao);
-		Mockito.when(xPolicyResourceDao.findByPolicyId(rangerPolicy.getId()))
-				.thenReturn(policyResourceList);
-
-		Mockito.when(daoManager.getXXPolicyResourceMap()).thenReturn(
-				xPolicyResourceMapDao);
-		Mockito.when(
-				xPolicyResourceMapDao.findByPolicyResId(policyResourceMap
-						.getId())).thenReturn(policyResourceMapList);
-
-		Mockito.when(daoManager.getXXPolicyItem()).thenReturn(xPolicyItemDao);
-
-		Mockito.when(
-				rangerAuditFields.populateAuditFields(
-						Mockito.isA(XXPolicyItem.class),
-						Mockito.isA(XXPolicy.class))).thenReturn(xPolicyItem);
-
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(
 				xService);
@@ -1927,19 +1826,19 @@ public class TestServiceDBStore {
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(
 				xService);
+		Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao);
+		Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST);
 
-                Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(
-                                xPolicyLabelMapDao);
-                Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId()))
-                                .thenReturn(xxPolicyLabelMapList);
 
 		RangerPolicyResourceSignature signature = Mockito
 				.mock(RangerPolicyResourceSignature.class);
 		Mockito.when(factory.createPolicyResourceSignature(rangerPolicy))
 				.thenReturn(signature);
 		Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true);
+        Mockito.when(policyRefUpdater.cleanupRefTables(rangerPolicy)).thenReturn(true);
+
 
-		RangerPolicy dbRangerPolicy = serviceDBStore.updatePolicy(rangerPolicy);
+        RangerPolicy dbRangerPolicy = serviceDBStore.updatePolicy(rangerPolicy);
 		Assert.assertNotNull(dbRangerPolicy);
 		Assert.assertEquals(dbRangerPolicy, rangerPolicy);
 		Assert.assertEquals(dbRangerPolicy.getId(), rangerPolicy.getId());
@@ -1955,9 +1854,6 @@ public class TestServiceDBStore {
 				rangerPolicy.getIsEnabled());
 		Assert.assertEquals(dbRangerPolicy.getVersion(),
 				rangerPolicy.getVersion());
-
-		Mockito.verify(rangerAuditFields).populateAuditFields(
-				Mockito.isA(XXPolicyItem.class), Mockito.isA(XXPolicy.class));
 	}
 
 	@Test
@@ -1965,24 +1861,7 @@ public class TestServiceDBStore {
 		setup();
 		XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
 		XXService xService = Mockito.mock(XXService.class);
-		//XXServiceVersionInfoDao xServiceVersionInfoDao = Mockito.mock(XXServiceVersionInfoDao.class);
-		//XXServiceVersionInfo xServiceVersionInfo = Mockito.mock(XXServiceVersionInfo.class);
-                XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class);
-		XXPolicyItemDao xPolicyItemDao = Mockito.mock(XXPolicyItemDao.class);
-		XXPolicyItemDataMaskInfoDao xPolicyItemDataMaskInfoDao = Mockito.mock(XXPolicyItemDataMaskInfoDao.class);
-		XXPolicyItemRowFilterInfoDao xPolicyItemRowFilterInfoDao = Mockito.mock(XXPolicyItemRowFilterInfoDao.class);
-		XXPolicyItemConditionDao xPolicyItemConditionDao = Mockito
-				.mock(XXPolicyItemConditionDao.class);
-		XXPolicyItemGroupPermDao xPolicyItemGroupPermDao = Mockito
-				.mock(XXPolicyItemGroupPermDao.class);
-		XXPolicyItemUserPermDao xPolicyItemUserPermDao = Mockito
-				.mock(XXPolicyItemUserPermDao.class);
-		XXPolicyItemAccessDao xPolicyItemAccessDao = Mockito
-				.mock(XXPolicyItemAccessDao.class);
-		XXPolicyResourceDao xPolicyResourceDao = Mockito
-				.mock(XXPolicyResourceDao.class);
-		XXPolicyResourceMapDao xPolicyResourceMapDao = Mockito
-				.mock(XXPolicyResourceMapDao.class);
+		XXPolicyLabelMapDao xPolicyLabelMapDao = Mockito.mock(XXPolicyLabelMapDao.class);
 
 		RangerService rangerService = rangerService();
 		RangerPolicy rangerPolicy = rangerPolicy();
@@ -2071,7 +1950,6 @@ public class TestServiceDBStore {
 		policyResource.setUpdateTime(new Date());
 		policyResourceList.add(policyResource);
 
-		List<XXPolicyResourceMap> policyResourceMapList = new ArrayList<XXPolicyResourceMap>();
 		XXPolicyResourceMap policyResourceMap = new XXPolicyResourceMap();
 		policyResourceMap.setAddedByUserId(Id);
 		policyResourceMap.setCreateTime(new Date());
@@ -2081,8 +1959,6 @@ public class TestServiceDBStore {
 		policyResourceMap.setUpdatedByUserId(Id);
 		policyResourceMap.setUpdateTime(new Date());
 		policyResourceMap.setValue("1L");
-		policyResourceMapList.add(policyResourceMap);
-                List<XXPolicyLabelMap> xxPolicyLabelMapList = new ArrayList<>();
 		List<XXServiceConfigDef> xServiceConfigDefList = new ArrayList<XXServiceConfigDef>();
 		XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef();
 		serviceConfigDefObj.setId(Id);
@@ -2096,68 +1972,17 @@ public class TestServiceDBStore {
 		Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(
 				rangerService);
 
-		Mockito.when(daoManager.getXXPolicyItem()).thenReturn(xPolicyItemDao);
-		Mockito.when(xPolicyItemDao.findByPolicyId(policyItem.getId()))
-				.thenReturn(policyItemList);
-
-		Mockito.when(daoManager.getXXPolicyItemDataMaskInfo()).thenReturn(xPolicyItemDataMaskInfoDao);
-
-		Mockito.when(daoManager.getXXPolicyItemRowFilterInfo()).thenReturn(xPolicyItemRowFilterInfoDao);
-
-		Mockito.when(daoManager.getXXPolicyItemCondition()).thenReturn(
-				xPolicyItemConditionDao);
-		Mockito.when(
-				xPolicyItemConditionDao.findByPolicyItemId(policyItemCondition
-						.getId())).thenReturn(policyItemConditionList);
-
-		Mockito.when(daoManager.getXXPolicyItemGroupPerm()).thenReturn(
-				xPolicyItemGroupPermDao);
-		Mockito.when(
-				xPolicyItemGroupPermDao.findByPolicyItemId(policyItem.getId()))
-				.thenReturn(policyItemGroupPermList);
-
-		Mockito.when(daoManager.getXXPolicyItemUserPerm()).thenReturn(
-				xPolicyItemUserPermDao);
-		Mockito.when(xPolicyItemUserPermDao.findByPolicyItemId(Id)).thenReturn(
-				policyItemUserPermList);
-
-		Mockito.when(daoManager.getXXPolicyItemAccess()).thenReturn(
-				xPolicyItemAccessDao);
-		Mockito.when(
-				xPolicyItemAccessDao.findByPolicyItemId(policyItemAccess
-						.getId())).thenReturn(policyItemAccessList);
-
-		Mockito.when(daoManager.getXXPolicyResource()).thenReturn(
-				xPolicyResourceDao);
-		Mockito.when(xPolicyResourceDao.findByPolicyId(policyResource.getId()))
-				.thenReturn(policyResourceList);
-
-		Mockito.when(daoManager.getXXPolicyResourceMap()).thenReturn(
-				xPolicyResourceMapDao);
-		Mockito.when(
-				xPolicyResourceMapDao.findByPolicyResId(policyResourceMap
-						.getId())).thenReturn(policyResourceMapList);
-
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.getById(Id)).thenReturn(xService);
 
-		//Mockito.when(daoManager.getXXServiceVersionInfo()).thenReturn(xServiceVersionInfoDao);
-		//Mockito.when(xServiceVersionInfoDao.findByServiceId(Id)).thenReturn(xServiceVersionInfo);
-		//Mockito.when(xServiceVersionInfoDao.update(xServiceVersionInfo)).thenReturn(xServiceVersionInfo);
-
 		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
 		Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(
 				xService);
+		Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(xPolicyLabelMapDao);
+		Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId())).thenReturn(ListUtils.EMPTY_LIST);
 
 		Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true);
-
-                Mockito.when(daoManager.getXXPolicyLabelMap()).thenReturn(
-                                xPolicyLabelMapDao);
-                Mockito.when(xPolicyLabelMapDao.findByPolicyId(rangerPolicy.getId()))
-                                .thenReturn(xxPolicyLabelMapList);
-		//RangerTransactionSynchronizationAdapter spy = Mockito.spy(transactionSynchronizationAdapter);
-		//Mockito.doNothing().when(spy).executeOnTransactionCommit(Mockito.any(Runnable.class));
-
+        Mockito.when(policyRefUpdater.cleanupRefTables(rangerPolicy)).thenReturn(true);
 
 		serviceDBStore.deletePolicy(Id);
 	}
@@ -2493,4 +2318,98 @@ public class TestServiceDBStore {
     	Mockito.verify(daoManager).getXXServiceConfigMap();
     	Mockito.verify(xxServiceConfigMapDao).findByServiceNameAndConfigKey(rService.getName(), configName);
     }
+	
+	@Test
+	public void test41createKMSService() throws Exception {
+		XXServiceDao xServiceDao = Mockito.mock(XXServiceDao.class);
+		XXServiceConfigMapDao xServiceConfigMapDao = Mockito
+				.mock(XXServiceConfigMapDao.class);
+		XXUserDao xUserDao = Mockito.mock(XXUserDao.class);
+		XXServiceConfigDefDao xServiceConfigDefDao = Mockito
+				.mock(XXServiceConfigDefDao.class);
+		XXService xService = Mockito.mock(XXService.class);
+		XXUser xUser = Mockito.mock(XXUser.class);
+
+		Mockito.when(xServiceDao.findByName("KMS_1")).thenReturn(
+				xService);
+		Mockito.when(!bizUtil.hasAccess(xService, null)).thenReturn(true);
+
+		RangerService rangerService = rangerKMSService();
+		VXUser vXUser = null;
+		String userName = "servicemgr";
+
+		List<XXServiceConfigDef> svcConfDefList = new ArrayList<XXServiceConfigDef>();
+		XXServiceConfigDef serviceConfigDefObj = new XXServiceConfigDef();
+		serviceConfigDefObj.setId(Id);
+		serviceConfigDefObj.setType("7");
+		svcConfDefList.add(serviceConfigDefObj);
+		Mockito.when(daoManager.getXXServiceConfigDef()).thenReturn(
+				xServiceConfigDefDao);
+
+		Mockito.when(svcService.create(rangerService)).thenReturn(rangerService);
+
+		Mockito.when(daoManager.getXXService()).thenReturn(xServiceDao);
+		Mockito.when(xServiceDao.getById(rangerService.getId())).thenReturn(
+				xService);
+		Mockito.when(daoManager.getXXServiceConfigMap()).thenReturn(
+				xServiceConfigMapDao);
+
+		Mockito.when(stringUtil.getValidUserName(userName))
+		.thenReturn(userName);
+		Mockito.when(daoManager.getXXUser()).thenReturn(xUserDao);
+		Mockito.when(xUserDao.findByUserName(userName)).thenReturn(xUser);
+
+		Mockito.when(xUserService.populateViewBean(xUser)).thenReturn(vXUser);
+		VXUser vXUserHdfs = new VXUser();
+		vXUserHdfs.setName("hdfs");
+		vXUserHdfs.setPassword("hdfs");
+		VXUser vXUserHive = new VXUser();
+		vXUserHive.setName("hive");
+		vXUserHive.setPassword("hive");
+
+		XXServiceConfigMap xConfMap = new XXServiceConfigMap();
+
+		Mockito.when(svcService.getPopulatedViewObject(xService)).thenReturn(
+				rangerService);
+
+		Mockito.when(
+				rangerAuditFields.populateAuditFields(
+						Mockito.isA(XXServiceConfigMap.class),
+						Mockito.isA(XXService.class))).thenReturn(xConfMap);
+
+		List<XXAccessTypeDef> accessTypeDefList = new ArrayList<XXAccessTypeDef>();
+		accessTypeDefList.add(rangerKmsAccessTypes("getmetadata", 7));
+		accessTypeDefList.add(rangerKmsAccessTypes("generateeek", 8));
+		accessTypeDefList.add(rangerKmsAccessTypes("decrypteek", 9));
+
+		RangerServiceDef ran = new RangerServiceDef();
+		ran.setName("KMS Test");
+
+		ServiceDBStore spy = Mockito.spy(serviceDBStore);
+
+		Mockito.when(spy.getServiceByName("KMS_1")).thenReturn(
+				rangerService);
+		Mockito.doNothing().when(spy).createDefaultPolicies(rangerService);
+
+		RangerResourceDef resourceDef = new RangerResourceDef();
+		resourceDef.setItemId(Id);
+		resourceDef.setName("keyname");
+		resourceDef.setType("string");
+		resourceDef.setType("string");
+		resourceDef.setLabel("Key Name");
+		resourceDef.setDescription("Key Name");
+
+		List<RangerResourceDef> resourceHierarchy = new ArrayList<RangerResourceDef>();
+		resourceHierarchy.addAll(resourceHierarchy);
+
+		spy.createService(rangerService);
+		vXUser = new VXUser();
+		vXUser.setName(userName);
+		vXUser.setPassword(userName);
+		
+		spy.createDefaultPolicies(rangerService);
+
+		Mockito.verify(daoManager, Mockito.atLeast(1)).getXXService();
+		Mockito.verify(daoManager).getXXServiceConfigMap();
+	}
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
----------------------------------------------------------------------
diff --git a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
index 15344ea..a8e6e61 100644
--- a/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
+++ b/security-admin/src/test/java/org/apache/ranger/rest/TestServiceREST.java
@@ -281,7 +281,7 @@ public class TestServiceREST {
 		return rangerService;
 	}
 
-	public RangerPolicy rangerPolicy() {
+	RangerPolicy rangerPolicy() {
 		List<RangerPolicyItemAccess> accesses = new ArrayList<RangerPolicyItemAccess>();
 		List<String> users = new ArrayList<String>();
 		List<String> groups = new ArrayList<String>();


[4/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java
new file mode 100644
index 0000000..2c04ab4
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefConditionDao.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.db;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.biz.RangerPolicyRetriever;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.XXPolicyRefCondition;
+import org.springframework.stereotype.Service;
+
+@Service
+public class XXPolicyRefConditionDao extends BaseDao<XXPolicyRefCondition>  {
+
+	public XXPolicyRefConditionDao(RangerDaoManagerBase daoManager) {
+		super(daoManager);
+	}
+
+	public List<XXPolicyRefCondition> findByPolicyId(Long polId) {
+		if(polId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager()
+					.createNamedQuery("XXPolicyRefCondition.findByPolicyId", tClass)
+					.setParameter("policyId", polId).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+	public List<XXPolicyRefCondition> findByConditionName(String conditionName) {
+		if (conditionName == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager().createNamedQuery("XXPolicyRefCondition.findByConditionName", tClass)
+					.setParameter("conditionName", conditionName).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	public List<XXPolicyRefCondition> findByConditionDefId(Long conditionDefId) {
+		if (conditionDefId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager().createNamedQuery("XXPolicyRefCondition.findByConditionDefId", tClass)
+					.setParameter("conditionDefId", conditionDefId)
+					.getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	@SuppressWarnings("unchecked")
+    public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedConditionNamesByPolicy(Long policyId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (policyId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefCondition.findUpdatedConditionNamesByPolicy")
+                    .setParameter("policy", policyId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+	@SuppressWarnings("unchecked")
+	public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedConditionNamesByService(Long serviceId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (serviceId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefCondition.findUpdatedConditionNamesByService")
+                    .setParameter("service", serviceId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java
new file mode 100644
index 0000000..258e3b0
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefDataMaskTypeDao.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.db;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.biz.RangerPolicyRetriever;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.XXPolicyRefDataMaskType;
+import org.springframework.stereotype.Service;
+
+@Service
+public class XXPolicyRefDataMaskTypeDao extends BaseDao<XXPolicyRefDataMaskType>{
+
+	public XXPolicyRefDataMaskTypeDao(RangerDaoManagerBase daoManager)  {
+		super(daoManager);
+	}
+
+	public List<XXPolicyRefDataMaskType> findByPolicyId(Long policyId) {
+		if(policyId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager()
+					.createNamedQuery("XXPolicyRefDataMaskType.findByPolicyId", tClass)
+					.setParameter("policyId", policyId).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	@SuppressWarnings("unchecked")
+    public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedDataMaskNamesByPolicy(Long policyId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (policyId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByPolicy")
+                    .setParameter("policy", policyId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+	@SuppressWarnings("unchecked")
+	public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedDataMaskNamesByService(Long serviceId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (serviceId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefDataMaskType.findUpdatedDataMaskNamesByService")
+                    .setParameter("service", serviceId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java
new file mode 100644
index 0000000..08829d4
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefGroupDao.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.db;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.biz.RangerPolicyRetriever;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.XXPolicyRefGroup;
+import org.springframework.stereotype.Service;
+
+@Service
+public class XXPolicyRefGroupDao extends BaseDao<XXPolicyRefGroup>{
+
+
+	public XXPolicyRefGroupDao(RangerDaoManagerBase daoManager)  {
+		super(daoManager);
+	}
+
+	public List<XXPolicyRefGroup> findByPolicyId(Long policyId) {
+		if(policyId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager()
+					.createNamedQuery("XXPolicyRefGroup.findByPolicyId", tClass)
+					.setParameter("policyId", policyId).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+	public List<XXPolicyRefGroup> findByGroupName(String groupName) {
+		if (groupName == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager().createNamedQuery("XXPolicyRefGroup.findByGroupName", tClass)
+					.setParameter("groupName", groupName).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+    @SuppressWarnings("unchecked")
+    public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedGroupNamesByPolicy(Long policyId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (policyId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefGroup.findUpdatedGroupNamesByPolicy")
+                    .setParameter("policy", policyId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+	@SuppressWarnings("unchecked")
+	public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedGroupNamesByService(Long serviceId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (serviceId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefGroup.findUpdatedGroupNamesByService")
+                    .setParameter("service", serviceId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java
new file mode 100644
index 0000000..e259ee8
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefResourceDao.java
@@ -0,0 +1,98 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.db;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.biz.RangerPolicyRetriever;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.XXPolicyRefResource;
+import org.springframework.stereotype.Service;
+
+@Service
+public class XXPolicyRefResourceDao extends BaseDao<XXPolicyRefResource>{
+
+	public XXPolicyRefResourceDao(RangerDaoManagerBase daoManager)  {
+		super(daoManager);
+	}
+
+	public List<XXPolicyRefResource> findByPolicyId(Long policyId) {
+		if(policyId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager()
+					.createNamedQuery("XXPolicyRefResource.findByPolicyId", tClass)
+					.setParameter("policyId", policyId).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	public List<XXPolicyRefResource> findByResourceDefID(Long resourceDefId) {
+		if (resourceDefId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager().createNamedQuery("XXPolicyRefResource.findByResourceDefId", tClass)
+					.setParameter("resourceDefId", resourceDefId).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	 @SuppressWarnings("unchecked")
+	    public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedResourceNamesByPolicy(Long policyId) {
+	        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+	        if (policyId != null) {
+	            List<Object[]> rows = (List<Object[]>) getEntityManager()
+	                    .createNamedQuery("XXPolicyRefResource.findUpdatedResourceNamesByPolicy")
+	                    .setParameter("policy", policyId)
+	                    .getResultList();
+	            if (rows != null) {
+	                for (Object[] row : rows) {
+	                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+	                }
+	            }
+	        }
+	        return ret;
+	    }
+
+		@SuppressWarnings("unchecked")
+		public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedResourceNamesByService(Long serviceId) {
+	        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+	        if (serviceId != null) {
+	            List<Object[]> rows = (List<Object[]>) getEntityManager()
+	                    .createNamedQuery("XXPolicyRefResource.findUpdatedResourceNamesByService")
+	                    .setParameter("service", serviceId)
+	                    .getResultList();
+	            if (rows != null) {
+	                for (Object[] row : rows) {
+	                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+	                }
+	            }
+	        }
+	        return ret;
+	    }
+}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java
new file mode 100644
index 0000000..f7b6131
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefUserDao.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.db;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.biz.RangerPolicyRetriever;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.XXPolicyRefUser;
+import org.springframework.stereotype.Service;
+
+@Service
+public class XXPolicyRefUserDao extends BaseDao<XXPolicyRefUser>{
+
+
+	public XXPolicyRefUserDao(RangerDaoManagerBase daoManager)  {
+		super(daoManager);
+	}
+
+	public List<XXPolicyRefUser> findByPolicyId(Long policyId) {
+		if(policyId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager()
+					.createNamedQuery("XXPolicyRefUser.findByPolicyId", tClass)
+					.setParameter("policyId", policyId).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+	public List<XXPolicyRefUser> findByUserName(String userName) {
+		if (userName == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager().createNamedQuery("XXPolicyRefUser.findByUserName", tClass)
+					.setParameter("userName", userName).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	public List<XXPolicyRefUser> findByUserId(String userID) {
+		if (userID == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager().createNamedQuery("XXPolicyRefUser.findByUserId", tClass)
+					.setParameter("userID", userID).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	@SuppressWarnings("unchecked")
+    public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedUserNamesByPolicy(Long policyId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (policyId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefUser.findUpdatedUserNamesByPolicy")
+                    .setParameter("policy", policyId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+	@SuppressWarnings("unchecked")
+	public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedUserNamesByService(Long serviceId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (serviceId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefUser.findUpdatedUserNamesByService")
+                    .setParameter("service", serviceId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java
index a7157de..6670a4e 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceDao.java
@@ -32,20 +32,6 @@ public class XXPolicyResourceDao extends BaseDao<XXPolicyResource> {
 	public XXPolicyResourceDao(RangerDaoManagerBase daoManager) {
 		super(daoManager);
 	}
-	
-	public XXPolicyResource findByResDefIdAndPolicyId(Long resDefId, Long polId) {
-		if(resDefId == null || polId == null) {
-			return null;
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyResource.findByResDefIdAndPolicyId", tClass)
-					.setParameter("resDefId", resDefId).setParameter("polId", polId)
-					.getSingleResult();
-		} catch (NoResultException e) {
-			return null;
-		}
-	}
 
 	public List<XXPolicyResource> findByPolicyId(Long policyId) {
 		if(policyId == null) {

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java
index 55d8c50..90123f5 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyResourceMapDao.java
@@ -32,19 +32,6 @@ public class XXPolicyResourceMapDao extends BaseDao<XXPolicyResourceMap> {
 	public XXPolicyResourceMapDao(RangerDaoManagerBase daoManager) {
 		super(daoManager);
 	}
-	
-	public List<XXPolicyResourceMap> findByPolicyResId(Long polResId) {
-		if(polResId == null) {
-			return new ArrayList<XXPolicyResourceMap>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyResourceMap.findByPolicyResId", tClass)
-					.setParameter("polResId", polResId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyResourceMap>();
-		}
-	}
 
 	public List<XXPolicyResourceMap> findByPolicyId(Long policyId) {
 		if(policyId == null) {

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java
index b2e311f..5613902 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXResourceDefDao.java
@@ -99,5 +99,4 @@ public class XXResourceDefDao extends BaseDao<XXResourceDef> {
 			return new ArrayList<XXResourceDef>();
 		}
 	}
-
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java
index ee0e400..5c0878c 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceDao.java
@@ -24,6 +24,7 @@ import java.util.List;
 
 import javax.persistence.NoResultException;
 
+import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.ranger.authorization.utils.StringUtil;
 import org.apache.ranger.common.db.BaseDao;
@@ -75,15 +76,32 @@ public class XXServiceResourceDao extends BaseDao<XXServiceResource> {
 	}
 
 	public List<XXServiceResource> findTaggedResourcesInServiceId(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXServiceResource>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXServiceResource.findTaggedResourcesInServiceId", tClass)
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXServiceResource>();
-		}
+	    List<XXServiceResource> ret = new ArrayList<>();
+		if (serviceId != null) {
+            List<Object[]> rows = null;
+            try {
+                rows = getEntityManager().createNamedQuery("XXServiceResource.findTaggedResourcesInServiceId", Object[].class)
+                        .setParameter("serviceId", serviceId).getResultList();
+            } catch (NoResultException e) {
+                // Nothing
+            }
+            if (CollectionUtils.isNotEmpty(rows)) {
+                for (Object[] row : rows) {
+                    XXServiceResource xxServiceResource = new XXServiceResource();
+                    xxServiceResource.setId((Long) row[0]);
+                    xxServiceResource.setGuid((String) row[1]);
+                    xxServiceResource.setVersion((Long) row[2]);
+                    xxServiceResource.setIsEnabled((Boolean) row[3]);
+                    xxServiceResource.setResourceSignature((String) row[4]);
+                    xxServiceResource.setServiceId((Long) row[5]);
+                    xxServiceResource.setServiceResourceElements((String) row[6]);
+                    xxServiceResource.setTags((String) row[7]);
+
+                    ret.add(xxServiceResource);
+                }
+            }
+        }
+        return ret;
 	}
 
 	public long countTaggedResourcesInServiceId(Long serviceId) {

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java
index c9a1c21..ece8c2e 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementDao.java
@@ -74,16 +74,4 @@ public class XXServiceResourceElementDao extends BaseDao<XXServiceResourceElemen
 		}
 	}
 
-	public List<XXServiceResourceElement> findForServicePlugin(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXServiceResourceElement>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXServiceResourceElement.findForServicePlugin", tClass)
-					.setParameter("serviceId", serviceId)
-					.getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXServiceResourceElement>();
-		}
-	}
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java
index 364af6d..1d6a1ea 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXServiceResourceElementValueDao.java
@@ -87,19 +87,6 @@ public class XXServiceResourceElementValueDao extends BaseDao<XXServiceResourceE
 	}
 
 	@SuppressWarnings("unchecked")
-	public List<XXServiceResourceElementValue> findForServicePlugin(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXServiceResourceElementValue>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXServiceResourceElementValue.findForServicePlugin")
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXServiceResourceElementValue>();
-		}
-	}
-
-	@SuppressWarnings("unchecked")
 	public List<XXServiceResourceElementValue> findByResourceId(Long resourceId) {
 		if (resourceId == null) {
 			return new ArrayList<XXServiceResourceElementValue>();

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java
index 40c3a88..474ef28 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDao.java
@@ -59,18 +59,6 @@ public class XXTagAttributeDao extends BaseDao<XXTagAttribute> {
 		}
 	}
 
-	public List<XXTagAttribute> findForServicePlugin(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXTagAttribute>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXTagAttribute.findForServicePlugin", tClass)
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXTagAttribute>();
-		}
-	}
-
 	public List<XXTagAttribute> findByServiceIdAndOwner(Long serviceId, Short owner) {
 		if (serviceId == null) {
 			return new ArrayList<XXTagAttribute>();

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java
index 129f3c1..3a9cf2c 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagAttributeDefDao.java
@@ -59,18 +59,6 @@ public class XXTagAttributeDefDao extends BaseDao<XXTagAttributeDef> {
 		}
 	}
 
-	public List<XXTagAttributeDef> findForServicePlugin(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXTagAttributeDef>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXTagAttributeDef.findForServicePlugin", tClass)
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXTagAttributeDef>();
-		}
-	}
-
 	public List<XXTagAttributeDef> findByResourceId(Long resourceId) {
 		if (resourceId == null) {
 			return new ArrayList<XXTagAttributeDef>();

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java
index e14f836..c3aed9d 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagDao.java
@@ -126,19 +126,6 @@ public class XXTagDao extends BaseDao<XXTag> {
 		}
 	}
 
-	public List<XXTag> findForServicePlugin(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXTag>();
-		}
-
-		try {
-			return getEntityManager().createNamedQuery("XXTag.findForServicePlugin", tClass)
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXTag>();
-		}
-	}
-
 	public List<XXTag> findByServiceIdAndOwner(Long serviceId, Short owner) {
 		if (serviceId == null) {
 			return new ArrayList<XXTag>();

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java
index c0dd883..f6c0bbf 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagDefDao.java
@@ -24,6 +24,7 @@ import java.util.List;
 
 import javax.persistence.NoResultException;
 
+import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.ranger.common.db.BaseDao;
 import org.apache.ranger.entity.XXTagDef;
@@ -62,31 +63,33 @@ public class XXTagDefDao extends BaseDao<XXTagDef> {
 		}
 	}
 
-	public List<XXTagDef> findByServiceId(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXTagDef>();
-		}
-
-		try {
-			return getEntityManager().createNamedQuery("XXTagDef.findByServiceId", tClass)
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXTagDef>();
-		}
-	}
-
-	public List<XXTagDef> findForServicePlugin(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXTagDef>();
-		}
-
-		try {
-			return getEntityManager().createNamedQuery("XXTagDef.findForServicePlugin", tClass)
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXTagDef>();
-		}
-	}
+    public List<XXTagDef> findByServiceId(Long serviceId) {
+        List<XXTagDef> ret = new ArrayList<>();
+        if (serviceId != null) {
+            List<Object[]> rows = null;
+            try {
+                rows = getEntityManager().createNamedQuery("XXTagDef.findByServiceId", Object[].class)
+                        .setParameter("serviceId", serviceId).getResultList();
+            } catch (NoResultException e) {
+                // Nothing
+            }
+            if (CollectionUtils.isNotEmpty(rows)) {
+                for (Object[] row : rows) {
+                    XXTagDef xxTagDef = new XXTagDef();
+                    xxTagDef.setId((Long) row[0]);
+                    xxTagDef.setGuid((String) row[1]);
+                    xxTagDef.setVersion((Long) row[2]);
+                    xxTagDef.setIsEnabled((Boolean) row[3]);
+                    xxTagDef.setName((String) row[4]);
+                    xxTagDef.setSource((String) row[5]);
+                    xxTagDef.setTagAttrDefs((String) row[6]);
+
+                    ret.add(xxTagDef);
+                }
+            }
+        }
+        return ret;
+    }
 
 	public List<String> getAllNames() {
 		try {

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java
index f9e041a..3f8b5b7 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXTagResourceMapDao.java
@@ -143,15 +143,4 @@ public class XXTagResourceMapDao extends BaseDao<XXTagResourceMap> {
 		}
 	}
 
-	public List<XXTagResourceMap> findForServicePlugin(Long serviceId) {
-		if (serviceId == null) {
-			return new ArrayList<XXTagResourceMap>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXTagResourceMap.findForServicePlugin", tClass)
-					.setParameter("serviceId", serviceId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXTagResourceMap>();
-		}
-	}
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java
index 58bf4d8..cea90c1 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXUserDao.java
@@ -17,10 +17,7 @@
  * under the License.
  */
 
- package org.apache.ranger.db;
-
-
-import java.util.List;
+package org.apache.ranger.db;
 
 import javax.persistence.NoResultException;
 
@@ -53,20 +50,6 @@ public class XXUserDao extends BaseDao<XXUser> {
 		return null;
 	}
 
-	@SuppressWarnings("unchecked")
-	public List<String> findByPolicyItemId(Long polItemId) {
-		if (polItemId == null) {
-			return null;
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXUser.findByPolicyItemId")
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return null;
-		}
-	}
-
 	public XXUser findByPortalUserId(Long portalUserId) {
 		if (portalUserId == null) {
 			return null;
@@ -78,4 +61,5 @@ public class XXUserDao extends BaseDao<XXUser> {
 			return null;
 		}
 	}
+
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java
index 8405eb3..4816b02 100644
--- a/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXDBBase.java
@@ -25,6 +25,7 @@
  */
 
 import java.util.Date;
+import java.util.Objects;
 
 import javax.persistence.Column;
 import javax.persistence.EntityListeners;
@@ -205,6 +206,11 @@ public abstract class XXDBBase implements java.io.Serializable {
 		return str;
 	}
 
+	@Override
+	public int hashCode() {
+		return Objects.hash(createTime, updateTime, addedByUserId, updatedByUserId);
+	}
+
 	/**
 	 * Checks for all attributes except referenced db objects
 	 * @return true if all attributes match

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java
index 584a103..e441ec0 100644
--- a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyBase.java
@@ -126,6 +126,10 @@ public abstract class XXPolicyBase extends XXDBBase {
      */
     @Column(name = "policy_options")
     protected String options;
+
+    	@Column(name = "policy_text")
+    	protected String policyText;
+
 	/**
 	 * @return the gUID
 	 */
@@ -310,7 +314,16 @@ public abstract class XXPolicyBase extends XXDBBase {
         return this.options;
     }
 
-	/*
+
+    	public void setPolicyText(String policyText) {
+        	this.policyText = policyText;
+    	}
+
+    	public String getPolicyText() {
+        	return this.policyText;
+    	}
+
+    /*
 	 * (non-Javadoc)
 	 *
 	 * @see java.lang.Object#equals(java.lang.Object)
@@ -399,6 +412,13 @@ public abstract class XXPolicyBase extends XXDBBase {
 		} else if (!options.equals(other.options)) {
 			return false;
 		}
+        if (policyText == null) {
+            if (other.policyText != null) {
+                return false;
+            }
+        } else if (!policyText.equals(other.policyText)) {
+            return false;
+        }
 
 		return true;
 	}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java
new file mode 100644
index 0000000..6af8f99
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefAccessType.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ranger.entity;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.util.Objects;
+
+@Entity
+@Cacheable
+@XmlRootElement
+@Table(name = "x_policy_ref_access_type")
+public class XXPolicyRefAccessType extends XXDBBase implements
+		java.io.Serializable {
+	private static final long serialVersionUID = 1L;
+	/**
+	 * id of the XXPolicyRefAccessType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Id
+	@SequenceGenerator(name = "x_policy_ref_access_type_SEQ", sequenceName = "x_policy_ref_access_type_SEQ", allocationSize = 1)
+	@GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_access_type_SEQ")
+	@Column(name = "id")
+	protected Long id;
+
+	/**
+	 * policyId of the XXPolicyRefAccessType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "policy_id")
+	protected Long policyId;
+
+	/**
+	 * accessDefId of the XXPolicyRefAccessType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "access_def_id")
+	protected Long accessDefId;
+
+	/**
+	 * accessTypeName of the XXPolicyRefAccessType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "access_type_name")
+	protected String accessTypeName;
+
+	/**
+	 * This method sets the value to the member attribute <b> id</b> . You
+	 * cannot set null to the attribute.
+	 *
+	 * @param id
+	 *            Value to set member attribute <b> id</b>
+	 */
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>id</b>
+	 *
+	 * @return Date - value of member attribute <b>id</b> .
+	 */
+	public Long getId() {
+		return this.id;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> policyId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param policyId
+	 *            Value to set member attribute <b> policyId</b>
+	 */
+	public void setPolicyId(Long policyId) {
+		this.policyId = policyId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>policyId</b>
+	 *
+	 * @return Date - value of member attribute <b>policyId</b> .
+	 */
+	public Long getPolicyId() {
+		return this.policyId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> accessDefId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param accessDefId
+	 *            Value to set member attribute <b> accessDefId</b>
+	 */
+	public void setAccessDefId(Long accessDefId) {
+		this.accessDefId = accessDefId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>accessDefId</b>
+	 *
+	 * @return Date - value of member attribute <b>accessDefId</b> .
+	 */
+	public Long getAccessDefId() {
+		return accessDefId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> accessTypeName</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param accessTypeName
+	 *            Value to set member attribute <b> accessTypeName</b>
+	 */
+	public void setAccessTypeName(String accessTypeName) {
+		this.accessTypeName = accessTypeName;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>accessTypeName</b>
+	 *
+	 * @return Date - value of member attribute <b>accessTypeName</b> .
+	 */
+	public String getAccessTypeName() {
+		return accessTypeName;
+	}
+
+	@Override
+	public int hashCode() {
+		return Objects.hash(super.hashCode(), id, policyId, accessDefId, accessTypeName);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see java.lang.Object#equals(java.lang.Object)
+	 */
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj) {
+			return true;
+		}
+
+		if (getClass() != obj.getClass()) {
+			return false;
+		}
+
+		XXPolicyRefAccessType other = (XXPolicyRefAccessType) obj;
+
+		return super.equals(obj) &&
+			   Objects.equals(id, other.id) &&
+			   Objects.equals(policyId, other.policyId) &&
+			   Objects.equals(accessDefId, other.accessDefId) &&
+			   Objects.equals(accessTypeName, other.accessTypeName);
+	}
+
+	/* (non-Javadoc)
+	 * @see java.lang.Object#toString()
+	 */
+	@Override
+	public String toString() {
+		return "XXPolicyRefAccessType [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", accessDefId="
+				+ accessDefId + ", accessTypeName=" + accessTypeName +  "]";
+	}
+
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java
new file mode 100644
index 0000000..4f4409d
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefCondition.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ranger.entity;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.util.Objects;
+
+@Entity
+@Cacheable
+@XmlRootElement
+@Table(name = "x_policy_ref_condition")
+public class XXPolicyRefCondition extends XXDBBase implements
+		java.io.Serializable {
+	private static final long serialVersionUID = 1L;
+	/**
+	 * id of the XXPolicyRefCondition
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Id
+	@SequenceGenerator(name = "x_policy_ref_condition_SEQ", sequenceName = "x_policy_ref_condition_SEQ", allocationSize = 1)
+	@GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_condition_SEQ")
+	@Column(name = "id")
+	protected Long id;
+
+	/**
+	 * policyId of the XXPolicyRefCondition
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "policy_id")
+	protected Long policyId;
+
+	/**
+	 * conditionDefId of the XXPolicyRefCondition
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "condition_def_id")
+	protected Long conditionDefId;
+
+	/**
+	 * conditionName of the XXPolicyRefCondition
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "condition_name")
+	protected String conditionName;
+
+	/**
+	 * This method sets the value to the member attribute <b> id</b> . You
+	 * cannot set null to the attribute.
+	 *
+	 * @param id
+	 *            Value to set member attribute <b> id</b>
+	 */
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>id</b>
+	 *
+	 * @return Date - value of member attribute <b>id</b> .
+	 */
+	public Long getId() {
+		return this.id;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> policyId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param policyId
+	 *            Value to set member attribute <b> policyId</b>
+	 */
+	public void setPolicyId(Long policyId) {
+		this.policyId = policyId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>policyId</b>
+	 *
+	 * @return Date - value of member attribute <b>policyId</b> .
+	 */
+	public Long getPolicyId() {
+		return this.policyId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> conditionDefId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param conditionDefId
+	 *            Value to set member attribute <b> conditionDefId</b>
+	 */
+	public void setConditionDefId(Long conditionDefId) {
+		this.conditionDefId = conditionDefId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>conditionDefId</b>
+	 *
+	 * @return Date - value of member attribute <b>conditionDefId</b> .
+	 */
+	public Long getConditionDefId() {
+		return conditionDefId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> conditionName</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param conditionName
+	 *            Value to set member attribute <b> conditionName</b>
+	 */
+	public void setConditionName(String conditionName) {
+		this.conditionName = conditionName;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>conditionName</b>
+	 *
+	 * @return Date - value of member attribute <b>conditionName</b> .
+	 */
+	public String getConditionName() {
+		return conditionName;
+	}
+
+	@Override
+	public int hashCode() {
+		return Objects.hash(super.hashCode(), id, policyId, conditionDefId, conditionName);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see java.lang.Object#equals(java.lang.Object)
+	 */
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj) {
+			return true;
+		}
+
+		if (getClass() != obj.getClass()) {
+			return false;
+		}
+
+		XXPolicyRefCondition other = (XXPolicyRefCondition) obj;
+
+		return super.equals(obj) &&
+			   Objects.equals(id, other.id) &&
+			   Objects.equals(policyId, other.policyId) &&
+			   Objects.equals(conditionDefId, other.conditionDefId) &&
+			   Objects.equals(conditionName, other.conditionName);
+	}
+
+	/* (non-Javadoc)
+	 * @see java.lang.Object#toString()
+	 */
+	@Override
+	public String toString() {
+		return "XXPolicyRefCondition [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", conditionDefId="
+				+ conditionDefId + ", conditionName=" + conditionName + "]";
+	}
+
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java
new file mode 100644
index 0000000..cb92674
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefDataMaskType.java
@@ -0,0 +1,192 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ranger.entity;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.util.Objects;
+
+@Entity
+@Cacheable
+@XmlRootElement
+@Table(name = "x_policy_ref_datamask_type")
+public class XXPolicyRefDataMaskType extends XXDBBase implements
+		java.io.Serializable {
+	private static final long serialVersionUID = 1L;
+	/**
+	 * id of the XXPolicyRefDataMaskType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Id
+	@SequenceGenerator(name = "x_policy_ref_datamask_type_SEQ", sequenceName = "x_policy_ref_datamask_type_SEQ", allocationSize = 1)
+	@GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_datamask_type_SEQ")
+	@Column(name = "id")
+	protected Long id;
+
+	/**
+	 * policyId of the XXPolicyRefDataMaskType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "policy_id")
+	protected Long policyId;
+
+	/**
+	 * DatamaskDefId of the XXPolicyRefDataMaskType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "datamask_def_id")
+	protected Long dataMaskDefId;
+
+	/**
+	 * dataMaskTypeName of the XXPolicyRefDataMaskType
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "datamask_type_name")
+	protected String dataMaskTypeName;
+
+	/**
+	 * This method sets the value to the member attribute <b> id</b> . You
+	 * cannot set null to the attribute.
+	 *
+	 * @param id
+	 *            Value to set member attribute <b> id</b>
+	 */
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>id</b>
+	 *
+	 * @return Date - value of member attribute <b>id</b> .
+	 */
+	public Long getId() {
+		return this.id;
+	}
+
+
+	/**
+	 * This method sets the value to the member attribute <b> policyId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param policyId
+	 *            Value to set member attribute <b> policyId</b>
+	 */
+	public void setPolicyId(Long policyId) {
+		this.policyId = policyId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>policyId</b>
+	 *
+	 * @return Date - value of member attribute <b>policyId</b> .
+	 */
+	public Long getPolicyId() {
+		return this.policyId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> dataMaskDefId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param dataMaskDefId
+	 *            Value to set member attribute <b> dataMaskDefId</b>
+	 */
+	public void setDataMaskDefId(Long dataMaskDefId) {
+		this.dataMaskDefId = dataMaskDefId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>dataMaskDefId</b>
+	 *
+	 * @return Date - value of member attribute <b>dataMaskDefId</b> .
+	 */
+	public Long getDataMaskDefId() {
+		return dataMaskDefId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> dataMaskTypeName</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param dataMaskTypeName
+	 *            Value to set member attribute <b> dataMaskTypeName</b>
+	 */
+	public void setDataMaskTypeName(String dataMaskTypeName) {
+		this.dataMaskTypeName = dataMaskTypeName;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>dataMaskTypeName</b>
+	 *
+	 * @return Date - value of member attribute <b>dataMaskTypeName</b> .
+	 */
+	public String getDataMaskTypeName() {
+		return dataMaskTypeName;
+	}
+
+	@Override
+	public int hashCode() {
+		return Objects.hash(super.hashCode(), id, policyId, dataMaskDefId, dataMaskTypeName);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see java.lang.Object#equals(java.lang.Object)
+	 */
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj) {
+			return true;
+		}
+
+		if (getClass() != obj.getClass()) {
+			return false;
+		}
+
+		XXPolicyRefDataMaskType other = (XXPolicyRefDataMaskType) obj;
+
+		return super.equals(obj) &&
+			   Objects.equals(id, other.id) &&
+			   Objects.equals(policyId, other.policyId) &&
+			   Objects.equals(dataMaskDefId, other.dataMaskDefId) &&
+			   Objects.equals(dataMaskTypeName, other.dataMaskTypeName);
+	}
+
+	/* (non-Javadoc)
+	 * @see java.lang.Object#toString()
+	 */
+	@Override
+	public String toString() {
+		return "XXPolicyRefDataMaskType [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", dataMaskDefId="
+				+ dataMaskDefId + ", dataMaskTypeName=" + dataMaskTypeName + "]";
+	}
+
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java
new file mode 100644
index 0000000..32a1b9f
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefGroup.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.entity;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+import javax.persistence.Cacheable;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.Table;
+import javax.xml.bind.annotation.XmlRootElement;
+
+
+/**
+ * The persistent class for the x_policy_ref_group database table.
+ * 
+ */
+@Entity
+@Cacheable
+@XmlRootElement
+@Table(name="x_policy_ref_group")
+public class XXPolicyRefGroup extends XXDBBase implements Serializable {
+
+	private static final long serialVersionUID = 1L;
+	/**
+	 * id of the XXPolicyRefGroup
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Id
+	@SequenceGenerator(name = "x_policy_ref_group_SEQ", sequenceName = "x_policy_ref_group_SEQ", allocationSize = 1)
+	@GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_group_SEQ")
+	@Column(name = "id")
+	protected Long id;
+
+	/**
+	 * policyId of the XXPolicyRefGroup
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "policy_id")
+	protected Long policyId;
+
+	/**
+	 * groupId of the XXPolicyRefGroup
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "group_id")
+	protected Long groupId;
+
+	/**
+	 * groupName of the XXPolicyRefGroup
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "group_name")
+	protected String groupName;
+
+	/**
+	 * This method sets the value to the member attribute <b> id</b> . You
+	 * cannot set null to the attribute.
+	 *
+	 * @param id
+	 *            Value to set member attribute <b> id</b>
+	 */
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>id</b>
+	 *
+	 * @return Date - value of member attribute <b>id</b> .
+	 */
+	public Long getId() {
+		return this.id;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> policyId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param policyId
+	 *            Value to set member attribute <b> policyId</b>
+	 */
+	public void setPolicyId(Long policyId) {
+		this.policyId = policyId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>policyId</b>
+	 *
+	 * @return Date - value of member attribute <b>policyId</b> .
+	 */
+	public Long getPolicyId() {
+		return this.policyId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> groupId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param groupId
+	 *            Value to set member attribute <b> groupId</b>
+	 */
+	public void setGroupId(Long groupId) {
+		this.groupId = groupId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>groupId</b>
+	 *
+	 * @return Date - value of member attribute <b>groupId</b> .
+	 */
+	public Long getGroupId() {
+		return groupId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> groupName</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param groupName
+	 *            Value to set member attribute <b> groupName</b>
+	 */
+	public void setGroupName(String groupName) {
+		this.groupName = groupName;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>groupName</b>
+	 *
+	 * @return Date - value of member attribute <b>groupName</b> .
+	 */
+	public String getGroupName() {
+		return groupName;
+	}
+
+	@Override
+	public int hashCode() {
+		return Objects.hash(super.hashCode(), id, policyId, groupId, groupName);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see java.lang.Object#equals(java.lang.Object)
+	 */
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj) {
+			return true;
+		}
+
+		if (getClass() != obj.getClass()) {
+			return false;
+		}
+
+		XXPolicyRefGroup other = (XXPolicyRefGroup) obj;
+
+		return super.equals(obj) &&
+			   Objects.equals(id, other.id) &&
+			   Objects.equals(policyId, other.policyId) &&
+			   Objects.equals(groupId, other.groupId) &&
+			   Objects.equals(groupName, other.groupName);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see java.lang.Object#toString()
+	 */
+	@Override
+	public String toString() {
+		return "XXPolicyRefGroup [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", groupId=" + groupId
+				+ ", groupName=" + groupName + "]";
+	}
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java
new file mode 100644
index 0000000..1150646
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefResource.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ranger.entity;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.util.Objects;
+
+@Entity
+@Cacheable
+@XmlRootElement
+@Table(name = "x_policy_ref_resource")
+public class XXPolicyRefResource extends XXDBBase implements
+		java.io.Serializable {
+	private static final long serialVersionUID = 1L;
+	/**
+	 * id of the XXPolicyRefResource
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Id
+	@SequenceGenerator(name = "x_policy_ref_resource_SEQ", sequenceName = "x_policy_ref_resource_SEQ", allocationSize = 1)
+	@GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_resource_SEQ")
+	@Column(name = "id")
+	protected Long id;
+
+	/**
+	 * policyId of the XXPolicyRefResource
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "policy_id")
+	protected Long policyId;
+
+	/**
+	 * resourceDefId of the XXPolicyRefResource
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "resource_def_id")
+	protected Long resourceDefId;
+
+	/**
+	 * resource_name of the XXPolicyRefResource
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "resource_name")
+	protected String resourceName;
+
+	/**
+	 * This method sets the value to the member attribute <b> id</b> . You
+	 * cannot set null to the attribute.
+	 *
+	 * @param id
+	 *            Value to set member attribute <b> id</b>
+	 */
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>id</b>
+	 *
+	 * @return Date - value of member attribute <b>id</b> .
+	 */
+	public Long getId() {
+		return this.id;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> policyId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param policyId
+	 *            Value to set member attribute <b> policyId</b>
+	 */
+	public void setPolicyId(Long policyId) {
+		this.policyId = policyId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>policyId</b>
+	 *
+	 * @return Date - value of member attribute <b>policyId</b> .
+	 */
+	public Long getPolicyId() {
+		return this.policyId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> resourceDefId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param resourceDefId
+	 *            Value to set member attribute <b> resourceDefId</b>
+	 */
+	public void setResourceDefId(Long resourceDefId) {
+		this.resourceDefId = resourceDefId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>resourceDefId</b>
+	 *
+	 * @return Date - value of member attribute <b>resourceDefId</b> .
+	 */
+	public Long getResourceDefId() {
+		return resourceDefId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> resource_name</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param resourceName
+	 *            Value to set member attribute <b> resource_name</b>
+	 */
+	public void setResourceName(String resourceName) {
+		this.resourceName = resourceName;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>resourceName</b>
+	 *
+	 * @return Date - value of member attribute <b>resourceName</b> .
+	 */
+	public String getResourceName() {
+		return resourceName;
+	}
+
+	@Override
+	public int hashCode() {
+		return Objects.hash(super.hashCode(), id, policyId, resourceDefId, resourceName);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see java.lang.Object#equals(java.lang.Object)
+	 */
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj) {
+			return true;
+		}
+
+		if (getClass() != obj.getClass()) {
+			return false;
+		}
+
+		XXPolicyRefResource other = (XXPolicyRefResource) obj;
+
+		return super.equals(obj) &&
+			   Objects.equals(id, other.id) &&
+			   Objects.equals(policyId, other.policyId) &&
+			   Objects.equals(resourceDefId, other.resourceDefId) &&
+			   Objects.equals(resourceName, other.resourceName);
+	}
+
+	/* (non-Javadoc)
+	 * @see java.lang.Object#toString()
+	 */
+	@Override
+	public String toString() {
+		return "XXPolicyRefResource [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", resourceDefId="
+				+ resourceDefId + ", resource_name=" + resourceName + "]";
+	}
+
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java
new file mode 100644
index 0000000..8dfb928
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXPolicyRefUser.java
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.ranger.entity;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.XmlRootElement;
+import java.util.Objects;
+
+@Entity
+@Cacheable
+@XmlRootElement
+@Table(name = "x_policy_ref_user")
+public class XXPolicyRefUser extends XXDBBase implements
+		java.io.Serializable {
+	private static final long serialVersionUID = 1L;
+	/**
+	 * id of the XXPolicyRefUser
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Id
+	@SequenceGenerator(name = "x_policy_ref_user_SEQ", sequenceName = "x_policy_ref_user_SEQ", allocationSize = 1)
+	@GeneratedValue(strategy = GenerationType.AUTO, generator = "x_policy_ref_user_SEQ")
+	@Column(name = "id")
+	protected Long id;
+
+	/**
+	 * policyId of the XXPolicyRefUser
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "policy_id")
+	protected Long policyId;
+
+	/**
+	 * userId of the XXPolicyRefUser
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "user_id")
+	protected Long userId;
+
+	/**
+	 * userName of the XXPolicyRefUser
+	 * <ul>
+	 * </ul>
+	 *
+	 */
+	@Column(name = "user_name")
+	protected String userName;
+
+	/**
+	 * This method sets the value to the member attribute <b> id</b> . You
+	 * cannot set null to the attribute.
+	 *
+	 * @param id
+	 *            Value to set member attribute <b> id</b>
+	 */
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>id</b>
+	 *
+	 * @return Date - value of member attribute <b>id</b> .
+	 */
+	public Long getId() {
+		return this.id;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> policyId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param policyId
+	 *            Value to set member attribute <b> policyId</b>
+	 */
+	public void setPolicyId(Long policyId) {
+		this.policyId = policyId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>policyId</b>
+	 *
+	 * @return Date - value of member attribute <b>policyId</b> .
+	 */
+	public Long getPolicyId() {
+		return this.policyId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> userId</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param userId
+	 *            Value to set member attribute <b> userId</b>
+	 */
+	public void setUserId(Long userId) {
+		this.userId = userId;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>userId</b>
+	 *
+	 * @return Date - value of member attribute <b>userId</b> .
+	 */
+	public Long getUserId() {
+		return userId;
+	}
+
+	/**
+	 * This method sets the value to the member attribute <b> userName</b> .
+	 * You cannot set null to the attribute.
+	 *
+	 * @param userName
+	 *            Value to set member attribute <b> userName</b>
+	 */
+	public void setUserName(String userName) {
+		this.userName = userName;
+	}
+
+	/**
+	 * Returns the value for the member attribute <b>userName</b>
+	 *
+	 * @return Date - value of member attribute <b>userName</b> .
+	 */
+	public String getUserName() {
+		return userName;
+	}
+
+	@Override
+	public int hashCode() {
+		return Objects.hash(super.hashCode(), id, policyId, userId, userName);
+	}
+
+	/*
+	 * (non-Javadoc)
+	 *
+	 * @see java.lang.Object#equals(java.lang.Object)
+	 */
+	@Override
+	public boolean equals(Object obj) {
+		if (this == obj) {
+			return true;
+		}
+
+		if (getClass() != obj.getClass()) {
+			return false;
+		}
+
+		XXPolicyRefUser other = (XXPolicyRefUser) obj;
+
+		return super.equals(obj) &&
+			   Objects.equals(id, other.id) &&
+			   Objects.equals(policyId, other.policyId) &&
+			   Objects.equals(userId, other.userId) &&
+			   Objects.equals(userName, other.userName);
+	}
+
+	/* (non-Javadoc)
+	 * @see java.lang.Object#toString()
+	 */
+	@Override
+	public String toString() {
+		return "XXPolicyRefUser [" + super.toString() + " id=" + id + ", policyId=" + policyId + ", userId="
+				+ userId + ", userName=" + userName +  "]";
+	}
+
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java
index 961627a..c784830 100644
--- a/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXServiceResource.java
@@ -63,6 +63,12 @@ public class XXServiceResource extends XXDBBase implements Serializable {
 	@Column(name = "service_id")
 	protected Long serviceId;
 
+	@Column(name = "service_resource_elements_text")
+	protected String serviceResourceElements;
+
+	@Column(name = "tags_text")
+	protected String tags;
+
 	@Override
 	public void setId(Long id) {
 		this.id = id;
@@ -148,6 +154,16 @@ public class XXServiceResource extends XXDBBase implements Serializable {
 		this.isEnabled = isEnabled;
 	}
 
+	public String getServiceResourceElements() { return serviceResourceElements; }
+
+	public void setServiceResourceElements(String serviceResourceElements) {
+		this.serviceResourceElements = serviceResourceElements;
+	}
+
+	public String getTags() { return tags; }
+
+	public void setTags(String tags) { this.tags = tags; }
+
 	@Override
 	public int getMyClassType() {
 		return AppConstants.CLASS_TYPE_XA_SERVICE_RESOURCE;
@@ -168,6 +184,8 @@ public class XXServiceResource extends XXDBBase implements Serializable {
 		result = prime * result + ((isEnabled == null) ? 0 : isEnabled.hashCode());
 		result = prime * result + ((resourceSignature == null) ? 0 : resourceSignature.hashCode());
 		result = prime * result + ((serviceId == null) ? 0 : serviceId.hashCode());
+		result = prime * result + ((serviceResourceElements == null) ? 0 : serviceResourceElements.hashCode());
+		result = prime * result + ((tags == null) ? 0 : tags.hashCode());
 		return result;
 	}
 
@@ -215,6 +233,16 @@ public class XXServiceResource extends XXDBBase implements Serializable {
 				return false;
 		} else if (!version.equals(other.version))
 			return false;
+		if (serviceResourceElements == null) {
+			if (other.serviceResourceElements != null)
+				return false;
+		} else if (!serviceResourceElements.equals(other.serviceResourceElements))
+			return false;
+		if (tags == null) {
+			if (other.tags != null)
+				return false;
+		} else if (!tags.equals(other.tags))
+			return false;
 		return true;
 	}
 
@@ -239,6 +267,8 @@ public class XXServiceResource extends XXDBBase implements Serializable {
 		sb.append("isEnabled={").append(isEnabled).append("} ");
 		sb.append("resourceSignature={").append(resourceSignature).append("} ");
 		sb.append("serviceId={").append(serviceId).append("} ");
+		sb.append("serviceResourceElements={").append(serviceResourceElements).append("} ");
+		sb.append("tags={").append(tags).append("} ");
 		sb.append(" }");
 
 		return sb;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java
index d26a0b0..9d5eb61 100644
--- a/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTag.java
@@ -63,6 +63,9 @@ public class XXTag extends XXDBBase implements Serializable {
 	@Column(name = "policy_options")
 	protected String options;
 
+	@Column(name = "tag_attrs_text")
+	protected String tagAttrs;
+
 	@Override
 	public void setId(Long id) {
 		this.id = id;
@@ -129,6 +132,10 @@ public class XXTag extends XXDBBase implements Serializable {
 		return this.options;
 	}
 
+	public String getTagAttrs() { return tagAttrs; }
+
+	public void setTagAttrs(String tagAttrs) { this.tagAttrs = tagAttrs; }
+
     @Override
 	public int getMyClassType() {
 		return AppConstants.CLASS_TYPE_XA_TAG;
@@ -149,6 +156,7 @@ public class XXTag extends XXDBBase implements Serializable {
 		result = prime * result + ((type == null) ? 0 : type.hashCode());
 		result = prime * result + ((owner == null) ? 0 : owner.hashCode());
 		result = prime * result + ((options == null) ? 0 : options.hashCode());
+		result = prime * result + ((tagAttrs == null) ? 0 : tagAttrs.hashCode());
 		return result;
 	}
 
@@ -195,6 +203,11 @@ public class XXTag extends XXDBBase implements Serializable {
 			if (other.options != null)
 				return false;
 		} else if (!options.equals(other.options))
+
+		if (tagAttrs == null) {
+			if (other.tagAttrs != null)
+				return false;
+		} else if (!tagAttrs.equals(other.tagAttrs))
 			return false;
 		return true;
 	}
@@ -219,6 +232,7 @@ public class XXTag extends XXDBBase implements Serializable {
 		sb.append("type={").append(type).append("} ");
 		sb.append("owned_by={").append(owner).append("} ");
 		sb.append("options={").append(options).append("} ");
+		sb.append("tagAttrs={").append(tagAttrs).append("} ");
 		sb.append(" }");
 
 		return sb;

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java b/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java
index 818908b..88a7633 100644
--- a/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXTagDef.java
@@ -63,6 +63,9 @@ public class XXTagDef extends XXDBBase implements Serializable {
 	@Column(name = "source")
 	protected String source;
 
+	@Column(name = "tag_attrs_def_text")
+	protected String tagAttrDefs;
+
 	/**
 	 * @return the guid
 	 */
@@ -138,6 +141,10 @@ public class XXTagDef extends XXDBBase implements Serializable {
 		this.source = source;
 	}
 
+	public String getTagAttrDefs() { return tagAttrDefs; }
+
+	public void setTagAttrDefs(String tagAttrDefs) { this.tagAttrDefs = tagAttrDefs; }
+
 	@Override
 	public void setId(Long id) {
 		this.id = id;
@@ -168,6 +175,7 @@ public class XXTagDef extends XXDBBase implements Serializable {
 		result = prime * result + ((name == null) ? 0 : name.hashCode());
 		result = prime * result + ((source == null) ? 0 : source.hashCode());
 		result = prime * result + ((version == null) ? 0 : version.hashCode());
+		result = prime * result + ((tagAttrDefs == null) ? 0 : tagAttrDefs.hashCode());
 		return result;
 	}
 
@@ -215,6 +223,11 @@ public class XXTagDef extends XXDBBase implements Serializable {
 				return false;
 		} else if (!version.equals(other.version))
 			return false;
+		if (tagAttrDefs == null) {
+			if (other.tagAttrDefs != null)
+				return false;
+		} else if (!tagAttrDefs.equals(other.tagAttrDefs))
+			return false;
 		return true;
 	}
 
@@ -239,6 +252,7 @@ public class XXTagDef extends XXDBBase implements Serializable {
 		sb.append("isEnabled={").append(isEnabled).append("} ");
 		sb.append("source={").append(source).append("} ");
 		sb.append("name={").append(name).append("} ");
+		sb.append("tagAttrDefs={").append(tagAttrDefs).append("} ");
 		sb.append(" }");
 
 		return sb;


[5/9] ranger git commit: RANGER-2203, RANGER-2219: Review and update database schema for ranger policies and tag objects to minimize database queries/updates

Posted by ab...@apache.org.
http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
index 6c699ca..5dfe446 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/ServiceDBStore.java
@@ -27,11 +27,10 @@ import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.Map.Entry;
+import java.util.Set;
 import java.util.StringTokenizer;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -51,6 +50,13 @@ import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.Row;
+import org.apache.poi.ss.usermodel.Sheet;
+import org.apache.poi.ss.usermodel.Workbook;
 import org.apache.ranger.audit.provider.MiscUtil;
 import org.apache.ranger.authorization.hadoop.config.RangerConfiguration;
 import org.apache.ranger.common.AppConstants;
@@ -58,6 +64,7 @@ import org.apache.ranger.common.ContextUtil;
 import org.apache.ranger.common.MessageEnums;
 import org.apache.ranger.common.RangerCommonEnums;
 import org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter;
+import org.apache.ranger.entity.*;
 import org.apache.ranger.plugin.policyengine.RangerPolicyEngine;
 import org.apache.ranger.plugin.policyresourcematcher.RangerDefaultPolicyResourceMatcher;
 import org.apache.ranger.plugin.policyresourcematcher.RangerPolicyResourceMatcher;
@@ -83,59 +90,19 @@ import org.apache.ranger.db.XXDataMaskTypeDefDao;
 import org.apache.ranger.db.XXEnumDefDao;
 import org.apache.ranger.db.XXEnumElementDefDao;
 import org.apache.ranger.db.XXPolicyConditionDefDao;
-import org.apache.ranger.db.XXPolicyItemAccessDao;
-import org.apache.ranger.db.XXPolicyItemConditionDao;
-import org.apache.ranger.db.XXPolicyItemDao;
-import org.apache.ranger.db.XXPolicyItemDataMaskInfoDao;
-import org.apache.ranger.db.XXPolicyItemGroupPermDao;
-import org.apache.ranger.db.XXPolicyItemRowFilterInfoDao;
-import org.apache.ranger.db.XXPolicyItemUserPermDao;
 import org.apache.ranger.db.XXPolicyLabelMapDao;
-import org.apache.ranger.db.XXPolicyResourceDao;
-import org.apache.ranger.db.XXPolicyResourceMapDao;
 import org.apache.ranger.db.XXResourceDefDao;
 import org.apache.ranger.db.XXServiceConfigDefDao;
 import org.apache.ranger.db.XXServiceConfigMapDao;
 import org.apache.ranger.db.XXServiceDao;
 import org.apache.ranger.db.XXServiceVersionInfoDao;
-import org.apache.ranger.entity.XXAccessTypeDef;
-import org.apache.ranger.entity.XXAccessTypeDefGrants;
-import org.apache.ranger.entity.XXContextEnricherDef;
-import org.apache.ranger.entity.XXDataHist;
-import org.apache.ranger.entity.XXDataMaskTypeDef;
-import org.apache.ranger.entity.XXEnumDef;
-import org.apache.ranger.entity.XXEnumElementDef;
-import org.apache.ranger.entity.XXGroup;
-import org.apache.ranger.entity.XXPolicy;
-import org.apache.ranger.entity.XXPolicyConditionDef;
-import org.apache.ranger.entity.XXPolicyItem;
-import org.apache.ranger.entity.XXPolicyItemAccess;
-import org.apache.ranger.entity.XXPolicyItemCondition;
-import org.apache.ranger.entity.XXPolicyItemDataMaskInfo;
-import org.apache.ranger.entity.XXPolicyItemGroupPerm;
-import org.apache.ranger.entity.XXPolicyItemRowFilterInfo;
-import org.apache.ranger.entity.XXPolicyItemUserPerm;
-import org.apache.ranger.entity.XXPolicyLabel;
-import org.apache.ranger.entity.XXPolicyLabelMap;
-import org.apache.ranger.entity.XXPolicyResource;
-import org.apache.ranger.entity.XXPolicyResourceMap;
-import org.apache.ranger.entity.XXResourceDef;
-import org.apache.ranger.entity.XXService;
-import org.apache.ranger.entity.XXServiceConfigDef;
-import org.apache.ranger.entity.XXServiceConfigMap;
-import org.apache.ranger.entity.XXServiceDef;
-import org.apache.ranger.entity.XXServiceVersionInfo;
-import org.apache.ranger.entity.XXTrxLog;
-import org.apache.ranger.entity.XXUser;
 import org.apache.ranger.plugin.model.RangerPolicy;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemDataMaskInfo;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemRowFilterInfo;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem;
 import org.apache.ranger.plugin.model.RangerPolicyResourceSignature;
 import org.apache.ranger.plugin.model.RangerService;
 import org.apache.ranger.plugin.model.RangerServiceDef;
@@ -150,7 +117,6 @@ import org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef;
 import org.apache.ranger.plugin.model.RangerServiceDef.RangerRowFilterDef;
 import org.apache.ranger.plugin.model.RangerServiceDef.RangerServiceConfigDef;
 import org.apache.ranger.plugin.model.validation.RangerServiceDefHelper;
-import org.apache.ranger.plugin.policyevaluator.RangerPolicyItemEvaluator;
 import org.apache.ranger.plugin.store.AbstractServiceStore;
 import org.apache.ranger.plugin.store.EmbeddedServiceDefsUtil;
 import org.apache.ranger.plugin.store.PList;
@@ -188,6 +154,7 @@ import org.apache.ranger.view.VXPolicyLabelList;
 import org.apache.ranger.view.VXString;
 import org.apache.ranger.view.VXUser;
 import org.apache.ranger.view.VXUserList;
+import org.codehaus.jettison.json.JSONException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.stereotype.Component;
@@ -195,14 +162,6 @@ import org.springframework.transaction.PlatformTransactionManager;
 import org.springframework.transaction.TransactionStatus;
 import org.springframework.transaction.support.TransactionCallback;
 import org.springframework.transaction.support.TransactionTemplate;
-import org.apache.poi.hssf.usermodel.HSSFWorkbook;
-import org.apache.poi.ss.usermodel.Cell;
-import org.apache.poi.ss.usermodel.CellStyle;
-import org.apache.poi.ss.usermodel.Font;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.codehaus.jettison.json.JSONException;
 
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
@@ -212,28 +171,30 @@ public class ServiceDBStore extends AbstractServiceStore {
 	private static final Log LOG = LogFactory.getLog(ServiceDBStore.class);
 
 	private static final String POLICY_ALLOW_EXCLUDE = "Policy Allow:Exclude";
-        private static final String POLICY_ALLOW_INCLUDE = "Policy Allow:Include";
-	private static final String POLICY_DENY_EXCLUDE = "Policy Deny:Exclude";
-	private static final String POLICY_DENY_INCLUDE = "Policy Deny:Include";
-	
-        private static final String POLICY_TYPE_ACCESS = "Access";
-        private static final String POLICY_TYPE_DATAMASK  = "Masking";
-        private static final String POLICY_TYPE_ROWFILTER = "Row Level Filter";
-	private static String LOCAL_HOSTNAME = "unknown";
-	private static final String HOSTNAME = "Host name";
-	private static final String USER_NAME = "Exported by";
-	private static final String RANGER_VERSION = "Ranger apache version";
-	private static final String TIMESTAMP = "Export time";
 
-	private static final String AMBARI_SERVICE_CHECK_USER = "ambari.service.check.user";
-	private static final String SERVICE_ADMIN_USERS = "service.admin.users";
+	private static final String POLICY_ALLOW_INCLUDE = "Policy Allow:Include";
+	private static final String POLICY_DENY_EXCLUDE  = "Policy Deny:Exclude";
+	private static final String POLICY_DENY_INCLUDE  = "Policy Deny:Include";
+
+    private static final String POLICY_TYPE_ACCESS = "Access";
+    private static final String POLICY_TYPE_DATAMASK  = "Masking";
+    private static final String POLICY_TYPE_ROWFILTER = "Row Level Filter";
 
-        public static final String CRYPT_ALGO = PropertiesUtil.getProperty("ranger.password.encryption.algorithm", PasswordUtils.DEFAULT_CRYPT_ALGO);
-        public static final String ENCRYPT_KEY = PropertiesUtil.getProperty("ranger.password.encryption.key", PasswordUtils.DEFAULT_ENCRYPT_KEY);
-        public static final String SALT = PropertiesUtil.getProperty("ranger.password.salt", PasswordUtils.DEFAULT_SALT);
-        public static final Integer ITERATION_COUNT = PropertiesUtil.getIntProperty("ranger.password.iteration.count", PasswordUtils.DEFAULT_ITERATION_COUNT);
+	private static       String LOCAL_HOSTNAME = "unknown";
+	private static final String HOSTNAME       = "Host name";
+	private static final String USER_NAME      = "Exported by";
+	private static final String RANGER_VERSION = "Ranger apache version";
+	private static final String TIMESTAMP      = "Export time";
+
+    private static final String AMBARI_SERVICE_CHECK_USER = "ambari.service.check.user";
+	private static final String SERVICE_ADMIN_USERS     = "service.admin.users";
 
-    static {
+	public static final String  CRYPT_ALGO      = PropertiesUtil.getProperty("ranger.password.encryption.algorithm", PasswordUtils.DEFAULT_CRYPT_ALGO);
+	public static final String  ENCRYPT_KEY     = PropertiesUtil.getProperty("ranger.password.encryption.key", PasswordUtils.DEFAULT_ENCRYPT_KEY);
+	public static final String  SALT            = PropertiesUtil.getProperty("ranger.password.salt", PasswordUtils.DEFAULT_SALT);
+	public static final Integer ITERATION_COUNT = PropertiesUtil.getIntProperty("ranger.password.iteration.count", PasswordUtils.DEFAULT_ITERATION_COUNT);
+	
+	static {
 		try {
 			LOCAL_HOSTNAME = java.net.InetAddress.getLocalHost().getCanonicalHostName();
 		} catch (UnknownHostException e) {
@@ -257,7 +218,7 @@ public class ServiceDBStore extends AbstractServiceStore {
 	StringUtil stringUtil;
 	
 	@Autowired
-	RangerAuditFields rangerAuditFields;
+	RangerAuditFields<?> rangerAuditFields;
 	
 	@Autowired
 	RangerPolicyService policyService;
@@ -271,8 +232,11 @@ public class ServiceDBStore extends AbstractServiceStore {
 	@Autowired
 	XUserMgr xUserMgr;
 
-	@Autowired
-	XGroupService xGroupService;
+    @Autowired
+    XGroupService xGroupService;
+
+    @Autowired
+	PolicyRefUpdater policyRefUpdater;
 
 	@Autowired
 	RangerDataHistService dataHistService;
@@ -772,8 +736,8 @@ public class ServiceDBStore extends AbstractServiceStore {
 				}
 			}
 			if (!found) {
-				List<XXPolicyResource> policyResList = daoMgr.getXXPolicyResource().findByResDefId(xRes.getId());
-				if (!stringUtil.isEmpty(policyResList)) {
+				List<XXPolicyRefResource> xxPolicyRefResource = daoMgr.getXXPolicyRefResource().findByResourceDefID(xRes.getId());
+				if (!stringUtil.isEmpty(xxPolicyRefResource)) {
 					throw restErrorUtil.createRESTException("Policy/Policies are referring to this resource: "
 							+ xRes.getName() + ". Please remove such references from policy before updating service-def.",
 							MessageEnums.DATA_NOT_UPDATABLE);
@@ -859,8 +823,8 @@ public class ServiceDBStore extends AbstractServiceStore {
 				}
 			}
 			if (!found) {
-				List<XXPolicyItemAccess> polItemAccessList = daoMgr.getXXPolicyItemAccess().findByType(xAccess.getId());
-				if(!stringUtil.isEmpty(polItemAccessList)) {
+				List<XXPolicyRefAccessType> policyRefAccessTypeList = daoMgr.getXXPolicyRefAccessType().findByAccessTypeDefId(xAccess.getId());
+				if(!stringUtil.isEmpty(policyRefAccessTypeList)) {
 					throw restErrorUtil.createRESTException("Policy/Policies are referring to this access-type: "
 							+ xAccess.getName() + ". Please remove such references from policy before updating service-def.",
 							MessageEnums.DATA_NOT_UPDATABLE);
@@ -902,15 +866,14 @@ public class ServiceDBStore extends AbstractServiceStore {
 				}
 			}
 			if(!found) {
-				List<XXPolicyItemCondition> policyItemCondList = daoMgr.getXXPolicyItemCondition()
-						.findByPolicyConditionDefId(xCondition.getId());
-				if(!stringUtil.isEmpty(policyItemCondList)) {
+				List<XXPolicyRefCondition> xxPolicyRefConditions = daoMgr.getXXPolicyRefCondition().findByConditionDefId(xCondition.getId());
+				if(!stringUtil.isEmpty(xxPolicyRefConditions)) {
 					throw restErrorUtil.createRESTException("Policy/Policies are referring to this policy-condition: "
 							+ xCondition.getName() + ". Please remove such references from policy before updating service-def.",
 							MessageEnums.DATA_NOT_UPDATABLE);
 				}
-				for(XXPolicyItemCondition policyItemCond : policyItemCondList) {
-					daoMgr.getXXPolicyItemCondition().remove(policyItemCond);
+				for(XXPolicyRefCondition xxPolicyRefCondition : xxPolicyRefConditions) {
+					daoMgr.getXXPolicyRefCondition().remove(xxPolicyRefCondition);
 				}
 				xxPolCondDao.remove(xCondition);
 			}
@@ -1243,9 +1206,9 @@ public class ServiceDBStore extends AbstractServiceStore {
 		List<XXPolicyConditionDef> policyCondList = policyCondDao.findByServiceDefId(serviceDefId);
 		
 		for (XXPolicyConditionDef policyCond : policyCondList) {
-			List<XXPolicyItemCondition> policyItemCondList = daoMgr.getXXPolicyItemCondition().findByPolicyConditionDefId(policyCond.getId());
-			for (XXPolicyItemCondition policyItemCond : policyItemCondList) {
-				daoMgr.getXXPolicyItemCondition().remove(policyItemCond);
+			List<XXPolicyRefCondition> xxPolicyRefConditions = daoMgr.getXXPolicyRefCondition().findByConditionDefId(policyCond.getId());
+			for (XXPolicyRefCondition XXPolicyRefCondition : xxPolicyRefConditions) {
+				daoMgr.getXXPolicyRefCondition().remove(XXPolicyRefCondition);
 			}
 			policyCondDao.remove(policyCond);
 		}
@@ -1295,37 +1258,25 @@ public class ServiceDBStore extends AbstractServiceStore {
 			daoMgr.getXXAccessTypeDefGrants().remove(atdGrant);
 		}
 
-		List<XXPolicyItemAccess> policyItemAccessList = daoMgr.getXXPolicyItemAccess().findByType(xAccess.getId());
-		for (XXPolicyItemAccess policyItemAccess : policyItemAccessList) {
-			daoMgr.getXXPolicyItemAccess().remove(policyItemAccess);
+		List<XXPolicyRefAccessType> policyRefAccessTypeList = daoMgr.getXXPolicyRefAccessType().findByAccessTypeDefId(xAccess.getId());
+		for (XXPolicyRefAccessType xxPolicyRefAccessType : policyRefAccessTypeList) {
+			daoMgr.getXXPolicyRefAccessType().remove(xxPolicyRefAccessType);
 		}
 		daoMgr.getXXAccessTypeDef().remove(xAccess);
 	}
 
 	public void deleteXXResourceDef(XXResourceDef xRes) {
-
 		List<XXResourceDef> xChildObjs = daoMgr.getXXResourceDef().findByParentResId(xRes.getId());
 		for(XXResourceDef childRes : xChildObjs) {
 			deleteXXResourceDef(childRes);
 		}
-
-		List<XXPolicyResource> xxResources = daoMgr.getXXPolicyResource().findByResDefId(xRes.getId());
-		for (XXPolicyResource xPolRes : xxResources) {
-			deleteXXPolicyResource(xPolRes);
+		List<XXPolicyRefResource> xxPolicyRefResources = daoMgr.getXXPolicyRefResource().findByResourceDefID(xRes.getId());
+		for (XXPolicyRefResource xPolRefRes : xxPolicyRefResources) {
+			daoMgr.getXXPolicyRefResource().remove(xPolRefRes);
 		}
-
 		daoMgr.getXXResourceDef().remove(xRes);
 	}
 
-	public void deleteXXPolicyResource(XXPolicyResource xPolRes) {
-		List<XXPolicyResourceMap> polResMapList = daoMgr.getXXPolicyResourceMap().findByPolicyResId(xPolRes.getId());
-		XXPolicyResourceMapDao polResMapDao = daoMgr.getXXPolicyResourceMap();
-		for (XXPolicyResourceMap xxPolResMap : polResMapList) {
-			polResMapDao.remove(xxPolResMap);
-		}
-		daoMgr.getXXPolicyResource().remove(xPolRes);
-	}
-
 	@Override
 	public RangerServiceDef getServiceDef(Long id) throws Exception {
 		if (LOG.isDebugEnabled()) {
@@ -1479,7 +1430,7 @@ public class ServiceDBStore extends AbstractServiceStore {
                                 configValue = stringUtil.getValidUserName(configValue);
                         }
 			xConfMap.setConfigvalue(configValue);
-			xConfMapDao.create(xConfMap);
+			xConfMap = xConfMapDao.create(xConfMap);
 		}
 		if (LOG.isDebugEnabled()) {
 			LOG.debug("vXUser:[" + vXUser + "]");
@@ -1605,7 +1556,7 @@ public class ServiceDBStore extends AbstractServiceStore {
 			service = svcService.update(service);
 
 			if (hasTagServiceValueChanged || hasIsEnabledChanged) {
-				updatePolicyVersion(service, false);
+				updatePolicyVersion(service);
 			}
 		}
 
@@ -1713,11 +1664,11 @@ public class ServiceDBStore extends AbstractServiceStore {
 		}
 
 		List<XXPolicy> policies = daoMgr.getXXPolicy().findByServiceId(service.getId());
-		RangerPolicy rangerPolicy =null;
+		//RangerPolicy rangerPolicy =null;
 		for(XXPolicy policy : policies) {
 			LOG.info("Deleting Policy, policyName: " + policy.getName());
-			rangerPolicy = getPolicy(policy.getId());
-			deletePolicy(rangerPolicy);
+			//rangerPolicy = getPolicy(policy.getId());
+			deletePolicy(policy.getId());
 		}
 
 		XXServiceConfigMapDao configDao = daoMgr.getXXServiceConfigMap();
@@ -1875,14 +1826,7 @@ public class ServiceDBStore extends AbstractServiceStore {
 			throw new Exception("policy already exists: ServiceName=" + policy.getService() + "; PolicyName=" + policy.getName() + ". ID=" + existing.getId());
 		}
 
-		Map<String, RangerPolicyResource> resources = policy.getResources();
-		List<RangerPolicyItem> policyItems     = policy.getPolicyItems();
-		List<RangerPolicyItem> denyPolicyItems = policy.getDenyPolicyItems();
-		List<RangerPolicyItem> allowExceptions = policy.getAllowExceptions();
-		List<RangerPolicyItem> denyExceptions  = policy.getDenyExceptions();
-		List<RangerDataMaskPolicyItem> dataMaskItems  = policy.getDataMaskPolicyItems();
-		List<RangerRowFilterPolicyItem> rowFilterItems = policy.getRowFilterPolicyItems();
-                List<String> policyLabels = policy.getPolicyLabels();
+		List<String> policyLabels = policy.getPolicyLabels();
 
 		policy.setVersion(Long.valueOf(1));
 		updatePolicySignature(policy);
@@ -1901,18 +1845,9 @@ public class ServiceDBStore extends AbstractServiceStore {
 		}
 
 		XXPolicy xCreatedPolicy = daoMgr.getXXPolicy().getById(policy.getId());
-
-		createNewResourcesForPolicy(policy, xCreatedPolicy, resources);
-		createNewPolicyItemsForPolicy(policy, xCreatedPolicy, policyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW);
-		createNewPolicyItemsForPolicy(policy, xCreatedPolicy, denyPolicyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY);
-		createNewPolicyItemsForPolicy(policy, xCreatedPolicy, allowExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS);
-		createNewPolicyItemsForPolicy(policy, xCreatedPolicy, denyExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS);
-		createNewDataMaskPolicyItemsForPolicy(policy, xCreatedPolicy, dataMaskItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK);
-		createNewRowFilterPolicyItemsForPolicy(policy, xCreatedPolicy, rowFilterItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER);
-
-                createNewLabelsForPolicy(xCreatedPolicy, policyLabels);
-
-		handlePolicyUpdate(service, true);
+		policyRefUpdater.createNewPolMappingForRefTable(policy, xCreatedPolicy, xServiceDef);
+		createNewLabelsForPolicy(xCreatedPolicy, policyLabels);
+		handlePolicyUpdate(service);
                 RangerPolicy createdPolicy = policyService.getPopulatedViewObject(xCreatedPolicy);
 		dataHistService.createObjectDataHistory(createdPolicy, RangerDataHistService.ACTION_CREATE);
 
@@ -1993,15 +1928,7 @@ public class ServiceDBStore extends AbstractServiceStore {
 				throw new Exception("another policy already exists with name '" + policy.getName() + "'. ID=" + newNamePolicy.getId());
 			}
 		}
-		Map<String, RangerPolicyResource> newResources = policy.getResources();
-		List<RangerPolicyItem> policyItems     = policy.getPolicyItems();
-		List<RangerPolicyItem> denyPolicyItems = policy.getDenyPolicyItems();
-		List<RangerPolicyItem> allowExceptions = policy.getAllowExceptions();
-		List<RangerPolicyItem> denyExceptions  = policy.getDenyExceptions();
-		List<RangerDataMaskPolicyItem> dataMaskPolicyItems = policy.getDataMaskPolicyItems();
-		List<RangerRowFilterPolicyItem> rowFilterItems = policy.getRowFilterPolicyItems();
-                List<String> policyLabels = policy.getPolicyLabels();
-
+		List<String> policyLabels = policy.getPolicyLabels();
 		policy.setCreateTime(xxExisting.getCreateTime());
 		policy.setGuid(xxExisting.getGuid());
 		policy.setVersion(xxExisting.getVersion());
@@ -2010,31 +1937,17 @@ public class ServiceDBStore extends AbstractServiceStore {
 
 		updatePolicySignature(policy);
 
-		boolean isTagVersionUpdateNeeded = false;
-		if (EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(service.getType())) {
-			isTagVersionUpdateNeeded = existing.getIsEnabled() ? !policy.getIsEnabled() : policy.getIsEnabled();
-			isTagVersionUpdateNeeded = isTagVersionUpdateNeeded || !StringUtils.equals(existing.getResourceSignature(), policy.getResourceSignature());
-		}
 		policy = policyService.update(policy);
 		XXPolicy newUpdPolicy = daoMgr.getXXPolicy().getById(policy.getId());
 
-		deleteExistingPolicyResources(policy);
-		deleteExistingPolicyItems(policy);
-                deleteExistingPolicyLabel(policy);
-		
-		createNewResourcesForPolicy(policy, newUpdPolicy, newResources);
-		createNewPolicyItemsForPolicy(policy, newUpdPolicy, policyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW);
-		createNewPolicyItemsForPolicy(policy, newUpdPolicy, denyPolicyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY);
-		createNewPolicyItemsForPolicy(policy, newUpdPolicy, allowExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS);
-		createNewPolicyItemsForPolicy(policy, newUpdPolicy, denyExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS);
-		createNewDataMaskPolicyItemsForPolicy(policy, newUpdPolicy, dataMaskPolicyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK);
-		createNewRowFilterPolicyItemsForPolicy(policy, newUpdPolicy, rowFilterItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER);
-                createNewLabelsForPolicy(newUpdPolicy, policyLabels);
-
-		handlePolicyUpdate(service, isTagVersionUpdateNeeded);
+		policyRefUpdater.cleanupRefTables(policy);
+		deleteExistingPolicyLabel(policy);
+		policyRefUpdater.createNewPolMappingForRefTable(policy, newUpdPolicy, xServiceDef);
+		createNewLabelsForPolicy(newUpdPolicy, policyLabels);
+        handlePolicyUpdate(service);
 		RangerPolicy updPolicy = policyService.getPopulatedViewObject(newUpdPolicy);
 		dataHistService.createObjectDataHistory(updPolicy, RangerDataHistService.ACTION_UPDATE);
-		
+
 		bizUtil.createTrxLog(trxLogList);
 
 		return updPolicy;
@@ -2070,13 +1983,11 @@ public class ServiceDBStore extends AbstractServiceStore {
 		policy.setVersion(version);
 		
 		List<XXTrxLog> trxLogList = policyService.getTransactionLog(policy, RangerPolicyService.OPERATION_DELETE_CONTEXT);
-		
-		deleteExistingPolicyItems(policy);
-		deleteExistingPolicyResources(policy);
-                deleteExistingPolicyLabel(policy);
-		
+
+		policyRefUpdater.cleanupRefTables(policy);
+		deleteExistingPolicyLabel(policy);
 		policyService.delete(policy);
-		handlePolicyUpdate(service, true);
+		handlePolicyUpdate(service);
 		
 		dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_DELETE);
 		
@@ -2085,35 +1996,6 @@ public class ServiceDBStore extends AbstractServiceStore {
 		LOG.info("Policy Deleted Successfully. PolicyName : " + policyName);
 	}
 
-	public void deletePolicy(RangerPolicy policy) throws Exception {
-		if(policy == null) {
-			return;
-		}
-		if(LOG.isDebugEnabled()) {
-			LOG.debug("==> ServiceDBStore.deletePolicy(" + policy.getId() + ")");
-		}
-		RangerService service = getServiceByName(policy.getService());
-		if(service == null) {
-			throw new Exception("service does not exist - name='" + policy.getService());
-		}
-		Long version = policy.getVersion();
-		if(version == null) {
-			version = Long.valueOf(1);
-			LOG.info("Found Version Value: `null`, so setting value of version to 1, While updating object, version should not be null.");
-		} else {
-			version = Long.valueOf(version.longValue() + 1);
-		}
-		policy.setVersion(version);
-		List<XXTrxLog> trxLogList = policyService.getTransactionLog(policy, RangerPolicyService.OPERATION_DELETE_CONTEXT);
-		deleteExistingPolicyItemsNative(policy);
-		deleteExistingPolicyResourcesNative(policy);
-                deleteExistingPolicyLabelNative(policy);
-		daoMgr.getXXPolicy().deletePolicyIDReference("id",policy.getId());
-		handlePolicyUpdate(service, true);
-		dataHistService.createObjectDataHistory(policy, RangerDataHistService.ACTION_DELETE);
-		bizUtil.createTrxLog(trxLogList);
-	}
-
 	@Override
 	public RangerPolicy getPolicy(Long id) throws Exception {
 		return policyService.read(id);
@@ -2814,22 +2696,20 @@ public class ServiceDBStore extends AbstractServiceStore {
 		return validConfigs;
 	}
 
-	private void handlePolicyUpdate(RangerService service, boolean isTagVersionUpdateNeeded) throws Exception {
-		updatePolicyVersion(service, isTagVersionUpdateNeeded);
+	private void handlePolicyUpdate(RangerService service) throws Exception {
+		updatePolicyVersion(service);
 	}
 
 	public enum VERSION_TYPE { POLICY_VERSION, TAG_VERSION, POLICY_AND_TAG_VERSION }
 
-	private void updatePolicyVersion(RangerService service, boolean isTagVersionUpdateNeeded) throws Exception {
+	private void updatePolicyVersion(RangerService service) throws Exception {
 		if(service == null || service.getId() == null) {
 			return;
 		}
 
-		boolean filterForServicePlugin = RangerConfiguration.getInstance().getBoolean(RangerTagDBRetriever.OPTION_RANGER_FILTER_TAGS_FOR_SERVICE_PLUGIN, false);
-
 		XXServiceDao serviceDao = daoMgr.getXXService();
 
-		XXService serviceDbObj = serviceDao.getById(service.getId());
+		final XXService serviceDbObj = serviceDao.getById(service.getId());
 		if(serviceDbObj == null) {
 			LOG.warn("updatePolicyVersion(serviceId=" + service.getId() + "): service not found");
 
@@ -2852,7 +2732,7 @@ public class ServiceDBStore extends AbstractServiceStore {
 			if(CollectionUtils.isNotEmpty(referringServices)) {
 				for(XXService referringService : referringServices) {
 					final Long 		    referringServiceId 	  = referringService.getId();
-					final VERSION_TYPE  tagServiceversionType = filterForServicePlugin && isTagVersionUpdateNeeded ? VERSION_TYPE.POLICY_AND_TAG_VERSION : VERSION_TYPE.POLICY_VERSION;
+					final VERSION_TYPE  tagServiceversionType = VERSION_TYPE.POLICY_VERSION;
 
 					Runnable tagServiceVersionUpdater = new ServiceVersionUpdater(daoManager, referringServiceId, tagServiceversionType);
 					transactionSynchronizationAdapter.executeOnTransactionCommit(tagServiceVersionUpdater);
@@ -2893,352 +2773,40 @@ public class ServiceDBStore extends AbstractServiceStore {
 		}
 	}
 
-	private XXPolicyItem createNewPolicyItemForPolicy(RangerPolicy policy, XXPolicy xPolicy, RangerPolicyItem policyItem, XXServiceDef xServiceDef, int itemOrder, int policyItemType) throws Exception {
-		XXPolicyItem xPolicyItem = new XXPolicyItem();
-
-		xPolicyItem = rangerAuditFields.populateAuditFields(xPolicyItem, xPolicy);
-
-		xPolicyItem.setDelegateAdmin(policyItem.getDelegateAdmin());
-		xPolicyItem.setItemType(policyItemType);
-		xPolicyItem.setIsEnabled(Boolean.TRUE);
-		xPolicyItem.setComments(null);
-		xPolicyItem.setPolicyId(policy.getId());
-		xPolicyItem.setOrder(itemOrder);
-		xPolicyItem = daoMgr.getXXPolicyItem().create(xPolicyItem);
-
-		List<RangerPolicyItemAccess> accesses = policyItem.getAccesses();
-		for (int i = 0; i < accesses.size(); i++) {
-			RangerPolicyItemAccess access = accesses.get(i);
-
-			XXAccessTypeDef xAccTypeDef = daoMgr.getXXAccessTypeDef()
-					.findByNameAndServiceId(access.getType(),
-							xPolicy.getService());
-			if (xAccTypeDef == null) {
-				throw new Exception(access.getType() + ": is not a valid access-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'");
-			}
-
-			XXPolicyItemAccess xPolItemAcc = new XXPolicyItemAccess();
-
-			xPolItemAcc = (XXPolicyItemAccess) rangerAuditFields.populateAuditFields(xPolItemAcc, xPolicyItem);
-			xPolItemAcc.setIsAllowed(access.getIsAllowed());
-			xPolItemAcc.setType(xAccTypeDef.getId());
-			xPolItemAcc.setPolicyitemid(xPolicyItem.getId());
-			xPolItemAcc.setOrder(i);
-
-			daoMgr.getXXPolicyItemAccess().create(xPolItemAcc);
-		}
-
-		List<String> users = policyItem.getUsers();
-		for(int i = 0; i < users.size(); i++) {
-			String user = users.get(i);
-			if (StringUtils.isBlank(user)) {
-				continue;
-			}
-			XXUser xUser = daoMgr.getXXUser().findByUserName(user);
-			if(xUser == null) {
-				throw new Exception(user + ": user does not exist. policy='"+  policy.getName() + "' service='"+ policy.getService() + "' user='" + user +"'");
-			}
-			XXPolicyItemUserPerm xUserPerm = new XXPolicyItemUserPerm();
-			xUserPerm = rangerAuditFields.populateAuditFields(xUserPerm, xPolicyItem);
-			xUserPerm.setUserId(xUser.getId());
-			xUserPerm.setPolicyItemId(xPolicyItem.getId());
-			xUserPerm.setOrder(i);
-			xUserPerm = daoMgr.getXXPolicyItemUserPerm().create(xUserPerm);
-		}
-
-		List<String> groups = policyItem.getGroups();
-		for(int i = 0; i < groups.size(); i++) {
-			String group = groups.get(i);
-			if (StringUtils.isBlank(group)) {
-				continue;
-			}
-			XXGroup xGrp = daoMgr.getXXGroup().findByGroupName(group);
-			if(xGrp == null) {
-				throw new Exception(group + ": group does not exist. policy='"+  policy.getName() + "' service='"+ policy.getService() + "' group='" + group + "'");
-			}
-			XXPolicyItemGroupPerm xGrpPerm = new XXPolicyItemGroupPerm();
-			xGrpPerm = rangerAuditFields.populateAuditFields(xGrpPerm, xPolicyItem);
-			xGrpPerm.setGroupId(xGrp.getId());
-			xGrpPerm.setPolicyItemId(xPolicyItem.getId());
-			xGrpPerm.setOrder(i);
-			xGrpPerm = daoMgr.getXXPolicyItemGroupPerm().create(xGrpPerm);
-		}
-
-		List<RangerPolicyItemCondition> conditions = policyItem.getConditions();
-		for(RangerPolicyItemCondition condition : conditions) {
-			XXPolicyConditionDef xPolCond = daoMgr
-					.getXXPolicyConditionDef().findByServiceDefIdAndName(
-							xServiceDef.getId(), condition.getType());
-
-			if(xPolCond == null) {
-				throw new Exception(condition.getType() + ": is not a valid condition-type. policy='"+  xPolicy.getName() + "' service='"+ xPolicy.getService() + "'");
-			}
-
-			for(int i = 0; i < condition.getValues().size(); i++) {
-				String value = condition.getValues().get(i);
-				XXPolicyItemCondition xPolItemCond = new XXPolicyItemCondition();
-				xPolItemCond = rangerAuditFields.populateAuditFields(xPolItemCond, xPolicyItem);
-				xPolItemCond.setPolicyItemId(xPolicyItem.getId());
-				xPolItemCond.setType(xPolCond.getId());
-				xPolItemCond.setValue(value);
-				xPolItemCond.setOrder(i);
-
-				daoMgr.getXXPolicyItemCondition().create(xPolItemCond);
-			}
-		}
-
-		return xPolicyItem;
-	}
-
-	private void createNewPolicyItemsForPolicy(RangerPolicy policy, XXPolicy xPolicy, List<RangerPolicyItem> policyItems, XXServiceDef xServiceDef, int policyItemType) throws Exception {
-		if(CollectionUtils.isNotEmpty(policyItems)) {
-			for (int itemOrder = 0; itemOrder < policyItems.size(); itemOrder++) {
-				RangerPolicyItem policyItem = policyItems.get(itemOrder);
-				createNewPolicyItemForPolicy(policy, xPolicy, policyItem, xServiceDef, itemOrder, policyItemType);
-			}
-		}
-	}
-
-	private void createNewDataMaskPolicyItemsForPolicy(RangerPolicy policy, XXPolicy xPolicy, List<RangerDataMaskPolicyItem> policyItems, XXServiceDef xServiceDef, int policyItemType) throws Exception {
-		if(CollectionUtils.isNotEmpty(policyItems)) {
-			for (int itemOrder = 0; itemOrder < policyItems.size(); itemOrder++) {
-				RangerDataMaskPolicyItem policyItem = policyItems.get(itemOrder);
-
-				XXPolicyItem xPolicyItem = createNewPolicyItemForPolicy(policy, xPolicy, policyItem, xServiceDef, itemOrder, policyItemType);
-
-				RangerPolicyItemDataMaskInfo dataMaskInfo = policyItem.getDataMaskInfo();
-
-				if(dataMaskInfo != null) {
-					XXDataMaskTypeDef dataMaskDef = daoMgr.getXXDataMaskTypeDef().findByNameAndServiceId(dataMaskInfo.getDataMaskType(), xPolicy.getService());
-
-					if(dataMaskDef == null) {
-						throw new Exception(dataMaskInfo.getDataMaskType() + ": is not a valid datamask-type. policy='" + policy.getName() + "' service='" + policy.getService() + "'");
-					}
-
-					XXPolicyItemDataMaskInfo xxDataMaskInfo = new XXPolicyItemDataMaskInfo();
-
-					xxDataMaskInfo.setPolicyItemId(xPolicyItem.getId());
-					xxDataMaskInfo.setType(dataMaskDef.getId());
-					xxDataMaskInfo.setConditionExpr(dataMaskInfo.getConditionExpr());
-					xxDataMaskInfo.setValueExpr(dataMaskInfo.getValueExpr());
-
-					daoMgr.getXXPolicyItemDataMaskInfo().create(xxDataMaskInfo);
+	private void createNewLabelsForPolicy(XXPolicy xPolicy, List<String> policyLabels) throws Exception {
+		for (String policyLabel : policyLabels) {
+			XXPolicyLabel xXPolicyLabel = daoMgr.getXXPolicyLabels().findByName(policyLabel);
+			if (xXPolicyLabel == null) {
+				xXPolicyLabel = new XXPolicyLabel();
+				if (StringUtils.isNotEmpty(policyLabel)) {
+					xXPolicyLabel.setPolicyLabel(policyLabel);
+					xXPolicyLabel = rangerAuditFields.populateAuditFieldsForCreate(xXPolicyLabel);
+					xXPolicyLabel = daoMgr.getXXPolicyLabels().create(xXPolicyLabel);
 				}
 			}
-		}
-	}
-
-	private void createNewRowFilterPolicyItemsForPolicy(RangerPolicy policy, XXPolicy xPolicy, List<RangerRowFilterPolicyItem> policyItems, XXServiceDef xServiceDef, int policyItemType) throws Exception {
-		if(CollectionUtils.isNotEmpty(policyItems)) {
-			for (int itemOrder = 0; itemOrder < policyItems.size(); itemOrder++) {
-				RangerRowFilterPolicyItem policyItem = policyItems.get(itemOrder);
-
-				XXPolicyItem xPolicyItem = createNewPolicyItemForPolicy(policy, xPolicy, policyItem, xServiceDef, itemOrder, policyItemType);
-
-				RangerPolicyItemRowFilterInfo dataMaskInfo = policyItem.getRowFilterInfo();
-
-				if(dataMaskInfo != null) {
-					XXPolicyItemRowFilterInfo xxRowFilterInfo = new XXPolicyItemRowFilterInfo();
-
-					xxRowFilterInfo.setPolicyItemId(xPolicyItem.getId());
-					xxRowFilterInfo.setFilterExpr(dataMaskInfo.getFilterExpr());
-
-					xxRowFilterInfo = daoMgr.getXXPolicyItemRowFilterInfo().create(xxRowFilterInfo);
-				}
-			}
-		}
-	}
-
-	private void createNewResourcesForPolicy(RangerPolicy policy, XXPolicy xPolicy, Map<String, RangerPolicyResource> resources) throws Exception {
-		
-		for (Entry<String, RangerPolicyResource> resource : resources.entrySet()) {
-			RangerPolicyResource policyRes = resource.getValue();
-
-			XXResourceDef xResDef = daoMgr.getXXResourceDef()
-					.findByNameAndPolicyId(resource.getKey(), policy.getId());
-			if (xResDef == null) {
-				throw new Exception(resource.getKey() + ": is not a valid resource-type. policy='"+  policy.getName() + "' service='"+ policy.getService() + "'");
-			}
-
-			XXPolicyResource xPolRes = new XXPolicyResource();
-			xPolRes = rangerAuditFields.populateAuditFields(xPolRes, xPolicy);
-
-			xPolRes.setIsExcludes(policyRes.getIsExcludes());
-			xPolRes.setIsRecursive(policyRes.getIsRecursive());
-			xPolRes.setPolicyId(policy.getId());
-			xPolRes.setResDefId(xResDef.getId());
-			xPolRes = daoMgr.getXXPolicyResource().create(xPolRes);
-
-			List<String> values = policyRes.getValues();
-			if (CollectionUtils.isNotEmpty(values)) {
-				Set<String> uniqueValues = new LinkedHashSet<String>(values);
-				int i = 0;
-				if (CollectionUtils.isNotEmpty(uniqueValues)) {
-					for (String uniqValue : uniqueValues) {
-						if (!StringUtils.isEmpty(uniqValue)) {
-							XXPolicyResourceMap xPolResMap = new XXPolicyResourceMap();
-							xPolResMap = (XXPolicyResourceMap) rangerAuditFields.populateAuditFields(xPolResMap,
-									xPolRes);
-							xPolResMap.setResourceId(xPolRes.getId());
-							xPolResMap.setValue(uniqValue);
-							xPolResMap.setOrder(i);
-							xPolResMap = daoMgr.getXXPolicyResourceMap().create(xPolResMap);
-							i++;
-
-						}
-					}
-				}
-			}
-		}
-	}
-
-        private void createNewLabelsForPolicy(XXPolicy xPolicy, List<String> policyLabels)
-                        throws Exception {
-                for (String policyLabel : policyLabels) {
-                        XXPolicyLabel xXPolicyLabel = daoMgr.getXXPolicyLabels().findByName(policyLabel);
-                        if (xXPolicyLabel == null) {
-                                xXPolicyLabel = new XXPolicyLabel();
-                                if (StringUtils.isNotEmpty(policyLabel)) {
-                                        xXPolicyLabel.setPolicyLabel(policyLabel);
-                                        xXPolicyLabel = rangerAuditFields.populateAuditFieldsForCreate(xXPolicyLabel);
-                                        xXPolicyLabel = daoMgr.getXXPolicyLabels().create(xXPolicyLabel);
-                                }
-                        }
-                        if (xXPolicyLabel.getId() != null) {
-                                XXPolicyLabelMap xxPolicyLabelMap = new XXPolicyLabelMap();
-                                xxPolicyLabelMap.setPolicyId(xPolicy.getId());
-                                xxPolicyLabelMap.setPolicyLabelId(xXPolicyLabel.getId());
-                                xxPolicyLabelMap = rangerAuditFields.populateAuditFieldsForCreate(xxPolicyLabelMap);
-                                xxPolicyLabelMap = daoMgr.getXXPolicyLabelMap().create(xxPolicyLabelMap);
-                        }
-                }
-        }
-
-
-	private Boolean deleteExistingPolicyItems(RangerPolicy policy) {
-		if(policy == null) {
-			return false;
-		}
-		
-		XXPolicyItemDao policyItemDao = daoMgr.getXXPolicyItem();
-		List<XXPolicyItem> policyItems = policyItemDao.findByPolicyId(policy.getId());
-		for(XXPolicyItem policyItem : policyItems) {
-			Long polItemId = policyItem.getId();
-			
-			XXPolicyItemConditionDao polCondDao = daoMgr.getXXPolicyItemCondition();
-			List<XXPolicyItemCondition> conditions = polCondDao.findByPolicyItemId(polItemId);
-			for(XXPolicyItemCondition condition : conditions) {
-				polCondDao.remove(condition);
-			}
-			
-			XXPolicyItemGroupPermDao grpPermDao = daoMgr.getXXPolicyItemGroupPerm();
-			List<XXPolicyItemGroupPerm> groups = grpPermDao.findByPolicyItemId(polItemId);
-			for(XXPolicyItemGroupPerm group : groups) {
-				grpPermDao.remove(group);
-			}
-			
-			XXPolicyItemUserPermDao userPermDao = daoMgr.getXXPolicyItemUserPerm();
-			List<XXPolicyItemUserPerm> users = userPermDao.findByPolicyItemId(polItemId);
-			for(XXPolicyItemUserPerm user : users) {
-				userPermDao.remove(user);
+			if (xXPolicyLabel.getId() != null) {
+				XXPolicyLabelMap xxPolicyLabelMap = new XXPolicyLabelMap();
+				xxPolicyLabelMap.setPolicyId(xPolicy.getId());
+				xxPolicyLabelMap.setPolicyLabelId(xXPolicyLabel.getId());
+				xxPolicyLabelMap = rangerAuditFields.populateAuditFieldsForCreate(xxPolicyLabelMap);
+				xxPolicyLabelMap = daoMgr.getXXPolicyLabelMap().create(xxPolicyLabelMap);
 			}
-			
-			XXPolicyItemAccessDao polItemAccDao = daoMgr.getXXPolicyItemAccess();
-			List<XXPolicyItemAccess> accesses = polItemAccDao.findByPolicyItemId(polItemId);
-			for(XXPolicyItemAccess access : accesses) {
-				polItemAccDao.remove(access);
-			}
-
-			XXPolicyItemDataMaskInfoDao polItemDataMaskInfoDao = daoMgr.getXXPolicyItemDataMaskInfo();
-			List<XXPolicyItemDataMaskInfo> dataMaskInfos = polItemDataMaskInfoDao.findByPolicyItemId(polItemId);
-			for(XXPolicyItemDataMaskInfo dataMaskInfo : dataMaskInfos) {
-				polItemDataMaskInfoDao.remove(dataMaskInfo);
-			}
-
-			XXPolicyItemRowFilterInfoDao polItemRowFilterInfoDao = daoMgr.getXXPolicyItemRowFilterInfo();
-			List<XXPolicyItemRowFilterInfo> rowFilterInfos = polItemRowFilterInfoDao.findByPolicyItemId(polItemId);
-			for(XXPolicyItemRowFilterInfo rowFilterInfo : rowFilterInfos) {
-				polItemRowFilterInfoDao.remove(rowFilterInfo);
-			}
-
-			policyItemDao.remove(policyItem);
 		}
-		return true;
 	}
 
-	private Boolean deleteExistingPolicyResources(RangerPolicy policy) {
-		if(policy == null) {
+	private Boolean deleteExistingPolicyLabel(RangerPolicy policy) {
+		if (policy == null) {
 			return false;
 		}
-		
-		List<XXPolicyResource> resources = daoMgr.getXXPolicyResource().findByPolicyId(policy.getId());
-		
-		XXPolicyResourceDao resDao = daoMgr.getXXPolicyResource();
-		for(XXPolicyResource resource : resources) {
-			List<XXPolicyResourceMap> resMapList = daoMgr.getXXPolicyResourceMap().findByPolicyResId(resource.getId());
-			
-			XXPolicyResourceMapDao resMapDao = daoMgr.getXXPolicyResourceMap();
-			for(XXPolicyResourceMap resMap : resMapList) {
-				resMapDao.remove(resMap);
-			}
-			resDao.remove(resource);
-		}
-		return true;
-	}
-
-        private Boolean deleteExistingPolicyLabel(RangerPolicy policy) {
-                if (policy == null) {
-                        return false;
-                }
-
-                List<XXPolicyLabelMap> xxPolicyLabelMaps = daoMgr.getXXPolicyLabelMap().findByPolicyId(policy.getId());
-                XXPolicyLabelMapDao policyLabelMapDao = daoMgr.getXXPolicyLabelMap();
-                for (XXPolicyLabelMap xxPolicyLabelMap : xxPolicyLabelMaps) {
-                        policyLabelMapDao.remove(xxPolicyLabelMap);
-                }
-                return true;
-        }
-
-
-	private Boolean deleteExistingPolicyItemsNative(RangerPolicy policy) {
-		if(policy == null) {
-			return false;
-		}
-		XXPolicyItemDao policyItemDao = daoMgr.getXXPolicyItem();
-		List<XXPolicyItem> policyItems = policyItemDao.findByPolicyId(policy.getId());
-		for(XXPolicyItem policyItem : policyItems) {
-			Long polItemId = policyItem.getId();
-			daoMgr.getXXPolicyItemRowFilterInfo().deletePolicyIDReference("policy_item_id", polItemId);
-			daoMgr.getXXPolicyItemDataMaskInfo().deletePolicyIDReference("policy_item_id", polItemId);
-			daoMgr.getXXPolicyItemGroupPerm().deletePolicyIDReference("policy_item_id", polItemId);
-			daoMgr.getXXPolicyItemUserPerm().deletePolicyIDReference("policy_item_id", polItemId);
-			daoMgr.getXXPolicyItemCondition().deletePolicyIDReference("policy_item_id", polItemId);
-			daoMgr.getXXPolicyItemAccess().deletePolicyIDReference("policy_item_id", polItemId);
-		}
-		daoMgr.getXXPolicyItem().deletePolicyIDReference("policy_id", policy.getId());
-		return true;
-	}
 
-	private Boolean deleteExistingPolicyResourcesNative(RangerPolicy policy) {
-		if(policy == null) {
-			return false;
-		}
-		List<XXPolicyResource> resources = daoMgr.getXXPolicyResource().findByPolicyId(policy.getId());
-		for(XXPolicyResource resource : resources) {
-			daoMgr.getXXPolicyResourceMap().deletePolicyIDReference("resource_id", resource.getId());
-			daoMgr.getXXPolicyResource().deletePolicyIDReference("id", resource.getId());
+		List<XXPolicyLabelMap> xxPolicyLabelMaps = daoMgr.getXXPolicyLabelMap().findByPolicyId(policy.getId());
+		XXPolicyLabelMapDao policyLabelMapDao = daoMgr.getXXPolicyLabelMap();
+		for (XXPolicyLabelMap xxPolicyLabelMap : xxPolicyLabelMaps) {
+			policyLabelMapDao.remove(xxPolicyLabelMap);
 		}
 		return true;
 	}
 
-        private Boolean deleteExistingPolicyLabelNative(RangerPolicy policy) {
-                if(policy == null) {
-                        return false;
-                }
-                daoMgr.getXXPolicyLabelMap().deletePolicyIDReference("policy_id", policy.getId());
-                return true;
-        }
-
 	@Override
 	public Boolean getPopulateExistingBaseFields() {
 		return populateExistingBaseFields;
@@ -3631,8 +3199,8 @@ public class ServiceDBStore extends AbstractServiceStore {
                 StringBuffer sbIsRecursive = new StringBuffer();
                 StringBuffer sbIsExcludes = new StringBuffer();
                 Map<String, RangerPolicyResource> resources = policy.getResources();
-                RangerPolicyItemDataMaskInfo dataMaskInfo = new RangerPolicyItemDataMaskInfo();
-                RangerPolicyItemRowFilterInfo filterInfo = new RangerPolicyItemRowFilterInfo();
+                RangerPolicy.RangerPolicyItemDataMaskInfo dataMaskInfo = new RangerPolicy.RangerPolicyItemDataMaskInfo();
+                RangerPolicy.RangerPolicyItemRowFilterInfo filterInfo = new RangerPolicy.RangerPolicyItemRowFilterInfo();
                 policyName = policy.getName();
                 policyName = policyName.replace("|", "");
                 if (resources != null) {
@@ -3953,8 +3521,8 @@ public class ServiceDBStore extends AbstractServiceStore {
                 StringBuffer sbIsRecursive = new StringBuffer();
                 StringBuffer sbIsExcludes = new StringBuffer();
 		Map<String, RangerPolicyResource> resources = policy.getResources();
-                RangerPolicyItemDataMaskInfo dataMaskInfo = new RangerPolicyItemDataMaskInfo();
-                RangerPolicyItemRowFilterInfo filterInfo = new RangerPolicyItemRowFilterInfo();
+                RangerPolicy.RangerPolicyItemDataMaskInfo dataMaskInfo = new RangerPolicy.RangerPolicyItemDataMaskInfo();
+                RangerPolicy.RangerPolicyItemRowFilterInfo filterInfo = new RangerPolicy.RangerPolicyItemRowFilterInfo();
                 cell = row.createCell(1);
                 cell.setCellValue(policy.getName());
                 cell = row.createCell(2);

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java
index d29df93..3cc4765 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/TagDBStore.java
@@ -21,35 +21,26 @@ package org.apache.ranger.biz;
 
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
 import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.ranger.authorization.utils.JsonUtils;
 import org.apache.ranger.common.GUIDUtil;
 import org.apache.ranger.common.MessageEnums;
 import org.apache.ranger.common.RESTErrorUtil;
 import org.apache.ranger.common.RangerAdminTagEnricher;
 import org.apache.ranger.common.RangerServiceTagsCache;
 import org.apache.ranger.db.RangerDaoManager;
-import org.apache.ranger.entity.XXResourceDef;
 import org.apache.ranger.entity.XXService;
-import org.apache.ranger.entity.XXServiceDef;
 import org.apache.ranger.entity.XXServiceResource;
 import org.apache.ranger.entity.XXServiceVersionInfo;
 import org.apache.ranger.entity.XXTag;
-import org.apache.ranger.entity.XXTagAttribute;
-import org.apache.ranger.entity.XXTagAttributeDef;
-import org.apache.ranger.entity.XXServiceResourceElement;
-import org.apache.ranger.entity.XXServiceResourceElementValue;
 import org.apache.ranger.entity.XXTagResourceMap;
 import org.apache.ranger.plugin.model.*;
-import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
-import org.apache.ranger.plugin.model.RangerTagDef.RangerTagAttributeDef;
 import org.apache.ranger.plugin.model.validation.RangerValidityScheduleValidator;
 import org.apache.ranger.plugin.model.validation.ValidationFailureDetails;
 import org.apache.ranger.plugin.store.AbstractTagStore;
@@ -119,8 +110,6 @@ public class TagDBStore extends AbstractTagStore {
 
 		RangerTagDef ret = rangerTagDefService.create(tagDef);
 
-		createTagAttributeDefs(ret.getId(), tagDef.getAttributeDefs());
-
 		ret = rangerTagDefService.read(ret.getId());
 
 		if (LOG.isDebugEnabled()) {
@@ -140,6 +129,8 @@ public class TagDBStore extends AbstractTagStore {
 
 		if (existing == null) {
 			throw errorUtil.createRESTException("failed to update tag-def [" + tagDef.getName() + "], Reason: No TagDef found with id: [" + tagDef.getId() + "]", MessageEnums.DATA_NOT_UPDATABLE);
+		} else if (!existing.getName().equals(tagDef.getName())) {
+			throw errorUtil.createRESTException("Cannot change tag-def name; existing-name:[" + existing.getName() + "], new-name:[" + tagDef.getName() + "]", MessageEnums.DATA_NOT_UPDATABLE);
 		}
 
 		tagDef.setCreatedBy(existing.getCreatedBy());
@@ -149,10 +140,6 @@ public class TagDBStore extends AbstractTagStore {
 
 		RangerTagDef ret = rangerTagDefService.update(tagDef);
 
-		// TODO: delete attributes might fail; so instead of delete+create, following should be updated to deal with only attributes that changed
-		deleteTagAttributeDefs(ret.getId());
-		createTagAttributeDefs(ret.getId(), tagDef.getAttributeDefs());
-
 		ret = rangerTagDefService.read(ret.getId());
 
 		if (LOG.isDebugEnabled()) {
@@ -176,7 +163,6 @@ public class TagDBStore extends AbstractTagStore {
 					LOG.debug("Deleting tag-def [name=" + name + "; id=" + tagDef.getId() + "]");
 				}
 
-				deleteTagAttributeDefs(tagDef.getId());
 				rangerTagDefService.delete(tagDef);
 			}
 		}
@@ -196,7 +182,6 @@ public class TagDBStore extends AbstractTagStore {
 			RangerTagDef tagDef = rangerTagDefService.read(id);
 
 			if(tagDef != null) {
-				deleteTagAttributeDefs(tagDef.getId());
 				rangerTagDefService.delete(tagDef);
 			}
 		}
@@ -311,8 +296,6 @@ public class TagDBStore extends AbstractTagStore {
 
 		RangerTag ret = rangerTagService.create(tag);
 
-		createTagAttributes(ret.getId(), tag.getAttributes());
-
 		ret = rangerTagService.read(ret.getId());
 
 		if (LOG.isDebugEnabled()) {
@@ -343,9 +326,6 @@ public class TagDBStore extends AbstractTagStore {
 
 		RangerTag ret = rangerTagService.update(tag);
 
-		deleteTagAttributes(existing.getId());
-		createTagAttributes(existing.getId(), tag.getAttributes());
-
 		ret = rangerTagService.read(ret.getId());
 
 		if (LOG.isDebugEnabled()) {
@@ -363,8 +343,6 @@ public class TagDBStore extends AbstractTagStore {
 
 		RangerTag tag = rangerTagService.read(id);
 
-		deleteTagAttributes(id);
-
 		rangerTagService.delete(tag);
 
 		if (LOG.isDebugEnabled()) {
@@ -504,8 +482,6 @@ public class TagDBStore extends AbstractTagStore {
 
 		RangerServiceResource ret = rangerServiceResourceService.create(resource);
 
-		createResourceForServiceResource(ret.getId(), resource);
-
 		ret = rangerServiceResourceService.read(ret.getId());
 
 		if (LOG.isDebugEnabled()) {
@@ -533,9 +509,6 @@ public class TagDBStore extends AbstractTagStore {
 			resource.setResourceSignature(serializer.getSignature());
 		}
 
-		boolean serviceResourceElementUpdateNeeded =
-				!StringUtils.equals(existing.getResourceSignature(), resource.getResourceSignature());
-
 		resource.setCreatedBy(existing.getCreatedBy());
 		resource.setCreateTime(existing.getCreateTime());
 		resource.setGuid(existing.getGuid());
@@ -543,11 +516,6 @@ public class TagDBStore extends AbstractTagStore {
 
 		rangerServiceResourceService.update(resource);
 
-		if (serviceResourceElementUpdateNeeded) {
-			deleteResourceForServiceResource(existing.getId());
-			createResourceForServiceResource(existing.getId(), resource);
-		}
-
 		RangerServiceResource ret = rangerServiceResourceService.read(existing.getId());
 
 		if (LOG.isDebugEnabled()) {
@@ -557,6 +525,24 @@ public class TagDBStore extends AbstractTagStore {
 		return ret;
 	}
 
+
+	@Override
+	public void refreshServiceResource(Long resourceId) throws Exception {
+		XXServiceResource serviceResourceEntity = daoManager.getXXServiceResource().getById(resourceId);
+		String tagsText = null;
+
+		List<RangerTagResourceMap> tagResourceMaps = getTagResourceMapsForResourceId(resourceId);
+		if (tagResourceMaps != null) {
+			List<RangerTag> associatedTags = new ArrayList<>();
+			for (RangerTagResourceMap element : tagResourceMaps) {
+				associatedTags.add(getTag(element.getTagId()));
+			}
+			tagsText = JsonUtils.listToJson(associatedTags);
+		}
+		serviceResourceEntity.setTags(tagsText);
+		daoManager.getXXServiceResource().update(serviceResourceEntity);
+	}
+
 	@Override
 	public void deleteServiceResource(Long id) throws Exception {
 		if (LOG.isDebugEnabled()) {
@@ -566,7 +552,6 @@ public class TagDBStore extends AbstractTagStore {
 		RangerServiceResource resource = getServiceResource(id);
 
 		if(resource != null) {
-			deleteResourceForServiceResource(resource.getId());
 			rangerServiceResourceService.delete(resource);
 		}
 
@@ -584,7 +569,6 @@ public class TagDBStore extends AbstractTagStore {
 		RangerServiceResource resource = getServiceResourceByGuid(guid);
 
 		if(resource != null) {
-			deleteResourceForServiceResource(resource.getId());
 			rangerServiceResourceService.delete(resource);
 		}
 
@@ -725,6 +709,9 @@ public class TagDBStore extends AbstractTagStore {
 
 		RangerTagResourceMap ret = rangerTagResourceMapService.create(tagResourceMap);
 
+		// We also need to update tags stored with the resource
+		refreshServiceResource(tagResourceMap.getResourceId());
+
 		if (LOG.isDebugEnabled()) {
 			LOG.debug("<== TagDBStore.createTagResourceMap(" + tagResourceMap + "): " + ret);
 		}
@@ -747,6 +734,8 @@ public class TagDBStore extends AbstractTagStore {
 		if (tag.getOwner() == RangerTag.OWNER_SERVICERESOURCE) {
 			deleteTag(tagId);
 		}
+		// We also need to update tags stored with the resource
+		refreshServiceResource(tagResourceMap.getResourceId());
 
 		if (LOG.isDebugEnabled()) {
 			LOG.debug("<== TagDBStore.deleteTagResourceMap(" + id + ")");
@@ -1002,31 +991,7 @@ public class TagDBStore extends AbstractTagStore {
 		Map<Long, RangerTagDef> tagDefMap = tagDBRetriever.getTagDefs();
 		Map<Long, RangerTag> tagMap = tagDBRetriever.getTags();
 		List<RangerServiceResource> resources = tagDBRetriever.getServiceResources();
-		List<RangerTagResourceMap> tagResourceMaps = tagDBRetriever.getTagResourceMaps();
-
-		Map<Long, List<Long>> resourceToTagIds = new HashMap<Long, List<Long>>();
-
-		if (CollectionUtils.isNotEmpty(tagResourceMaps)) {
-			Long resourceId = null;
-			List<Long> tagIds = null;
-
-			for (RangerTagResourceMap tagResourceMap : tagResourceMaps) {
-				if (!tagResourceMap.getResourceId().equals(resourceId)) {
-					if (resourceId != null) {
-						resourceToTagIds.put(resourceId, tagIds);
-					}
-
-					resourceId = tagResourceMap.getResourceId();
-					tagIds = new ArrayList<Long>();
-				}
-
-				tagIds.add(tagResourceMap.getTagId());
-			}
-
-			if (resourceId != null) {
-				resourceToTagIds.put(resourceId, tagIds);
-			}
-		}
+		Map<Long, List<Long>> resourceToTagIds = tagDBRetriever.getResourceToTagIds();
 
 		ret = new ServiceTags();
 
@@ -1045,159 +1010,6 @@ public class TagDBStore extends AbstractTagStore {
 
 	}
 
-	private List<XXTagAttributeDef> createTagAttributeDefs(Long tagDefId, List<RangerTagAttributeDef> tagAttrDefList) {
-		if (LOG.isDebugEnabled()) {
-			LOG.debug("==> TagDBStore.createTagAttributeDefs(" + tagDefId + ", attributeDefCount=" + (tagAttrDefList == null ? 0 : tagAttrDefList.size()) + ")");
-		}
-
-		if (tagDefId == null) {
-			throw errorUtil.createRESTException("TagDBStore.createTagAttributeDefs(): Error creating tag-attr def. tagDefId can not be null.", MessageEnums.ERROR_CREATING_OBJECT);
-		}
-
-		List<XXTagAttributeDef> ret = new ArrayList<XXTagAttributeDef>();
-
-		if (CollectionUtils.isNotEmpty(tagAttrDefList)) {
-			for (RangerTagDef.RangerTagAttributeDef attrDef : tagAttrDefList) {
-				XXTagAttributeDef xAttrDef = new XXTagAttributeDef();
-
-				xAttrDef.setTagDefId(tagDefId);
-				xAttrDef.setName(attrDef.getName());
-				xAttrDef.setType(attrDef.getType());
-				xAttrDef = rangerAuditFields.populateAuditFieldsForCreate(xAttrDef);
-
-				xAttrDef = daoManager.getXXTagAttributeDef().create(xAttrDef);
-
-				ret.add(xAttrDef);
-			}
-		}
-
-		if (LOG.isDebugEnabled()) {
-			LOG.debug("<== TagDBStore.createTagAttributeDefs(" + tagDefId + ", attributeDefCount=" + (tagAttrDefList == null ? 0 : tagAttrDefList.size()) + "): retCount=" + ret.size());
-		}
-
-		return ret;
-	}
-
-	private void deleteTagAttributeDefs(Long tagDefId) {
-		if (LOG.isDebugEnabled()) {
-			LOG.debug("==> TagDBStore.deleteTagAttributeDefs(" + tagDefId + ")");
-		}
-
-		if (tagDefId != null) {
-			List<XXTagAttributeDef> tagAttrDefList = daoManager.getXXTagAttributeDef().findByTagDefId(tagDefId);
-
-			if (CollectionUtils.isNotEmpty(tagAttrDefList)) {
-				for (XXTagAttributeDef xAttrDef : tagAttrDefList) {
-					if (LOG.isDebugEnabled()) {
-						LOG.debug("Deleting tag-attribute def [name=" + xAttrDef.getName() + "; id=" + xAttrDef.getId() + "]");
-					}
-					daoManager.getXXTagAttributeDef().remove(xAttrDef);
-				}
-			}
-		}
-
-		if (LOG.isDebugEnabled()) {
-			LOG.debug("<== TagDBStore.deleteTagAttributeDefs(" + tagDefId + ")");
-		}
-	}
-
-	private List<XXTagAttribute> createTagAttributes(Long tagId, Map<String, String> attributes) throws Exception {
-		List<XXTagAttribute> ret = new ArrayList<XXTagAttribute>();
-
-		if(MapUtils.isNotEmpty(attributes)) {
-			for (Map.Entry<String, String> attr : attributes.entrySet()) {
-				XXTagAttribute xTagAttr = new XXTagAttribute();
-
-				xTagAttr.setTagId(tagId);
-				xTagAttr.setName(attr.getKey());
-				xTagAttr.setValue(attr.getValue());
-				xTagAttr = rangerAuditFields.populateAuditFieldsForCreate(xTagAttr);
-
-				xTagAttr = daoManager.getXXTagAttribute().create(xTagAttr);
-
-				ret.add(xTagAttr);
-			}
-		}
-
-		return ret;
-	}
-
-	private void deleteTagAttributes(Long tagId) {
-		List<XXTagAttribute> tagAttrList = daoManager.getXXTagAttribute().findByTagId(tagId);
-		for (XXTagAttribute tagAttr : tagAttrList) {
-			daoManager.getXXTagAttribute().remove(tagAttr);
-		}
-	}
-
-	private void deleteResourceForServiceResource(Long resourceId) {
-		List<XXServiceResourceElement> resElements = daoManager.getXXServiceResourceElement().findByResourceId(resourceId);
-		
-		if(CollectionUtils.isNotEmpty(resElements)) {
-			for(XXServiceResourceElement resElement : resElements) {
-				List<XXServiceResourceElementValue> elementValues = daoManager.getXXServiceResourceElementValue().findByResValueId(resElement.getId());
-				
-				if(CollectionUtils.isNotEmpty(elementValues)) {
-					for(XXServiceResourceElementValue elementValue : elementValues) {
-						daoManager.getXXServiceResourceElementValue().remove(elementValue.getId());
-					}
-				}
-				
-				daoManager.getXXServiceResourceElement().remove(resElement.getId());
-			}
-		}
-	}
-
-	private void createResourceForServiceResource(Long resourceId, RangerServiceResource serviceResource) {
-		String serviceName = serviceResource.getServiceName();
-
-		XXService xService = daoManager.getXXService().findByName(serviceName);
-
-		if (xService == null) {
-			throw errorUtil.createRESTException("No Service found with name: " + serviceName, MessageEnums.ERROR_CREATING_OBJECT);
-		}
-
-		XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType());
-
-		if (xServiceDef == null) {
-			throw errorUtil.createRESTException("No Service-Def found with ID: " + xService.getType(), MessageEnums.ERROR_CREATING_OBJECT);
-		}
-
-		Map<String, RangerPolicy.RangerPolicyResource> resElements = serviceResource.getResourceElements();
-
-		for (Map.Entry<String, RangerPolicyResource> resElement : resElements.entrySet()) {
-			XXResourceDef xResDef = daoManager.getXXResourceDef().findByNameAndServiceDefId(resElement.getKey(), xServiceDef.getId());
-
-			if (xResDef == null) {
-				LOG.error("TagDBStore.createResource: ResourceType is not valid [" + resElement.getKey() + "]");
-				throw errorUtil.createRESTException("Resource Type is not valid [" + resElement.getKey() + "]", MessageEnums.DATA_NOT_FOUND);
-			}
-
-			RangerPolicyResource policyRes = resElement.getValue();
-
-			XXServiceResourceElement resourceElement = new XXServiceResourceElement();
-			resourceElement.setIsExcludes(policyRes.getIsExcludes());
-			resourceElement.setIsRecursive(policyRes.getIsRecursive());
-			resourceElement.setResDefId(xResDef.getId());
-			resourceElement.setResourceId(resourceId);
-
-			resourceElement = rangerAuditFields.populateAuditFieldsForCreate(resourceElement);
-
-			resourceElement = daoManager.getXXServiceResourceElement().create(resourceElement);
-
-			int sortOrder = 1;
-			for (String resVal : policyRes.getValues()) {
-				XXServiceResourceElementValue resourceElementValue = new XXServiceResourceElementValue();
-				resourceElementValue.setResElementId(resourceElement.getId());
-				resourceElementValue.setValue(resVal);
-				resourceElementValue.setSortOrder(sortOrder);
-				resourceElementValue = rangerAuditFields.populateAuditFieldsForCreate(resourceElementValue);
-
-				resourceElementValue = daoManager.getXXServiceResourceElementValue().create(resourceElementValue);
-				sortOrder++;
-			}
-		}
-	}
-
 	@Override
 	public void deleteAllTagObjectsForService(String serviceName) throws Exception {
 
@@ -1210,8 +1022,6 @@ public class TagDBStore extends AbstractTagStore {
 		if (service != null) {
 			Long serviceId = service.getId();
 
-			List<XXTagAttribute> xxTagAttributes = daoManager.getXXTagAttribute().findByServiceIdAndOwner(serviceId, RangerTag.OWNER_SERVICERESOURCE);
-
 			List<XXTag> xxTags = daoManager.getXXTag().findByServiceIdAndOwner(serviceId, RangerTag.OWNER_SERVICERESOURCE);
 
 			List<XXTagResourceMap> xxTagResourceMaps = daoManager.getXXTagResourceMap().findByServiceId(serviceId);
@@ -1227,17 +1037,6 @@ public class TagDBStore extends AbstractTagStore {
 				}
 			}
 
-			if (CollectionUtils.isNotEmpty(xxTagAttributes)) {
-				for (XXTagAttribute xxTagAttribute : xxTagAttributes) {
-					try {
-						daoManager.getXXTagAttribute().remove(xxTagAttribute);
-					} catch (Exception e) {
-						LOG.error("Error deleting RangerTagAttribute with id=" + xxTagAttribute.getId(), e);
-						throw e;
-					}
-				}
-			}
-
 			if (CollectionUtils.isNotEmpty(xxTags)) {
 				for (XXTag xxTag : xxTags) {
 					try {
@@ -1249,32 +1048,6 @@ public class TagDBStore extends AbstractTagStore {
 				}
 			}
 
-			List<XXServiceResourceElementValue> xxServiceResourceElementValues = daoManager.getXXServiceResourceElementValue().findByServiceId(serviceId);
-
-			if (CollectionUtils.isNotEmpty(xxServiceResourceElementValues)) {
-				for (XXServiceResourceElementValue xxServiceResourceElementValue : xxServiceResourceElementValues) {
-					try {
-						daoManager.getXXServiceResourceElementValue().remove(xxServiceResourceElementValue);
-					} catch (Exception e) {
-						LOG.error("Error deleting ServiceResourceElementValue with id=" + xxServiceResourceElementValue.getId(), e);
-						throw e;
-					}
-				}
-			}
-
-			List<XXServiceResourceElement> xxServiceResourceElements = daoManager.getXXServiceResourceElement().findByServiceId(serviceId);
-
-			if (CollectionUtils.isNotEmpty(xxServiceResourceElements)) {
-				for (XXServiceResourceElement xxServiceResourceElement : xxServiceResourceElements) {
-					try {
-						daoManager.getXXServiceResourceElement().remove(xxServiceResourceElement);
-					} catch (Exception e) {
-						LOG.error("Error deleting ServiceResourceElement with id=" + xxServiceResourceElement.getId(), e);
-						throw e;
-					}
-				}
-			}
-
 			List<XXServiceResource> xxServiceResources = daoManager.getXXServiceResource().findByServiceId(serviceId);
 
 			if (CollectionUtils.isNotEmpty(xxServiceResources)) {

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java b/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java
index 0d5689a..0724952 100644
--- a/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java
+++ b/security-admin/src/main/java/org/apache/ranger/common/RangerServicePoliciesCache.java
@@ -274,6 +274,7 @@ public class RangerServicePoliciesCache {
 					// policy.setName(null); /* this is used by GUI in policy list page */
 					// policy.setDescription(null); /* this is used by export policy */
 					policy.setResourceSignature(null);
+					policy.setOptions(null);
 				}
 			}
 		}

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java b/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java
index 5dffc0e..5cecef1 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/RangerDaoManagerBase.java
@@ -264,5 +264,29 @@ public abstract class RangerDaoManagerBase {
 	public XXUgsyncAuditInfoDao getXXUgsyncAuditInfo() {
 		return new XXUgsyncAuditInfoDao(this);
 	}
+
+	public XXPolicyRefConditionDao getXXPolicyRefCondition() {
+		return new XXPolicyRefConditionDao(this);
+	}
+
+	public XXPolicyRefGroupDao getXXPolicyRefGroup() {
+		return new XXPolicyRefGroupDao(this);
+	}
+
+	public XXPolicyRefDataMaskTypeDao getXXPolicyRefDataMaskType() {
+		return new XXPolicyRefDataMaskTypeDao(this);
+	}
+
+	public XXPolicyRefResourceDao getXXPolicyRefResource() {
+		return new XXPolicyRefResourceDao(this);
+	}
+
+	public XXPolicyRefUserDao getXXPolicyRefUser() {
+		return new XXPolicyRefUserDao(this);
+	}
+
+	public XXPolicyRefAccessTypeDao getXXPolicyRefAccessType() {
+		return new XXPolicyRefAccessTypeDao(this);
+	}
 }
 

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java
index e04280b..8f57498 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXAccessTypeDefDao.java
@@ -60,5 +60,4 @@ public class XXAccessTypeDefDao extends BaseDao<XXAccessTypeDef> {
 			return null;
 		}
 	}
-
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java
index 3dd4376..83c2881 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXDataMaskTypeDefDao.java
@@ -60,5 +60,4 @@ public class XXDataMaskTypeDefDao extends BaseDao<XXDataMaskTypeDef> {
 			return null;
 		}
 	}
-
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java
index 9a87b4c..1bd59f8 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXGroupDao.java
@@ -23,8 +23,6 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import javax.persistence.NoResultException;
-
 import org.apache.ranger.common.db.BaseDao;
 import org.apache.ranger.entity.XXGroup;
 import org.springframework.stereotype.Service;
@@ -68,19 +66,5 @@ public class XXGroupDao extends BaseDao<XXGroup> {
 		}
 		return null;
 	}
-	
-	@SuppressWarnings("unchecked")
-	public List<String> findByPolicyItemId(Long polItemId) {
-		if (polItemId == null) {
-			return null;
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXGroup.findByPolicyItemId")
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return null;
-		}
-	}
 
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java
index a12140a..de2c47d 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyConditionDefDao.java
@@ -61,33 +61,5 @@ public class XXPolicyConditionDefDao extends BaseDao<XXPolicyConditionDef> {
 			return null;
 		}
 	}
-
-	public List<XXPolicyConditionDef> findByPolicyItemId(Long polItemId) {
-		if(polItemId == null) {
-			return new ArrayList<XXPolicyConditionDef>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyConditionDef.findByPolicyItemId", tClass)
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyConditionDef>();
-		}
-	}
-	
-	public XXPolicyConditionDef findByPolicyItemIdAndName(Long polItemId, String name) {
-		if(polItemId == null || name == null) {
-			return null;
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyConditionDef.findByPolicyItemIdAndName", tClass)
-					.setParameter("polItemId", polItemId)
-					.setParameter("name", name).getSingleResult();
-		} catch (NoResultException e) {
-			return null;
-		}
-	}
-
 	
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java
index 9be38de..671ed0e 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemAccessDao.java
@@ -32,19 +32,6 @@ public class XXPolicyItemAccessDao extends BaseDao<XXPolicyItemAccess> {
 	public XXPolicyItemAccessDao(RangerDaoManagerBase daoManager) {
 		super(daoManager);
 	}
-	
-	public List<XXPolicyItemAccess> findByPolicyItemId(Long polItemId) {
-		if(polItemId == null) {
-			return new ArrayList<XXPolicyItemAccess>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyItemAccess.findByPolicyItemId", tClass)
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemAccess>();
-		}
-	}
 
 	public List<XXPolicyItemAccess> findByPolicyId(Long policyId) {
 		if(policyId == null) {
@@ -72,16 +59,4 @@ public class XXPolicyItemAccessDao extends BaseDao<XXPolicyItemAccess> {
 		}
 	}
 
-	public List<XXPolicyItemAccess> findByType(Long type) {
-		if (type == null) {
-			return new ArrayList<XXPolicyItemAccess>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXPolicyItemAccess.findByType", tClass)
-					.setParameter("type", type).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemAccess>();
-		}
-	}
-
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java
index 9b11545..43e17db 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemConditionDao.java
@@ -32,19 +32,6 @@ public class XXPolicyItemConditionDao extends BaseDao<XXPolicyItemCondition> {
 	public XXPolicyItemConditionDao(RangerDaoManagerBase daoManager) {
 		super(daoManager);
 	}
-	
-	public List<XXPolicyItemCondition> findByPolicyItemId(Long polItemId) {
-		if(polItemId == null) {
-			return new ArrayList<XXPolicyItemCondition>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyItemCondition.findByPolicyItemId", tClass)
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemCondition>();
-		}
-	}
 
 	public List<XXPolicyItemCondition> findByPolicyId(Long policyId) {
 		if(policyId == null) {
@@ -72,31 +59,4 @@ public class XXPolicyItemConditionDao extends BaseDao<XXPolicyItemCondition> {
 		}
 	}
 
-	public List<XXPolicyItemCondition> findByPolicyItemAndDefId(Long polItemId,
-			Long polCondDefId) {
-		if(polItemId == null || polCondDefId == null) {
-			return new ArrayList<XXPolicyItemCondition>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyItemCondition.findByPolicyItemAndDefId", tClass)
-					.setParameter("polItemId", polItemId)
-					.setParameter("polCondDefId", polCondDefId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemCondition>();
-		}
-	}
-
-	public List<XXPolicyItemCondition> findByPolicyConditionDefId(Long polCondDefId) {
-		if (polCondDefId == null) {
-			return new ArrayList<XXPolicyItemCondition>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXPolicyItemCondition.findByPolicyConditionDefId", tClass)
-					.setParameter("polCondDefId", polCondDefId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemCondition>();
-		}
-	}
-
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java
index 67c7e99..5cee710 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemDataMaskInfoDao.java
@@ -32,19 +32,6 @@ public class XXPolicyItemDataMaskInfoDao extends BaseDao<XXPolicyItemDataMaskInf
 	public XXPolicyItemDataMaskInfoDao(RangerDaoManagerBase daoManager) {
 		super(daoManager);
 	}
-	
-	public List<XXPolicyItemDataMaskInfo> findByPolicyItemId(Long polItemId) {
-		if(polItemId == null) {
-			return new ArrayList<XXPolicyItemDataMaskInfo>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyItemDataMaskInfo.findByPolicyItemId", tClass)
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemDataMaskInfo>();
-		}
-	}
 
 	public List<XXPolicyItemDataMaskInfo> findByPolicyId(Long policyId) {
 		if(policyId == null) {
@@ -72,16 +59,4 @@ public class XXPolicyItemDataMaskInfoDao extends BaseDao<XXPolicyItemDataMaskInf
 		}
 	}
 
-	public List<XXPolicyItemDataMaskInfo> findByType(Long type) {
-		if (type == null) {
-			return new ArrayList<XXPolicyItemDataMaskInfo>();
-		}
-		try {
-			return getEntityManager().createNamedQuery("XXPolicyItemDataMaskInfo.findByType", tClass)
-					.setParameter("type", type).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemDataMaskInfo>();
-		}
-	}
-
 }

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java
index a6fd8c6..68cf4d0 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemGroupPermDao.java
@@ -33,19 +33,6 @@ public class XXPolicyItemGroupPermDao extends BaseDao<XXPolicyItemGroupPerm> {
 		super(daoManager);
 	}
 
-	public List<XXPolicyItemGroupPerm> findByPolicyItemId(Long polItemId) {
-		if(polItemId == null) {
-			return new ArrayList<XXPolicyItemGroupPerm>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyItemGroupPerm.findByPolicyItemId", tClass)
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemGroupPerm>();
-		}
-	}
-
 	public List<XXPolicyItemGroupPerm> findByPolicyId(Long policyId) {
 		if(policyId == null) {
 			return new ArrayList<XXPolicyItemGroupPerm>();

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java
index 01a36a5..9c2edbc 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemRowFilterInfoDao.java
@@ -31,19 +31,6 @@ public class XXPolicyItemRowFilterInfoDao extends BaseDao<XXPolicyItemRowFilterI
 	public XXPolicyItemRowFilterInfoDao(RangerDaoManagerBase daoManager) {
 		super(daoManager);
 	}
-	
-	public List<XXPolicyItemRowFilterInfo> findByPolicyItemId(Long polItemId) {
-		if(polItemId == null) {
-			return new ArrayList<XXPolicyItemRowFilterInfo>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyItemRowFilterInfo.findByPolicyItemId", tClass)
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemRowFilterInfo>();
-		}
-	}
 
 	public List<XXPolicyItemRowFilterInfo> findByPolicyId(Long policyId) {
 		if(policyId == null) {

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java
index 6672654..63ef5ca 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyItemUserPermDao.java
@@ -33,19 +33,6 @@ public class XXPolicyItemUserPermDao extends BaseDao<XXPolicyItemUserPerm> {
 		super(daoManager);
 	}
 
-	public List<XXPolicyItemUserPerm> findByPolicyItemId(Long polItemId) {
-		if(polItemId == null) {
-			return new ArrayList<XXPolicyItemUserPerm>();
-		}
-		try {
-			return getEntityManager()
-					.createNamedQuery("XXPolicyItemUserPerm.findByPolicyItemId", tClass)
-					.setParameter("polItemId", polItemId).getResultList();
-		} catch (NoResultException e) {
-			return new ArrayList<XXPolicyItemUserPerm>();
-		}
-	}
-
 	public List<XXPolicyItemUserPerm> findByPolicyId(Long policyId) {
 		if(policyId == null) {
 			return new ArrayList<XXPolicyItemUserPerm>();

http://git-wip-us.apache.org/repos/asf/ranger/blob/d424b1a8/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java
new file mode 100644
index 0000000..1ef01bb
--- /dev/null
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyRefAccessTypeDao.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.ranger.db;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.persistence.NoResultException;
+
+import org.apache.ranger.biz.RangerPolicyRetriever;
+import org.apache.ranger.common.db.BaseDao;
+import org.apache.ranger.entity.XXPolicyRefAccessType;
+import org.springframework.stereotype.Service;
+
+@Service
+public class XXPolicyRefAccessTypeDao extends BaseDao<XXPolicyRefAccessType> {
+
+	public XXPolicyRefAccessTypeDao(RangerDaoManagerBase daoManager)  {
+		super(daoManager);
+	}
+
+	public List<XXPolicyRefAccessType> findByPolicyId(Long polId) {
+		if(polId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager()
+					.createNamedQuery("XXPolicyRefAccessType.findByPolicyId", tClass)
+					.setParameter("policyId", polId).getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	public List<XXPolicyRefAccessType> findByAccessTypeDefId(Long accessTypeDefId) {
+		if (accessTypeDefId == null) {
+			return Collections.EMPTY_LIST;
+		}
+		try {
+			return getEntityManager().createNamedQuery("XXPolicyRefAccessType.findByAccessTypeDefId", tClass)
+					.setParameter("accessDefId", accessTypeDefId)
+					.getResultList();
+		} catch (NoResultException e) {
+			return Collections.EMPTY_LIST;
+		}
+	}
+
+	@SuppressWarnings("unchecked")
+    public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedAccessNamesByPolicy(Long policyId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (policyId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefAccessType.findUpdatedAccessNamesByPolicy")
+                    .setParameter("policy", policyId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+	@SuppressWarnings("unchecked")
+	public List<RangerPolicyRetriever.PolicyTextNameMap> findUpdatedAccessNamesByService(Long serviceId) {
+        List<RangerPolicyRetriever.PolicyTextNameMap> ret = new ArrayList<>();
+        if (serviceId != null) {
+            List<Object[]> rows = (List<Object[]>) getEntityManager()
+                    .createNamedQuery("XXPolicyRefAccessType.findUpdatedAccessNamesByService")
+                    .setParameter("service", serviceId)
+                    .getResultList();
+            if (rows != null) {
+                for (Object[] row : rows) {
+                    ret.add(new RangerPolicyRetriever.PolicyTextNameMap((Long)row[0], (String)row[1], (String)row[2]));
+                }
+            }
+        }
+        return ret;
+    }
+
+}