This is an automated email from the ASF dual-hosted git repository.

abhay pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ranger.git


The following commit(s) were added to refs/heads/master by this push:
     new c5fab5a  RANGER-2400: policy name needs to be unique within security 
zone and service
c5fab5a is described below

commit c5fab5a84df2b68cc4838bd1da6078ba78466603
Author: Abhay Kulkarni <[email protected]>
AuthorDate: Wed Apr 17 12:25:06 2019 -0700

    RANGER-2400: policy name needs to be unique within security zone and service
---
 .../ranger/plugin/model/RangerSecurityZone.java    |  1 +
 .../model/validation/RangerPolicyValidator.java    | 43 ++++++++++++----------
 .../plugin/model/validation/RangerValidator.java   | 14 ++-----
 .../apache/ranger/plugin/store/ServiceStore.java   |  2 +-
 .../validation/TestRangerPolicyValidator.java      | 12 +++---
 .../optimized/current/ranger_core_db_mysql.sql     |  7 +++-
 .../patches/037-create-security-zone-schema.sql    |  4 +-
 ...40-modify-unique-constraint-on-policy-table.sql | 35 ++++++++++++++++++
 .../optimized/current/ranger_core_db_oracle.sql    |  9 ++++-
 .../patches/037-create-security-zone-schema.sql    |  5 ++-
 ...40-modify-unique-constraint-on-policy-table.sql | 42 +++++++++++++++++++++
 .../optimized/current/ranger_core_db_postgres.sql  |  7 +++-
 .../patches/037-create-security-zone-schema.sql    |  3 +-
 ...40-modify-unique-constraint-on-policy-table.sql | 37 +++++++++++++++++++
 .../current/ranger_core_db_sqlanywhere.sql         |  9 ++++-
 .../patches/037-create-security-zone-schema.sql    |  4 +-
 ...40-modify-unique-constraint-on-policy-table.sql | 33 +++++++++++++++++
 .../optimized/current/ranger_core_db_sqlserver.sql | 13 ++++---
 .../patches/037-create-security-zone-schema.sql    |  4 +-
 ...40-modify-unique-constraint-on-policy-table.sql | 37 +++++++++++++++++++
 .../org/apache/ranger/biz/SecurityZoneDBStore.java |  4 +-
 .../java/org/apache/ranger/biz/ServiceDBStore.java | 29 ++++++++-------
 .../java/org/apache/ranger/db/XXPolicyDao.java     | 20 +++++++---
 .../org/apache/ranger/entity/XXSecurityZone.java   |  2 +-
 .../org/apache/ranger/rest/SecurityZoneREST.java   | 10 +++++
 .../ranger/service/RangerPolicyServiceBase.java    | 41 ++++++++++++++-------
 .../main/resources/META-INF/jpa_named_queries.xml  |  5 ++-
 .../apache/ranger/biz/TestSecurityZoneDBStore.java | 42 ++++++++++-----------
 .../apache/ranger/rest/TestSecurityZoneREST.java   | 14 +++----
 .../service/TestRangerPolicyServiceBase.java       |  2 +
 30 files changed, 372 insertions(+), 118 deletions(-)

diff --git 
a/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerSecurityZone.java
 
b/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerSecurityZone.java
index c3e96bf..98ef6cf 100644
--- 
a/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerSecurityZone.java
+++ 
b/agents-common/src/main/java/org/apache/ranger/plugin/model/RangerSecurityZone.java
@@ -37,6 +37,7 @@ import java.util.Map;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.FIELD)
 public class RangerSecurityZone extends RangerBaseModelObject implements 
java.io.Serializable {
+    public static final long RANGER_UNZONED_SECURITY_ZONE_ID = 1L;
        private static final long serialVersionUID = 1L;
     private String                                  name;
     private Map<String, RangerSecurityZoneService>  services;
diff --git 
a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
 
b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
index 710e75d..54e541d 100644
--- 
a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
+++ 
b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerPolicyValidator.java
@@ -166,10 +166,12 @@ public class RangerPolicyValidator extends 
RangerValidator {
                                        valid = false;
                                }
                        }
-                       String policyName = policy.getName();
+                       String policyName  = policy.getName();
                        String serviceName = policy.getService();
+                       String zoneName    = policy.getZoneName();
 
                        RangerService service = null;
+                       RangerSecurityZone zone = null;
                        boolean serviceNameValid = false;
                        if (StringUtils.isBlank(serviceName)) {
                                ValidationErrorCode error = 
ValidationErrorCode.POLICY_VALIDATION_ERR_MISSING_FIELD;
@@ -196,6 +198,20 @@ public class RangerPolicyValidator extends RangerValidator 
{
                                }
                        }
 
+                       if (StringUtils.isNotEmpty(zoneName)) {
+                               zone = getSecurityZone(zoneName);
+                               if (zone == null) {
+                                       ValidationErrorCode error = 
ValidationErrorCode.POLICY_VALIDATION_ERR_NONEXISTANT_ZONE_NAME;
+                                       failures.add(new 
ValidationFailureDetailsBuilder()
+                                                       .field("zoneName")
+                                                       
.isSemanticallyIncorrect()
+                                                       
.becauseOf(error.getMessage(id, zoneName))
+                                                       
.errorCode(error.getErrorCode())
+                                                       .build());
+                                       valid = false;
+                               }
+                       }
+
                        if (StringUtils.isBlank(policyName)) {
                                ValidationErrorCode error = 
ValidationErrorCode.POLICY_VALIDATION_ERR_MISSING_FIELD;
                                failures.add(new 
ValidationFailureDetailsBuilder()
@@ -206,8 +222,10 @@ public class RangerPolicyValidator extends RangerValidator 
{
                                        .build());
                                valid = false;
                        } else {
-                               if (service != null) {
-                                       Long policyId = 
getPolicyId(service.getId(), policyName);
+                               if (service != null && 
(StringUtils.isEmpty(zoneName) || zone != null)) {
+                                       Long zoneId = zone != null ? 
zone.getId() : RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID;
+                                       Long policyId = 
getPolicyId(service.getId(), policyName, zoneId);
+
                                        if (policyId != null) {
                                                if (action == Action.CREATE) {
                                                        ValidationErrorCode 
error = ValidationErrorCode.POLICY_VALIDATION_ERR_POLICY_NAME_CONFLICT;
@@ -259,32 +277,17 @@ public class RangerPolicyValidator extends 
RangerValidator {
                                }
 
                                String existingZoneName = 
existingPolicy.getZoneName();
-                               String newZoneName = policy.getZoneName();
 
-                               if (!StringUtils.equals(existingZoneName, 
newZoneName)) {
+                               if (!StringUtils.equals(existingZoneName, 
zoneName)) {
                                        ValidationErrorCode error = 
ValidationErrorCode.POLICY_VALIDATION_ERR_UPDATE_ZONE_NAME_NOT_ALLOWED;
                                        failures.add(new 
ValidationFailureDetailsBuilder()
                                                        .field("zoneName")
                                                        
.isSemanticallyIncorrect()
-                                                       
.becauseOf(error.getMessage(id, existingZoneName, newZoneName))
+                                                       
.becauseOf(error.getMessage(id, existingZoneName, zoneName))
                                                        
.errorCode(error.getErrorCode())
                                                        .build());
                                        valid = false;
                                }
-                       } else {
-                               if 
(StringUtils.isNotEmpty(policy.getZoneName())) {
-                                       RangerSecurityZone zone = 
getSecurityZone(policy.getZoneName());
-                                       if (zone == null) {
-                                               ValidationErrorCode error = 
ValidationErrorCode.POLICY_VALIDATION_ERR_NONEXISTANT_ZONE_NAME;
-                                               failures.add(new 
ValidationFailureDetailsBuilder()
-                                                               
.field("zoneName")
-                                                               
.isSemanticallyIncorrect()
-                                                               
.becauseOf(error.getMessage(id, policy.getZoneName()))
-                                                               
.errorCode(error.getErrorCode())
-                                                               .build());
-                                               valid = false;
-                                       }
-                               }
                        }
 
                        boolean          isAuditEnabled   = 
getIsAuditEnabled(policy);
diff --git 
a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java
 
b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java
index fa50ab2..f31483e 100644
--- 
a/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java
+++ 
b/agents-common/src/main/java/org/apache/ranger/plugin/model/validation/RangerValidator.java
@@ -271,21 +271,15 @@ public abstract class RangerValidator {
                return result;
        }
 
-       Long getPolicyId(final Long serviceId, final String policyName) {
+       Long getPolicyId(final Long serviceId, final String policyName, final 
Long zoneId) {
                if(LOG.isDebugEnabled()) {
-                       LOG.debug("==> RangerValidator.getPolicyId(" + 
serviceId + ", " + policyName + ")");
+                       LOG.debug("==> RangerValidator.getPolicyId(" + 
serviceId + ", " + policyName + ", " + zoneId + ")");
                }
 
-               Long policyId = null;
-               try {
-                       policyId = _store.getPolicyId(serviceId, policyName);
-
-               } catch (Exception e) {
-                       LOG.debug("Encountred exception while retrieving 
service from service store!", e);
-               }
+               Long policyId = _store.getPolicyId(serviceId, policyName, 
zoneId);
 
                if(LOG.isDebugEnabled()) {
-                       LOG.debug("<== RangerValidator.getPolicyId(" + 
serviceId + ", " + policyName + "): policy-id[" + policyId + "]");
+                       LOG.debug("<== RangerValidator.getPolicyId(" + 
serviceId + ", " + policyName + ", " + zoneId + "): policy-id[" + policyId + 
"]");
                }
                return policyId;
        }
diff --git 
a/agents-common/src/main/java/org/apache/ranger/plugin/store/ServiceStore.java 
b/agents-common/src/main/java/org/apache/ranger/plugin/store/ServiceStore.java
index 9e37cd5..d487976 100644
--- 
a/agents-common/src/main/java/org/apache/ranger/plugin/store/ServiceStore.java
+++ 
b/agents-common/src/main/java/org/apache/ranger/plugin/store/ServiceStore.java
@@ -75,7 +75,7 @@ public interface ServiceStore {
 
        List<RangerPolicy> getPolicies(SearchFilter filter) throws Exception;
 
-       Long getPolicyId(final Long serviceId, final String policyName);
+       Long getPolicyId(final Long serviceId, final String policyName, final 
Long zoneId);
 
        PList<RangerPolicy> getPaginatedPolicies(SearchFilter filter) throws 
Exception;
 
diff --git 
a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java
 
b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java
index 8cdb9c3..2c1de4e 100644
--- 
a/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java
+++ 
b/agents-common/src/test/java/org/apache/ranger/plugin/model/validation/TestRangerPolicyValidator.java
@@ -36,6 +36,7 @@ import 
org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess;
 import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource;
 import org.apache.ranger.plugin.model.RangerPolicyResourceSignature;
+import org.apache.ranger.plugin.model.RangerSecurityZone;
 import org.apache.ranger.plugin.model.RangerService;
 import org.apache.ranger.plugin.model.RangerServiceDef;
 import org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef;
@@ -252,7 +253,7 @@ public class TestRangerPolicyValidator {
                                        if (action == Action.CREATE) {
                                                
when(_policy.getId()).thenReturn(7L);
                                                
when(_policy.getName()).thenReturn("policy-name-1");
-                                               
when(_store.getPolicyId(service.getId(), _policy.getName())).thenReturn(null);
+                                               
when(_store.getPolicyId(service.getId(), _policy.getName(), 
_zoneId)).thenReturn(null);
                                                Assert.assertTrue("" + action + 
", " + auditEnabled, _validator.isValid(_policy, action, isAdmin, _failures));
                                                
Assert.assertTrue(_failures.isEmpty());
                                        } else {
@@ -263,7 +264,7 @@ public class TestRangerPolicyValidator {
                                                
Assert.assertTrue(_failures.isEmpty());
        
                                                
when(_policy.getName()).thenReturn("policy-name-2");
-                                               
when(_store.getPolicyId(service.getId(), _policy.getName())).thenReturn(null);
+                                               
when(_store.getPolicyId(service.getId(), _policy.getName(), 
_zoneId)).thenReturn(null);
                                                Assert.assertTrue("" + action + 
", " + auditEnabled, _validator.isValid(_policy, action, isAdmin, _failures));
                                                
Assert.assertTrue(_failures.isEmpty());
                                        }
@@ -377,7 +378,7 @@ public class TestRangerPolicyValidator {
                when(existingPolicy.getService()).thenReturn("service-name");
                List<RangerPolicy> existingPolicies = new ArrayList<>();
 
-               when(_store.getPolicyId(service.getId(), 
"policy-name")).thenReturn(7L);
+               when(_store.getPolicyId(service.getId(), "policy-name", 
_zoneId)).thenReturn(7L);
                checkFailure_isValid(Action.CREATE, "semantic", "policy name");
                
                // update : does not exist for id
@@ -392,7 +393,7 @@ public class TestRangerPolicyValidator {
                
when(anotherExistingPolicy.getService()).thenReturn("service-name");
 
                existingPolicies.add(anotherExistingPolicy);
-               when(_store.getPolicyId(service.getId(), 
"policy-name")).thenReturn(8L);
+               when(_store.getPolicyId(service.getId(), "policy-name", 
_zoneId)).thenReturn(8L);
                checkFailure_isValid(Action.UPDATE, "semantic", "id/name");
                
                // policy must have service name on it and it should be valid
@@ -474,7 +475,7 @@ public class TestRangerPolicyValidator {
                
                // create the right service def with right resource defs - this 
is the same as in the happypath test above.
                _serviceDef = 
_utils.createServiceDefWithAccessTypes(accessTypes, "service-type");
-               when(_store.getPolicyId(service.getId(), 
"policy-name")).thenReturn(null);
+               when(_store.getPolicyId(service.getId(), "policy-name", 
_zoneId)).thenReturn(null);
                List<RangerResourceDef> resourceDefs = 
_utils.createResourceDefs(resourceDefData);
                when(_serviceDef.getResources()).thenReturn(resourceDefs);
                
when(_store.getServiceDefByName("service-type")).thenReturn(_serviceDef);
@@ -813,4 +814,5 @@ public class TestRangerPolicyValidator {
        private RangerPolicyValidator _validator;
        private RangerServiceDef _serviceDef;
        private RangerObjectFactory _factory;
+       private Long _zoneId = 
RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID;
 }
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 ef413b6..2cdd8fb 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
@@ -569,6 +569,8 @@ CREATE TABLE IF NOT EXISTS `x_security_zone`(
  CONSTRAINT `x_security_zone_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) 
REFERENCES `x_portal_user` (`id`)
 )ROW_FORMAT=DYNAMIC;
 
+INSERT INTO x_security_zone(id, create_time, update_time, added_by_id, 
upd_by_id, version, name, jsonData, description) VALUES (1, NULL, NULL, 1, 1, 
1, "", "", "Unzoned zone");
+
 CREATE TABLE IF NOT EXISTS `x_ranger_global_state`(
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `create_time` datetime NULL DEFAULT NULL,
@@ -671,7 +673,7 @@ CREATE TABLE  `x_policy` (
 `policy_options` varchar(4000) NULL DEFAULT NULL,
 `policy_priority` int NOT NULL DEFAULT '0',
 `policy_text` MEDIUMTEXT NULL DEFAULT NULL,
-`zone_id` bigint(20) NULL DEFAULT NULL,
+`zone_id` bigint(20) NOT NULL DEFAULT '1',
 primary key (`id`),
 KEY `x_policy_added_by_id` (`added_by_id`),
 KEY `x_policy_upd_by_id` (`upd_by_id`),
@@ -679,7 +681,7 @@ KEY `x_policy_cr_time` (`create_time`),
 KEY `x_policy_up_time` (`update_time`),
 KEY `x_policy_service` (`service`),
 KEY `x_policy_resource_signature` (`resource_signature`),
-UNIQUE KEY `x_policy_UK_name_service` (`name`(180),`service`),
+UNIQUE KEY `x_policy_UK_name_service_zone` (`name`(180),`service`, `zone_id`),
 CONSTRAINT `x_policy_FK_added_by_id` FOREIGN KEY (`added_by_id`) REFERENCES 
`x_portal_user` (`id`),
 CONSTRAINT `x_policy_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) REFERENCES 
`x_portal_user` (`id`),
 CONSTRAINT `x_policy_FK_service` FOREIGN KEY (`service`) REFERENCES 
`x_service` (`id`),
@@ -1557,6 +1559,7 @@ 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 
('037',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 
('038',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 
('039',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 
('040',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 
('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)
diff --git 
a/security-admin/db/mysql/patches/037-create-security-zone-schema.sql 
b/security-admin/db/mysql/patches/037-create-security-zone-schema.sql
index a50ec0e..b2b69f0 100644
--- a/security-admin/db/mysql/patches/037-create-security-zone-schema.sql
+++ b/security-admin/db/mysql/patches/037-create-security-zone-schema.sql
@@ -78,6 +78,8 @@ CREATE TABLE IF NOT EXISTS `x_security_zone`(
  CONSTRAINT `x_security_zone_FK_upd_by_id` FOREIGN KEY (`upd_by_id`) 
REFERENCES `x_portal_user` (`id`)
 )ROW_FORMAT=DYNAMIC;
 
+INSERT INTO x_security_zone(id, create_time, update_time, added_by_id, 
upd_by_id, version, name, jsonData, description) VALUES (1, NULL, NULL, 1, 1, 
1, "", "", "Unzoned zone");
+
 CREATE TABLE IF NOT EXISTS `x_ranger_global_state`(
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `create_time` datetime NULL DEFAULT NULL,
@@ -184,7 +186,7 @@ create procedure add_x_policy_zone_id() 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 = 
'zone_id') then
-    ALTER TABLE `x_policy` ADD COLUMN `zone_id` bigint(20) DEFAULT NULL 
NULL,ADD CONSTRAINT `x_policy_FK_zone_id` FOREIGN KEY(`zone_id`) REFERENCES 
`x_security_zone`(`id`);
+    ALTER TABLE `x_policy` ADD COLUMN `zone_id` bigint(20) DEFAULT 1 NOT 
NULL,ADD CONSTRAINT `x_policy_FK_zone_id` FOREIGN KEY(`zone_id`) REFERENCES 
`x_security_zone`(`id`);
   end if;
  end if;
 end;;
diff --git 
a/security-admin/db/mysql/patches/040-modify-unique-constraint-on-policy-table.sql
 
b/security-admin/db/mysql/patches/040-modify-unique-constraint-on-policy-table.sql
new file mode 100644
index 0000000..a709eb7
--- /dev/null
+++ 
b/security-admin/db/mysql/patches/040-modify-unique-constraint-on-policy-table.sql
@@ -0,0 +1,35 @@
+-- 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 create_unique_constraint_on_name_service_zone;
+
+delimiter ;;
+create procedure create_unique_constraint_on_name_service_zone() begin
+ /* check tables exist or not */
+       if exists (select * from information_schema.columns where 
table_schema=database() and table_name = 'x_policy' and column_name 
in('service','name','zone_id')) then
+               /* check unique constraint exist on service and name column or 
not */
+               if exists (select * from information_schema.table_constraints 
where table_schema=database() and table_name = 'x_policy' and 
constraint_name='x_policy_UK_name_service') then
+                       ALTER TABLE x_policy DROP INDEX 
x_policy_UK_name_service;
+               end if;
+               if not exists (select * from 
information_schema.table_constraints where table_schema=database() and 
table_name = 'x_policy' and constraint_name='x_policy_UK_name_service_zone') 
then
+                       ALTER TABLE x_policy ADD UNIQUE INDEX 
x_policy_UK_name_service_zone(name(180),service,zone_id);
+               end if;
+       end if;
+end;;
+
+delimiter ;
+call create_unique_constraint_on_name_service_zone();
+
+drop procedure if exists create_unique_constraint_on_name_service_zone;
\ No newline at end of file
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 0838bac..88fa98a 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
@@ -654,6 +654,10 @@ CONSTRAINT x_security_zone_FK_upd_by_id FOREIGN KEY 
(upd_by_id) REFERENCES x_por
 );
 commit;
 
+INSERT INTO x_security_zone(id, create_time, update_time, added_by_id, 
upd_by_id, version, name, jsonData, description) VALUES 
(X_SECURITY_ZONE_SEQ.NEXTVAL, NULL, NULL, 1, 1, 1, "", "", "Unzoned zone");
+
+commit;
+
 CREATE TABLE x_ranger_global_state(
 id NUMBER(20) NOT NULL,
 create_time DATE DEFAULT NULL NULL,
@@ -761,9 +765,9 @@ 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,
-zone_id NUMBER(20) DEFAULT NULL NULL,
+zone_id NUMBER(20) DEFAULT '1' NOT NULL,
 primary key (id),
-CONSTRAINT x_policy_UK_name_service UNIQUE (name,service),
+CONSTRAINT x_policy_UK_name_service_zone UNIQUE (name,service,zone_id),
 CONSTRAINT x_policy_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES 
x_portal_user (id),
 CONSTRAINT x_policy_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES 
x_portal_user (id),
 CONSTRAINT x_policy_FK_service FOREIGN KEY (service) REFERENCES x_service (id),
@@ -1727,6 +1731,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, '037',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, '038',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, '039',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, '040',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,getXportalUIdByLoginId('admin'),getModulesIdByName('Reports'),sys_extract_utc(systimestamp),sys_extract_utc(systimestamp),getXportalUIdByLoginId('admin'),getXportalUIdByLoginId('admin'),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,getXportalUIdByLoginId('admin'),getModulesIdByName('Resource
 Based 
Policies'),sys_extract_utc(systimestamp),sys_extract_utc(systimestamp),getXportalUIdByLoginId('admin'),getXportalUIdByLoginId('admin'),1);
diff --git 
a/security-admin/db/oracle/patches/037-create-security-zone-schema.sql 
b/security-admin/db/oracle/patches/037-create-security-zone-schema.sql
index 354c74d..9b69314 100644
--- a/security-admin/db/oracle/patches/037-create-security-zone-schema.sql
+++ b/security-admin/db/oracle/patches/037-create-security-zone-schema.sql
@@ -96,8 +96,11 @@ CONSTRAINT x_security_zone_UK_name UNIQUE(name),
 CONSTRAINT x_security_zone_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES 
x_portal_user (id),
 CONSTRAINT x_security_zone_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES 
x_portal_user (id)
 );
+commit;
 
+INSERT INTO x_security_zone(id, create_time, update_time, added_by_id, 
upd_by_id, version, name, jsonData, description) VALUES 
(X_SECURITY_ZONE_SEQ.NEXTVAL, NULL, NULL, 1, 1, 1, "", "", "Unzoned zone");
 commit;
+
 CREATE TABLE x_ranger_global_state(
 id NUMBER(20) NOT NULL,
 create_time DATE DEFAULT NULL NULL,
@@ -207,7 +210,7 @@ DECLARE
 BEGIN
 Select count(*) into v_column_exists from user_tab_cols where column_name = 
upper('zone_id') and table_name = upper('x_policy');
        if (v_column_exists = 0) then
-               execute immediate 'ALTER TABLE x_policy ADD (zone_id NUMBER(20) 
DEFAULT NULL NULL) ADD CONSTRAINT x_policy_FK_zone_id FOREIGN KEY (zone_id) 
REFERENCES x_security_zone (id)';
+               execute immediate 'ALTER TABLE x_policy ADD (zone_id NUMBER(20) 
DEFAULT 1 NOT NULL) ADD CONSTRAINT x_policy_FK_zone_id FOREIGN KEY (zone_id) 
REFERENCES x_security_zone (id)';
                commit;
        end if;
 end;/
diff --git 
a/security-admin/db/oracle/patches/040-modify-unique-constraint-on-policy-table.sql
 
b/security-admin/db/oracle/patches/040-modify-unique-constraint-on-policy-table.sql
new file mode 100644
index 0000000..82b2d61
--- /dev/null
+++ 
b/security-admin/db/oracle/patches/040-modify-unique-constraint-on-policy-table.sql
@@ -0,0 +1,42 @@
+-- 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_POLICY' and column_name IN('NAME','SERVICE','ZONE_ID');
+       if (v_count = 3) THEN
+               v_count:=0;
+               select count(*) into v_count from user_constraints where 
table_name='X_POLICY' and constraint_name='X_POLICY_UK_NAME_SERVICE' and 
constraint_type='U';
+               if (v_count = 1) THEN
+                       v_count:=0;
+                       select count(*) into v_count from user_ind_columns 
WHERE table_name='X_POLICY' and column_name IN('NAME','SERVICE') and 
index_name='X_POLICY_UK_NAME_SERVICE';
+                       if (v_count = 2) THEN
+                               execute immediate 'ALTER TABLE X_POLICY DROP 
CONSTRAINT x_policy_UK_name_service';
+                       end if;
+                       commit;
+                       v_count:=0;
+                       select count(*) into v_count from user_constraints 
where table_name='X_POLICY' and constraint_name='X_POLICY_UK_NAME_SERVICE_ZONE' 
and constraint_type='U';
+                       if (v_count = 0) THEN
+                               v_count:=0;
+                               select count(*) into v_count from 
user_ind_columns WHERE table_name='X_POLICY' and column_name 
IN('NAME','SERVICE','ZONE_ID') and index_name='X_POLICY_UK_NAME_SERVICE_ZONE';
+                               if (v_count = 0) THEN
+                                       execute immediate 'ALTER TABLE X_POLICY 
ADD CONSTRAINT x_policy_UK_name_service_zone UNIQUE (NAME,SERVICE,ZONE_ID)';
+                               end if;
+                               commit;
+                       end if;
+               end if;
+       end if;
+END;/
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 3ed9e75..0ae7147 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
@@ -560,6 +560,8 @@ CONSTRAINT x_security_zone_FK_added_by_id FOREIGN KEY 
(added_by_id) REFERENCES x
 CONSTRAINT x_security_zone_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES 
x_portal_user (id)
 );
 
+INSERT INTO x_security_zone(create_time, update_time, added_by_id, upd_by_id, 
version, name, jsonData, description) VALUES (NULL, NULL, 1, 1, 1, "", "", 
"Unzoned zone");
+
 CREATE SEQUENCE x_ranger_global_state_seq;
 CREATE TABLE x_ranger_global_state (
 id BIGINT DEFAULT nextval('x_ranger_global_state_seq'::regclass),
@@ -595,9 +597,9 @@ 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,
-zone_id BIGINT DEFAULT NULL NULL,
+zone_id BIGINT DEFAULT '1' NOT NULL,
 primary key(id),
-CONSTRAINT x_policy_uk_name_service UNIQUE(name,service),
+CONSTRAINT x_policy_uk_name_service_zone UNIQUE(name,service,zone_id),
 CONSTRAINT x_policy_FK_added_by_id FOREIGN KEY(added_by_id) REFERENCES 
x_portal_user(id),
 CONSTRAINT x_policy_FK_upd_by_id FOREIGN KEY(upd_by_id) REFERENCES 
x_portal_user(id),
 CONSTRAINT x_policy_FK_service FOREIGN KEY(service) REFERENCES x_service(id),
@@ -1652,6 +1654,7 @@ 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 
('037',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 
('038',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 
('039',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 
('040',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
diff --git 
a/security-admin/db/postgres/patches/037-create-security-zone-schema.sql 
b/security-admin/db/postgres/patches/037-create-security-zone-schema.sql
index 434231d..8121330 100644
--- a/security-admin/db/postgres/patches/037-create-security-zone-schema.sql
+++ b/security-admin/db/postgres/patches/037-create-security-zone-schema.sql
@@ -93,6 +93,7 @@ CONSTRAINT x_security_zone_UK_name UNIQUE (name),
 CONSTRAINT x_security_zone_FK_added_by_id FOREIGN KEY (added_by_id) REFERENCES 
x_portal_user (id),
 CONSTRAINT x_security_zone_FK_upd_by_id FOREIGN KEY (upd_by_id) REFERENCES 
x_portal_user (id)
 );
+INSERT INTO x_security_zone(create_time, update_time, added_by_id, upd_by_id, 
version, name, jsonData, description) VALUES (NULL, NULL, 1, 1, 1, "", "", 
"Unzoned zone");
 
 CREATE SEQUENCE x_ranger_global_state_seq;
 CREATE TABLE x_ranger_global_state (
@@ -208,7 +209,7 @@ DECLARE
 BEGIN
   select count(*) into v_column_exists from pg_attribute where attrelid 
in(select oid from pg_class where relname='x_policy') and attname='zone_id';
    IF v_column_exists = 0 THEN
-     ALTER TABLE x_policy ADD COLUMN zone_id BIGINT DEFAULT NULL NULL,ADD 
CONSTRAINT x_policy_FK_zone_id FOREIGN KEY(zone_id) REFERENCES 
x_security_zone(id);
+     ALTER TABLE x_policy ADD COLUMN zone_id BIGINT DEFAULT 1 NOT NULL,ADD 
CONSTRAINT x_policy_FK_zone_id FOREIGN KEY(zone_id) REFERENCES 
x_security_zone(id);
    END IF;
 END;
 $$ LANGUAGE plpgsql;
diff --git 
a/security-admin/db/postgres/patches/040-modify-unique-constraint-on-policy-table.sql
 
b/security-admin/db/postgres/patches/040-modify-unique-constraint-on-policy-table.sql
new file mode 100644
index 0000000..eff5aa3
--- /dev/null
+++ 
b/security-admin/db/postgres/patches/040-modify-unique-constraint-on-policy-table.sql
@@ -0,0 +1,37 @@
+-- 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.
+
+select 'delimiter start';
+CREATE OR REPLACE FUNCTION modify_unique_constraint_on_policyname()
+RETURNS void AS $$
+DECLARE
+       v_attnum integer := 0;
+BEGIN
+       select attnum into v_attnum from pg_attribute where attrelid in(select 
oid from pg_class where relname='x_policy') and attname in('name');
+       IF v_attnum > 0 THEN
+               IF exists (select * from pg_constraint where conrelid in(select 
oid from pg_class where relname='x_policy') and 
conname='x_policy_uk_name_service' and contype='u') THEN
+                       ALTER TABLE x_policy DROP CONSTRAINT 
x_policy_uk_name_service;
+               END IF;
+               IF not exists (select * from pg_constraint where conrelid 
in(select oid from pg_class where relname='x_policy') and 
conname='x_policy_uk_name_service_zone' and contype='u') THEN
+                       IF not exists (select * from pg_index where indrelid 
in(select oid from pg_class where relname='x_policy') and indkey[0]=v_attnum) 
THEN
+                               ALTER TABLE x_policy ADD CONSTRAINT 
x_policy_uk_name_service_zone UNIQUE(name,service,zone_id);
+                       END IF;
+               END IF;
+       END IF;
+
+END;
+$$ LANGUAGE plpgsql;
+select modify_unique_constraint_on_policyname();
+select 'delimiter end';
\ No newline at end of file
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 e82f43e..ea0ff2b 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
@@ -517,6 +517,9 @@ CREATE TABLE dbo.x_security_zone(
        CONSTRAINT x_security_zone_UK_name UNIQUE NONCLUSTERED(name)
 )
 GO
+INSERT INTO x_security_zone(create_time, update_time, added_by_id, upd_by_id, 
version, name, jsonData, description) VALUES (NULL, NULL, 1, 1, 1, "", "", 
"Unzoned zone");
+GO
+
 CREATE TABLE dbo.x_ranger_global_state(
        id bigint IDENTITY NOT NULL,
        create_time datetime DEFAULT NULL NULL,
@@ -548,9 +551,9 @@ create table dbo.x_policy (
        policy_options varchar(4000) DEFAULT NULL NULL,
        policy_priority int DEFAULT 0 NOT NULL,
        policy_text text DEFAULT NULL NULL,
-       zone_id bigint DEFAULT NULL NULL,
+       zone_id bigint DEFAULT '1' NOT NULL,
        CONSTRAINT x_policy_PK_id PRIMARY KEY CLUSTERED(id),
-       CONSTRAINT x_policy_UK_name_service UNIQUE NONCLUSTERED (name,service)
+       CONSTRAINT x_policy_UK_name_service_zone UNIQUE NONCLUSTERED 
(name,service,zone_id)
 )
 GO
 create table dbo.x_service_config_def (
@@ -1996,6 +1999,8 @@ 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 
('039',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 
('040',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 
(dbo.getXportalUIdByLoginId('admin'),dbo.getModulesIdByName('Reports'),CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,dbo.getXportalUIdByLoginId('admin'),dbo.getXportalUIdByLoginId('admin'),1);
diff --git 
a/security-admin/db/sqlanywhere/patches/037-create-security-zone-schema.sql 
b/security-admin/db/sqlanywhere/patches/037-create-security-zone-schema.sql
index 893d453..e4bfb78 100644
--- a/security-admin/db/sqlanywhere/patches/037-create-security-zone-schema.sql
+++ b/security-admin/db/sqlanywhere/patches/037-create-security-zone-schema.sql
@@ -72,6 +72,8 @@ ALTER TABLE dbo.x_security_zone ADD CONSTRAINT 
x_security_zone_FK_added_by_id FO
 GO
 ALTER TABLE dbo.x_security_zone ADD CONSTRAINT x_security_zone_FK_upd_by_id 
FOREIGN KEY(upd_by_id) REFERENCES dbo.x_portal_user (id)
 GO
+INSERT INTO x_security_zone(create_time, update_time, added_by_id, upd_by_id, 
version, name, jsonData, description) VALUES (NULL, NULL, 1, 1, 1, "", "", 
"Unzoned zone");
+GO
 CREATE TABLE dbo.x_ranger_global_state(
        id bigint IDENTITY NOT NULL,
        create_time datetime DEFAULT NULL NULL,
@@ -205,7 +207,7 @@ GO
 ALTER TABLE dbo.x_security_zone_ref_group ADD CONSTRAINT 
x_sz_ref_agrp_FK_group_id FOREIGN KEY(group_id) REFERENCES dbo.x_group (id)
 GO
 IF NOT EXISTS(select * from SYS.SYSCOLUMNS where tname = 'x_policy' and 
cname='zone_id') THEN
-       ALTER TABLE dbo.x_policy ADD (zone_id bigint DEFAULT NULL NULL), ADD 
CONSTRAINT x_policy_FK_zone_id FOREIGN KEY(zone_id) REFERENCES 
dbo.x_security_zone (id);
+       ALTER TABLE dbo.x_policy ADD (zone_id bigint DEFAULT 1 NOT NULL), ADD 
CONSTRAINT x_policy_FK_zone_id FOREIGN KEY(zone_id) REFERENCES 
dbo.x_security_zone (id);
 END IF;
 GO
 
diff --git 
a/security-admin/db/sqlanywhere/patches/040-modify-unique-constraint-on-policy-table.sql
 
b/security-admin/db/sqlanywhere/patches/040-modify-unique-constraint-on-policy-table.sql
new file mode 100644
index 0000000..f8174fc
--- /dev/null
+++ 
b/security-admin/db/sqlanywhere/patches/040-modify-unique-constraint-on-policy-table.sql
@@ -0,0 +1,33 @@
+-- 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.
+BEGIN
+DECLARE tableID INT = 0;
+DECLARE columnID INT = 0;
+DECLARE guTableID INT = 0;
+DECLARE guColumnID INT = 0;
+       IF EXISTS(select * from SYS.SYSCOLUMNS where tname = 'x_policy' and 
cname='name') THEN
+               IF EXISTS(select * from SYS.SYSCONSTRAINT where constraint_name 
= 'x_policy_UK_name_service') THEN
+                       select table_id into tableID from SYS.SYSTAB where 
table_name = 'x_policy';
+                       select column_id into columnID from SYS.SYSTABCOL where 
table_id=tableID and column_name = 'name';
+                       IF EXISTS(select * from SYS.SYSIDXCOL where 
table_id=tableID and column_id=columnID) THEN
+                               ALTER TABLE dbo.x_policy DROP CONSTRAINT 
x_policy_UK_name_service;
+                       END IF;
+                       IF NOT EXISTS(select * from SYS.SYSCONSTRAINT where 
constraint_name = 'x_policy_UK_name_service_zone') THEN
+                               ALTER TABLE dbo.x_policy ADD CONSTRAINT 
x_policy_UK_name_service_zone UNIQUE NONCLUSTERED (name,service,zone_id);
+                       END IF;
+               END IF;
+       END IF;
+END
+GO
\ No newline at end of file
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 281de40..d451709 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
@@ -505,9 +505,9 @@ IF (OBJECT_ID('x_plugin_info_UK') IS NOT NULL)
 BEGIN
     ALTER TABLE [dbo].[x_plugin_info] DROP CONSTRAINT x_plugin_info_UK
 END
-IF (OBJECT_ID('x_policy$x_policy_UK_name_service') IS NOT NULL)
+IF (OBJECT_ID('x_policy$x_policy_UK_name_service_zone') IS NOT NULL)
 BEGIN
-    ALTER TABLE [dbo].[x_policy] DROP CONSTRAINT 
x_policy$x_policy_UK_name_service
+    ALTER TABLE [dbo].[x_policy] DROP CONSTRAINT 
x_policy$x_policy_UK_name_service_zone
 END
 IF (OBJECT_ID('x_sz_ref_admin_group_FK_added_by_id') IS NOT NULL)
 BEGIN
@@ -1383,6 +1383,8 @@ CONSTRAINT [x_security_zone$x_security_zone_UK_name] 
UNIQUE NONCLUSTERED
 )WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = 
OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 ) ON [PRIMARY]
 GO
+INSERT INTO x_security_zone(create_time, update_time, added_by_id, upd_by_id, 
version, name, jsonData, description) VALUES (NULL, NULL, 1, 1, 1, "", "", 
"Unzoned zone");
+GO
 SET ANSI_NULLS ON
 SET QUOTED_IDENTIFIER ON
 SET ANSI_PADDING ON
@@ -1426,14 +1428,14 @@ CREATE TABLE [dbo].[x_policy] (
         [policy_options] [varchar](4000) DEFAULT NULL NULL,
         [policy_priority] [int] DEFAULT 0 NOT NULL,
                [policy_text] [nvarchar](max) DEFAULT NULL NULL,
-               [zone_id] [bigint] DEFAULT NULL NULL,
+               [zone_id] [bigint] DEFAULT 1 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],
-CONSTRAINT [x_policy$x_policy_UK_name_service] UNIQUE NONCLUSTERED
+CONSTRAINT [x_policy$x_policy_UK_name_service_zone] UNIQUE NONCLUSTERED
 (
-        [name] ASC, [service] ASC
+        [name] ASC, [service] ASC, [zone_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
@@ -3680,6 +3682,7 @@ 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 
('037',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 
('038',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 
('039',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 
('040',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 
(dbo.getXportalUIdByLoginId('admin'),dbo.getModulesIdByName('Reports'),CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,dbo.getXportalUIdByLoginId('admin'),dbo.getXportalUIdByLoginId('admin'),1);
 INSERT INTO x_user_module_perm 
(user_id,module_id,create_time,update_time,added_by_id,upd_by_id,is_allowed) 
VALUES (dbo.getXportalUIdByLoginId('admin'),dbo.getModulesIdByName('Resource 
Based 
Policies'),CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,dbo.getXportalUIdByLoginId('admin'),dbo.getXportalUIdByLoginId('admin'),1);
diff --git 
a/security-admin/db/sqlserver/patches/037-create-security-zone-schema.sql 
b/security-admin/db/sqlserver/patches/037-create-security-zone-schema.sql
index a610b70..be0287c 100644
--- a/security-admin/db/sqlserver/patches/037-create-security-zone-schema.sql
+++ b/security-admin/db/sqlserver/patches/037-create-security-zone-schema.sql
@@ -212,6 +212,8 @@ CONSTRAINT [x_security_zone$x_security_zone_UK_name] UNIQUE 
NONCLUSTERED
 )WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = 
OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 ) ON [PRIMARY]
 GO
+INSERT INTO x_security_zone(create_time, update_time, added_by_id, upd_by_id, 
version, name, jsonData, description) VALUES (NULL, NULL, 1, 1, 1, "", "", 
"Unzoned zone");
+GO
 CREATE TABLE [dbo].[x_ranger_global_state](
        [id] [bigint] IDENTITY(1,1) NOT NULL,
        [create_time] [datetime2] DEFAULT NULL NULL,
@@ -373,7 +375,7 @@ ALTER TABLE [dbo].[x_ranger_global_state] WITH CHECK ADD 
CONSTRAINT [x_ranger_gl
 GO
 IF NOT EXISTS(select * from INFORMATION_SCHEMA.columns where table_name = 
'x_policy' and column_name in('zone_id'))
 BEGIN
-       ALTER TABLE [dbo].[x_policy] ADD [zone_id] [bigint] DEFAULT NULL NULL;
+       ALTER TABLE [dbo].[x_policy] ADD [zone_id] [bigint] DEFAULT 1 NOT NULL;
 END
 GO
 IF (OBJECT_ID('x_policy_FK_zone_id') IS NULL)
diff --git 
a/security-admin/db/sqlserver/patches/040-modify-unique-constraint-on-policy-table.sql
 
b/security-admin/db/sqlserver/patches/040-modify-unique-constraint-on-policy-table.sql
new file mode 100644
index 0000000..4362f58
--- /dev/null
+++ 
b/security-admin/db/sqlserver/patches/040-modify-unique-constraint-on-policy-table.sql
@@ -0,0 +1,37 @@
+
+
+-- 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 EXISTS(select * from INFORMATION_SCHEMA.columns where table_name = 
'x_policy' and column_name = 'name')
+BEGIN
+       IF EXISTS(select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
where table_name='x_policy' and column_name='name' and constraint_name = 
'x_policy$x_policy_UK_name_service')
+       BEGIN
+               IF EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
where table_name='x_policy' and constraint_name = 
'x_policy$x_policy_UK_name_service' and CONSTRAINT_TYPE='UNIQUE')
+               BEGIN
+                       ALTER TABLE [dbo].[x_policy] DROP CONSTRAINT 
[x_policy$x_policy_UK_name_service];
+               END
+       END
+       IF NOT EXISTS(select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
where table_name='x_policy' and column_name='name' and constraint_name = 
'x_policy$x_policy_UK_name_service_zone')
+       BEGIN
+               IF NOT EXISTS(select * from 
INFORMATION_SCHEMA.TABLE_CONSTRAINTS where table_name='x_policy' and 
constraint_name = 'x_policy$x_policy_UK_name_service_zone' and 
CONSTRAINT_TYPE='UNIQUE')
+               BEGIN
+                       ALTER TABLE [dbo].[x_policy] ADD CONSTRAINT 
[x_policy$x_policy_UK_name_service_zone] UNIQUE ([name],[service],[zone_id]);
+               END
+       END
+END
+GO
+exit
\ No newline at end of file
diff --git 
a/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java 
b/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java
index 5499ea7..12ad7e6 100644
--- 
a/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java
+++ 
b/security-admin/src/main/java/org/apache/ranger/biz/SecurityZoneDBStore.java
@@ -178,7 +178,9 @@ public class SecurityZoneDBStore implements 
SecurityZoneStore {
         List<XXSecurityZone> xxSecurityZones = 
daoMgr.getXXSecurityZoneDao().getAll();
 
         for (XXSecurityZone xxSecurityZone : xxSecurityZones) {
-            ret.add(securityZoneService.read(xxSecurityZone.getId()));
+            if 
(!xxSecurityZone.getId().equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID))
 {
+                ret.add(securityZoneService.read(xxSecurityZone.getId()));
+            }
         }
 
         if (CollectionUtils.isNotEmpty(ret) && filter != null && 
!filter.isEmpty()) {
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 1d341c5..17be098 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
@@ -335,6 +335,7 @@ public class ServiceDBStore extends AbstractServiceStore {
                                                                
getServiceUpgraded();
                                                                
createGenericUsers();
                                                                
resetPolicyUpdateLog(RETENTION_PERIOD_IN_DAYS, false);
+                                                               
//createUnzonedSecurityZone();
                                                                return null;
                                                        }
                                                });
@@ -1846,7 +1847,17 @@ public class ServiceDBStore extends AbstractServiceStore 
{
                        throw new Exception("service-def does not exist - 
name=" + service.getType());
                }
 
-               XXPolicy existing = 
daoMgr.getXXPolicy().findByNameAndServiceId(policy.getName(), service.getId());
+               Long   zoneId   = 
RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID;
+               String zoneName = policy.getZoneName();
+               if (StringUtils.isNotEmpty(zoneName)) {
+                       RangerSecurityZone zone = getSecurityZone(zoneName);
+                       if (zone == null) {
+                               throw new Exception("zone does not exist - 
name=" + zoneName);
+                       } else {
+                               zoneId = zone.getId();
+                       }
+               }
+               XXPolicy existing = 
daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policy.getName(), 
service.getId(), zoneId);
 
                if(existing != null) {
                        throw new Exception("policy already exists: 
ServiceName=" + policy.getService() + "; PolicyName=" + policy.getName() + ". 
ID=" + existing.getId());
@@ -1950,7 +1961,7 @@ public class ServiceDBStore extends AbstractServiceStore {
                boolean renamed = 
!StringUtils.equalsIgnoreCase(policy.getName(), existing.getName());
 
                if(renamed) {
-                       XXPolicy newNamePolicy = 
daoMgr.getXXPolicy().findByNameAndServiceId(policy.getName(), service.getId());
+                       XXPolicy newNamePolicy = 
daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policy.getName(), 
service.getId(), xxExisting.getZoneId());
 
                        if(newNamePolicy != null) {
                                throw new Exception("another policy already 
exists with name '" + policy.getName() + "'. ID=" + newNamePolicy.getId());
@@ -2046,12 +2057,12 @@ public class ServiceDBStore extends 
AbstractServiceStore {
        }
 
        @Override
-       public Long getPolicyId(final Long serviceId, final String policyName) {
+       public Long getPolicyId(final Long serviceId, final String policyName, 
final Long zoneId) {
                if(LOG.isDebugEnabled()) {
                        LOG.debug("==> ServiceDBStore.getPolicyId()");
                }
                Long ret = null;
-               XXPolicy xxPolicy = 
daoMgr.getXXPolicy().findByNameAndServiceId(policyName, serviceId);
+               XXPolicy xxPolicy = 
daoMgr.getXXPolicy().findByNameAndServiceIdAndZoneId(policyName, serviceId, 
zoneId);
                if (xxPolicy != null) {
                        ret = xxPolicy.getId();
                }
@@ -2840,19 +2851,9 @@ public class ServiceDBStore extends AbstractServiceStore 
{
                                        if 
(CollectionUtils.isNotEmpty(defaultPolicies)) {
 
                                                String zoneName = 
zone.getName();
-                                               XXPolicyDao policyDao = 
daoMgr.getXXPolicy();
 
                                                for (RangerPolicy defaultPolicy 
: defaultPolicies) {
 
-                                                       String policyName;
-                                                       String 
zonePolicyNamePrefix = zoneName + "-" + defaultPolicy.getName() + "-";
-                                                       int i = -1;
-
-                                                       do {
-                                                               policyName = 
zonePolicyNamePrefix + ++i;
-                                                       } while 
(policyDao.findByNameAndServiceId(policyName, service.getId()) != null);
-
-                                                       
defaultPolicy.setName(policyName);
                                                        
defaultPolicy.setZoneName(zoneName);
 
                                                        
createPolicy(defaultPolicy);
diff --git a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java 
b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java
index 2a870ef..6cb85f9 100644
--- a/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java
+++ b/security-admin/src/main/java/org/apache/ranger/db/XXPolicyDao.java
@@ -24,6 +24,7 @@ import javax.persistence.NoResultException;
 
 import org.apache.ranger.common.db.BaseDao;
 import org.apache.ranger.entity.XXPolicy;
+import org.apache.ranger.plugin.model.RangerSecurityZone;
 import org.apache.solr.common.StringUtils;
 import org.springframework.stereotype.Service;
 
@@ -40,18 +41,27 @@ public class XXPolicyDao extends BaseDao<XXPolicy> {
        }
 
        public XXPolicy findByNameAndServiceId(String polName, Long serviceId) {
+               return findByNameAndServiceIdAndZoneId(polName, serviceId, 
RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID);
+       }
+
+       public XXPolicy findByNameAndServiceIdAndZoneId(String polName, Long 
serviceId, Long zoneId) {
                if (polName == null || serviceId == null) {
                        return null;
                }
+
+               XXPolicy ret;
+
                try {
-                       XXPolicy xPol = getEntityManager()
-                                       
.createNamedQuery("XXPolicy.findByNameAndServiceId", tClass)
-                                       .setParameter("polName", 
polName).setParameter("serviceId", serviceId)
+                       ret = getEntityManager()
+                                       
.createNamedQuery("XXPolicy.findByNameAndServiceIdAndZoneId", tClass)
+                                       .setParameter("polName", 
polName).setParameter("serviceId", serviceId).setParameter("zoneId", zoneId)
                                        .getSingleResult();
-                       return xPol;
+
                } catch (NoResultException e) {
-                       return null;
+                       ret = null;
                }
+
+               return ret;
        }
 
        public List<XXPolicy> findByServiceId(Long serviceId) {
diff --git 
a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java 
b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java
index eccff5f..2b3ce56 100644
--- a/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java
+++ b/security-admin/src/main/java/org/apache/ranger/entity/XXSecurityZone.java
@@ -35,7 +35,7 @@ import java.util.Objects;
 public class XXSecurityZone extends XXSecurityZoneBase implements 
java.io.Serializable {
     private static final long serialVersionUID = 1L;
     @Id
-    @SequenceGenerator(name = "x_security_zone_SEQ", sequenceName = 
"x_security_zone_SEQ", allocationSize = 1)
+    @SequenceGenerator(name = "x_security_zone_SEQ", sequenceName = 
"x_security_zone_SEQ", initialValue = 1, allocationSize = 1)
     @GeneratedValue(strategy = GenerationType.AUTO, generator = 
"x_security_zone_SEQ")
     @Column(name = "id")
     protected Long id;
diff --git 
a/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java 
b/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java
index 3c1b1d2..6ce5365 100644
--- a/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java
+++ b/security-admin/src/main/java/org/apache/ranger/rest/SecurityZoneREST.java
@@ -120,6 +120,10 @@ public class SecurityZoneREST {
             LOG.debug("==> updateSecurityZone(id=" + zoneId +", " + 
securityZone + ")");
         }
 
+        if (zoneId != null && 
zoneId.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) {
+            throw restErrorUtil.createRESTException("Cannot update unzoned 
zone");
+        }
+
         ensureAdminAccess();
         removeEmptyEntries(securityZone);
         if (securityZone.getId() != null && 
!zoneId.equals(securityZone.getId())) {
@@ -174,6 +178,9 @@ public class SecurityZoneREST {
         if (LOG.isDebugEnabled()) {
             LOG.debug("==> deleteSecurityZone(id=" + zoneId + ")");
         }
+        if (zoneId != null && 
zoneId.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) {
+            throw restErrorUtil.createRESTException("Cannot delete unzoned 
zone");
+        }
         try {
                ensureAdminAccess();
             RangerSecurityZoneValidator validator = 
validatorFactory.getSecurityZoneValidator(svcStore, securityZoneStore);
@@ -219,6 +226,9 @@ public class SecurityZoneREST {
         if (LOG.isDebugEnabled()) {
             LOG.debug("==> getSecurityZone(id=" + id + ")");
         }
+        if (id != null && 
id.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) {
+            throw restErrorUtil.createRESTException("Cannot delete unzoned 
zone");
+        }
         RangerSecurityZone ret;
         try {
             ret = securityZoneStore.getSecurityZone(id);
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 c18759a..8dfbf41 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
@@ -30,6 +30,7 @@ import org.apache.ranger.entity.XXPolicyBase;
 import org.apache.ranger.entity.XXSecurityZone;
 import org.apache.ranger.entity.XXService;
 import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerSecurityZone;
 import org.apache.ranger.plugin.util.SearchFilter;
 import org.springframework.beans.factory.annotation.Autowired;
 
@@ -109,7 +110,7 @@ public abstract class RangerPolicyServiceBase<T extends 
XXPolicyBase, V extends
                xObj.setResourceSignature(vObj.getResourceSignature());
                xObj.setIsAuditEnabled(vObj.getIsAuditEnabled());
                xObj.setIsEnabled(vObj.getIsEnabled());
-               Long zoneId = convertZoneNameToZoneId(vObj.getZoneName());
+               Long zoneId = convertZoneNameToZoneId(vObj.getZoneName(), vObj);
 
                xObj.setZoneId(zoneId);
 
@@ -146,7 +147,7 @@ public abstract class RangerPolicyServiceBase<T extends 
XXPolicyBase, V extends
                vObj.setResourceSignature(xObj.getResourceSignature());
                vObj.setIsEnabled(xObj.getIsEnabled());
                vObj.setIsAuditEnabled(xObj.getIsAuditEnabled());
-               String zoneName = convertZoneIdToZoneName(xObj.getZoneId());
+               String zoneName = convertZoneIdToZoneName(xObj.getZoneId(), 
vObj);
                vObj.setZoneName(zoneName);
 
                String policyText = xObj.getPolicyText();
@@ -162,15 +163,29 @@ public abstract class RangerPolicyServiceBase<T extends 
XXPolicyBase, V extends
                return vObj;
        }
 
-       private Long convertZoneNameToZoneId(String zoneName) {
-           if (StringUtils.isEmpty(zoneName)) return null;
-           XXSecurityZone zone = 
daoMgr.getXXSecurityZoneDao().findByZoneName(zoneName);
-           return zone == null ? null : zone.getId();
-    }
-
-    private String convertZoneIdToZoneName(Long zoneId) {
-        if (zoneId == null) return null;
-        XXSecurityZone zone = 
daoMgr.getXXSecurityZoneDao().findByZoneId(zoneId);
-        return zone == null ? null : zone.getName();
-    }
+       private Long convertZoneNameToZoneId(String zoneName, V vObj) {
+               if (StringUtils.isEmpty(zoneName)) return 
RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID;
+               XXSecurityZone zone = 
daoMgr.getXXSecurityZoneDao().findByZoneName(zoneName);
+               if (zone == null) {
+                       throw restErrorUtil.createRESTException("No 
corresponding zone found for policyName: " + vObj.getName()
+                                       + "Zone Not Found : " + zoneName, 
MessageEnums.INVALID_INPUT_DATA);
+               }
+               return zone.getId();
+       }
+
+       private String convertZoneIdToZoneName(Long zoneId, V vObj) {
+               if (zoneId == null) {
+                       throw restErrorUtil.createRESTException("No 
corresponding zone found for policyName: " + vObj.getName()
+                                       + "Zone Not Found : " + zoneId, 
MessageEnums.INVALID_INPUT_DATA);
+               }
+               if 
(zoneId.equals(RangerSecurityZone.RANGER_UNZONED_SECURITY_ZONE_ID)) {
+                       return StringUtils.EMPTY;
+               }
+               XXSecurityZone zone = 
daoMgr.getXXSecurityZoneDao().findByZoneId(zoneId);
+               if (zone == null) {
+                       throw restErrorUtil.createRESTException("No 
corresponding zone found for policyName: " + vObj.getName()
+                                       + "Zone Not Found : " + zoneId, 
MessageEnums.INVALID_INPUT_DATA);
+               }
+               return zone.getName();
+       }
 }
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 18dc5fe..97cc58b 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
@@ -265,8 +265,9 @@
        </named-query>
 
        <!-- XXPolicy -->
-       <named-query name="XXPolicy.findByNameAndServiceId">
-               <query>select obj from XXPolicy obj where obj.name = :polName 
and obj.service = :serviceId order by obj.id</query>
+
+       <named-query name="XXPolicy.findByNameAndServiceIdAndZoneId">
+               <query>select obj from XXPolicy obj where obj.name = :polName 
and obj.service = :serviceId and obj.zoneId = :zoneId order by obj.id</query>
        </named-query>
 
        <named-query name="XXPolicy.findByServiceId">
diff --git 
a/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java
 
b/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java
index ecd120e..0a9e3bb 100644
--- 
a/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java
+++ 
b/security-admin/src/test/java/org/apache/ranger/biz/TestSecurityZoneDBStore.java
@@ -80,7 +80,7 @@ public class TestSecurityZoneDBStore {
                XXSecurityZone xxSecurityZone = null;
                RangerSecurityZone securityZone = new RangerSecurityZone();
                RangerSecurityZone createdSecurityZone = new 
RangerSecurityZone();
-               createdSecurityZone.setId(1L);
+               createdSecurityZone.setId(2L);
 
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
                XXGlobalStateDao xXGlobalStateDao = 
Mockito.mock(XXGlobalStateDao.class);
@@ -108,11 +108,11 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test2updateSecurityZoneById() throws Exception {
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                RangerSecurityZone securityZone = new RangerSecurityZone();
-               securityZone.setId(1L);
+               securityZone.setId(2L);
                RangerSecurityZone updateSecurityZone = new 
RangerSecurityZone();
-               updateSecurityZone.setId(1L);
+               updateSecurityZone.setId(2L);
 
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
                XXGlobalStateDao xXGlobalStateDao = 
Mockito.mock(XXGlobalStateDao.class);
@@ -140,9 +140,9 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test3deleteSecurityZoneByName() throws Exception {
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                RangerSecurityZone securityZone = new RangerSecurityZone();
-               securityZone.setId(1L);
+               securityZone.setId(2L);
                securityZone.setName("sz1");
 
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
@@ -166,9 +166,9 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test4deleteSecurityZoneById() throws Exception {
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                RangerSecurityZone securityZone = new RangerSecurityZone();
-               securityZone.setId(1L);
+               securityZone.setId(2L);
                securityZone.setName("sz1");
 
                XXGlobalStateDao xXGlobalStateDao = 
Mockito.mock(XXGlobalStateDao.class);
@@ -186,13 +186,13 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test5getSecurityZoneByName() throws Exception {
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                xxSecurityZone.setName("sz1");
                RangerSecurityZone securityZone = new RangerSecurityZone();
-               securityZone.setId(1L);
+               securityZone.setId(2L);
                securityZone.setName("sz1");
                RangerSecurityZone createdSecurityZone = new 
RangerSecurityZone();
-               createdSecurityZone.setId(1L);
+               createdSecurityZone.setId(2L);
                createdSecurityZone.setName("sz1");
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
 
@@ -215,12 +215,12 @@ public class TestSecurityZoneDBStore {
                List<RangerSecurityZone> ret = new ArrayList<>();
                List<XXSecurityZone> xxSecurityZones = new 
ArrayList<XXSecurityZone>();
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                xxSecurityZone.setName("sz1");
                xxSecurityZones.add(xxSecurityZone);
 
                RangerSecurityZone rangerSecurityZone = new 
RangerSecurityZone();
-               rangerSecurityZone.setId(2L);
+               rangerSecurityZone.setId(3L);
                ret.add(rangerSecurityZone);
                List<RangerSecurityZone> copy = new ArrayList<>(ret);
 
@@ -251,12 +251,12 @@ public class TestSecurityZoneDBStore {
                List<XXSecurityZone> xxSecurityZones = new 
ArrayList<XXSecurityZone>();
 
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                xxSecurityZone.setName("sz1");
                xxSecurityZones.add(xxSecurityZone);
 
                RangerSecurityZone rangerSecurityZone = new 
RangerSecurityZone();
-               rangerSecurityZone.setId(2L);
+               rangerSecurityZone.setId(3L);
                ret.add(rangerSecurityZone);
 //             List<RangerSecurityZone> copy = new ArrayList<>(ret);
 
@@ -279,10 +279,10 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test8createSecurityZoneWithExistingName() throws Exception {
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                RangerSecurityZone securityZone = new RangerSecurityZone();
                RangerSecurityZone createdSecurityZone = new 
RangerSecurityZone();
-               createdSecurityZone.setId(1L);
+               createdSecurityZone.setId(2L);
 
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
 
@@ -301,7 +301,7 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test9updateSecurityZoneByUnknownId() throws Exception {
                RangerSecurityZone securityZoneToUpdate = new 
RangerSecurityZone();
-               securityZoneToUpdate.setId(1L);
+               securityZoneToUpdate.setId(2L);
 
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
                
Mockito.when(daoManager.getXXSecurityZoneDao()).thenReturn(xXSecurityZoneDao);
@@ -317,9 +317,9 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test10deleteSecurityZoneByWrongName() throws Exception {
                XXSecurityZone xxSecurityZone = new XXSecurityZone();
-               xxSecurityZone.setId(1L);
+               xxSecurityZone.setId(2L);
                RangerSecurityZone securityZone = new RangerSecurityZone();
-               securityZone.setId(1L);
+               securityZone.setId(2L);
                securityZone.setName("sz1");
 
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
@@ -336,7 +336,7 @@ public class TestSecurityZoneDBStore {
        @Test
        public void test11getSecurityZoneByWrongName() throws Exception {
                RangerSecurityZone securityZone = new RangerSecurityZone();
-               securityZone.setId(1L);
+               securityZone.setId(2L);
                securityZone.setName("sz1");
 
                XXSecurityZoneDao xXSecurityZoneDao = 
Mockito.mock(XXSecurityZoneDao.class);
diff --git 
a/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java 
b/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java
index 88a563b..edb3102 100644
--- 
a/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java
+++ 
b/security-admin/src/test/java/org/apache/ranger/rest/TestSecurityZoneREST.java
@@ -117,7 +117,7 @@ public class TestSecurityZoneREST {
        @Test
        public void testUpdateSecurityZone() throws Exception {
                RangerSecurityZone rangerSecurityZoneToUpdate = 
createRangerSecurityZone();
-               Long securityZoneId = 1L;
+               Long securityZoneId = 2L;
                rangerSecurityZoneToUpdate.setId(securityZoneId);
                when(rangerBizUtil.isAdmin()).thenReturn(true);
                when(validatorFactory.getSecurityZoneValidator(svcStore, 
securityZoneStore)).thenReturn(validator);
@@ -133,7 +133,7 @@ public class TestSecurityZoneREST {
        @Test
        public void testUpdateSecurityZoneWithMisMatchId() throws Exception {
                RangerSecurityZone rangerSecurityZoneToUpdate = 
createRangerSecurityZone();
-               Long securityZoneId = 1L;
+               Long securityZoneId = 2L;
                rangerSecurityZoneToUpdate.setId(securityZoneId);
                when(rangerBizUtil.isAdmin()).thenReturn(true);
                when(validatorFactory.getSecurityZoneValidator(svcStore, 
securityZoneStore)).thenReturn(validator);
@@ -151,7 +151,7 @@ public class TestSecurityZoneREST {
        @Test
        public void testGetSecurityZoneById() throws Exception {
                RangerSecurityZone securityZone = createRangerSecurityZone();
-               Long securityZoneId = 1L;
+               Long securityZoneId = 2L;
                securityZone.setId(securityZoneId);
                
when(securityZoneStore.getSecurityZone(securityZoneId)).thenReturn(securityZone);
                RangerSecurityZone rangerSecurityZone = 
securityZoneREST.getSecurityZone(securityZoneId);
@@ -162,7 +162,7 @@ public class TestSecurityZoneREST {
        @Test
        public void testGetSecurityZoneByName() throws Exception {
                RangerSecurityZone securityZone = createRangerSecurityZone();
-               Long securityZoneId = 1L;
+               Long securityZoneId = 2L;
                String securityZoneName = securityZone.getName();
                securityZone.setId(securityZoneId);
                
when(securityZoneStore.getSecurityZoneByName(securityZoneName)).thenReturn(securityZone);
@@ -179,7 +179,7 @@ public class TestSecurityZoneREST {
                when(
                                searchUtil.getSearchFilter(request, 
securityZoneService.sortFields))
                                .thenReturn(filter);
-               Long securityZoneId = 1L;
+               Long securityZoneId = 2L;
                securityZone.setId(securityZoneId);
                List<RangerSecurityZone> zonesList = new ArrayList<>();
                zonesList.add(securityZone);
@@ -195,7 +195,7 @@ public class TestSecurityZoneREST {
        @Test
        public void testDeleteSecurityZoneById() throws Exception {
                RangerSecurityZone securityZone = createRangerSecurityZone();
-               Long securityZoneId = 1L;
+               Long securityZoneId = 2L;
                securityZone.setId(securityZoneId);
                when(rangerBizUtil.isAdmin()).thenReturn(true);
                when(validatorFactory.getSecurityZoneValidator(svcStore, 
securityZoneStore)).thenReturn(validator);
@@ -208,7 +208,7 @@ public class TestSecurityZoneREST {
        @Test
        public void testDeleteSecurityZoneByName() throws Exception {
                RangerSecurityZone securityZone = createRangerSecurityZone();
-               Long securityZoneId = 1L;
+               Long securityZoneId = 2L;
                securityZone.setId(securityZoneId);
                String securityZoneName = securityZone.getName();
                when(rangerBizUtil.isAdmin()).thenReturn(true);
diff --git 
a/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java
 
b/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java
index c32422e..f2d6149 100644
--- 
a/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java
+++ 
b/security-admin/src/test/java/org/apache/ranger/service/TestRangerPolicyServiceBase.java
@@ -121,6 +121,7 @@ public class TestRangerPolicyServiceBase {
                policy.setIsAuditEnabled(true);
                policy.setPolicyItems(policyItems);
                policy.setResources(policyResource);
+               policy.setZoneName("");
 
                return policy;
        }
@@ -137,6 +138,7 @@ public class TestRangerPolicyServiceBase {
                xxPolicy.setService(1L);
                xxPolicy.setUpdatedByUserId(Id);
                xxPolicy.setUpdateTime(new Date());
+               xxPolicy.setZoneId(1L);
                return xxPolicy;
        }
 

Reply via email to