Forráskód Böngészése

AMBARI-6543 - Views : Admin - Add Privilege Resource

tbeerbower 11 éve
szülő
commit
e19a719bd4
62 módosított fájl, 4136 hozzáadás és 136 törlés
  1. 58 0
      ambari-server/src/main/java/org/apache/ambari/server/api/resources/PrivilegeResourceDefinition.java
  2. 12 0
      ambari-server/src/main/java/org/apache/ambari/server/api/resources/ResourceInstanceFactoryImpl.java
  3. 3 1
      ambari-server/src/main/java/org/apache/ambari/server/api/resources/ViewInstanceResourceDefinition.java
  4. 40 0
      ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariPrivilegeService.java
  5. 156 0
      ambari-server/src/main/java/org/apache/ambari/server/api/services/PrivilegeService.java
  6. 7 0
      ambari-server/src/main/java/org/apache/ambari/server/api/services/ViewInstanceService.java
  7. 55 0
      ambari-server/src/main/java/org/apache/ambari/server/api/services/ViewPrivilegeService.java
  8. 15 1
      ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
  9. 79 0
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java
  10. 4 0
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
  11. 43 37
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PermissionResourceProvider.java
  12. 376 0
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PrivilegeResourceProvider.java
  13. 161 0
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ViewPrivilegeResourceProvider.java
  14. 7 3
      ambari-server/src/main/java/org/apache/ambari/server/controller/spi/Resource.java
  15. 18 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/GroupDAO.java
  16. 81 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PermissionDAO.java
  17. 87 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrincipalDAO.java
  18. 84 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrincipalTypeDAO.java
  19. 114 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrivilegeDAO.java
  20. 80 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ResourceDAO.java
  21. 102 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ResourceTypeDAO.java
  22. 18 1
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java
  23. 12 12
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ViewInstanceDAO.java
  24. 33 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/GroupEntity.java
  25. 155 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PermissionEntity.java
  26. 109 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrincipalEntity.java
  27. 120 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrincipalTypeEntity.java
  28. 182 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrivilegeEntity.java
  29. 115 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ResourceEntity.java
  30. 103 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ResourceTypeEntity.java
  31. 30 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java
  32. 27 1
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewEntity.java
  33. 26 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewInstanceEntity.java
  34. 26 4
      ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java
  35. 36 0
      ambari-server/src/main/java/org/apache/ambari/server/security/authorization/Users.java
  36. 87 5
      ambari-server/src/main/java/org/apache/ambari/server/upgrade/UpgradeCatalog170.java
  37. 94 8
      ambari-server/src/main/java/org/apache/ambari/server/view/ViewRegistry.java
  38. 58 6
      ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
  39. 57 6
      ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
  40. 67 8
      ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
  41. 72 7
      ambari-server/src/main/resources/Ambari-DDL-Postgres-EMBEDDED-CREATE.sql
  42. 6 0
      ambari-server/src/main/resources/META-INF/persistence.xml
  43. 50 0
      ambari-server/src/test/java/org/apache/ambari/server/api/resources/PrivilegeResourceDefinitionTest.java
  44. 2 2
      ambari-server/src/test/java/org/apache/ambari/server/api/resources/ViewInstanceResourceDefinitionTest.java
  45. 106 0
      ambari-server/src/test/java/org/apache/ambari/server/api/services/PrivilegeServiceTest.java
  46. 141 0
      ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProviderTest.java
  47. 46 1
      ambari-server/src/test/java/org/apache/ambari/server/controller/internal/PermissionResourceProviderTest.java
  48. 167 0
      ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ViewPrivilegeResourceProviderTest.java
  49. 15 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/OrmTestHelper.java
  50. 61 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/dao/PrincipalDAOTest.java
  51. 61 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/dao/PrincipalTypeDAOTest.java
  52. 61 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/dao/ResourceDAOTest.java
  53. 61 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/dao/ResourceTypeDAOTest.java
  54. 47 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/entities/PrincipalEntityTest.java
  55. 49 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/entities/PrincipalTypeEntityTest.java
  56. 47 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ResourceEntityTest.java
  57. 49 0
      ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ResourceTypeEntityTest.java
  58. 16 1
      ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ViewEntityTest.java
  59. 14 1
      ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ViewInstanceEntityTest.java
  60. 20 6
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestAmbariLdapAuthoritiesPopulator.java
  61. 18 0
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestUsers.java
  62. 90 25
      ambari-server/src/test/java/org/apache/ambari/server/view/ViewRegistryTest.java

+ 58 - 0
ambari-server/src/main/java/org/apache/ambari/server/api/resources/PrivilegeResourceDefinition.java

@@ -0,0 +1,58 @@
+/**
+ * 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.ambari.server.api.resources;
+
+import org.apache.ambari.server.controller.spi.Resource;
+
+import java.util.Collections;
+import java.util.Set;
+
+
+/**
+ * Privilege resource definition.
+ */
+public class PrivilegeResourceDefinition extends BaseResourceDefinition {
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a privilege resource definition.
+   */
+  public PrivilegeResourceDefinition(Resource.Type type) {
+    super(type);
+  }
+
+
+  // ----- ResourceDefinition ------------------------------------------------
+
+  @Override
+  public String getPluralName() {
+    return "privileges";
+  }
+
+  @Override
+  public String getSingularName() {
+    return "privilege";
+  }
+
+  @Override
+  public Set<SubResourceDefinition> getSubResourceDefinitions() {
+    return Collections.emptySet();
+  }
+}

+ 12 - 0
ambari-server/src/main/java/org/apache/ambari/server/api/resources/ResourceInstanceFactoryImpl.java

@@ -238,6 +238,18 @@ public class ResourceInstanceFactoryImpl implements ResourceInstanceFactory {
         resourceDefinition = new AlertDefResourceDefinition();
         break;
 
+      case AmbariPrivilege:
+        resourceDefinition = new PrivilegeResourceDefinition(Resource.Type.AmbariPrivilege);
+        break;
+
+      case ClusterPrivilege:
+        resourceDefinition = new PrivilegeResourceDefinition(Resource.Type.ClusterPrivilege);
+        break;
+
+      case ViewPrivilege:
+        resourceDefinition = new PrivilegeResourceDefinition(Resource.Type.ViewPrivilege);
+        break;
+
       default:
         throw new IllegalArgumentException("Unsupported resource type: " + type);
     }

+ 3 - 1
ambari-server/src/main/java/org/apache/ambari/server/api/resources/ViewInstanceResourceDefinition.java

@@ -20,6 +20,7 @@ package org.apache.ambari.server.api.resources;
 
 import org.apache.ambari.server.controller.spi.Resource;
 
+import java.util.HashSet;
 import java.util.Set;
 
 
@@ -40,7 +41,8 @@ public class ViewInstanceResourceDefinition extends BaseResourceDefinition {
    */
   public ViewInstanceResourceDefinition(Set<SubResourceDefinition> subResourceDefinitions) {
     super(Resource.Type.ViewInstance);
-    this.subResourceDefinitions = subResourceDefinitions;
+    this.subResourceDefinitions = new HashSet<SubResourceDefinition>(subResourceDefinitions);
+    this.subResourceDefinitions.add(new SubResourceDefinition(Resource.Type.ViewPrivilege));
   }
 
 

+ 40 - 0
ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariPrivilegeService.java

@@ -0,0 +1,40 @@
+/**
+ * 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 privileges and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services;
+
+import org.apache.ambari.server.api.resources.ResourceInstance;
+import org.apache.ambari.server.controller.spi.Resource;
+
+import javax.ws.rs.Path;
+import java.util.Collections;
+
+/**
+ *  Service responsible for Ambari privilege resource requests.
+ */
+@Path("/privileges/")
+public class AmbariPrivilegeService extends PrivilegeService {
+
+  // ----- PrivilegeService --------------------------------------------------
+
+  @Override
+  protected ResourceInstance createPrivilegeResource(String privilegeId) {
+    return createResource(Resource.Type.AmbariPrivilege,
+        Collections.singletonMap(Resource.Type.AmbariPrivilege, privilegeId));
+  }
+}

+ 156 - 0
ambari-server/src/main/java/org/apache/ambari/server/api/services/PrivilegeService.java

@@ -0,0 +1,156 @@
+/**
+ * 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 privileges and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services;
+
+import org.apache.ambari.server.api.resources.ResourceInstance;
+
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+
+/**
+ * Service responsible for privilege requests.
+ */
+public abstract class PrivilegeService extends BaseService {
+
+  /**
+   * Handles: GET /privileges/{privilegeID}
+   * Get a specific privilege.
+   *
+   * @param headers        http headers
+   * @param ui             uri info
+   * @param privilegeId   privilege id
+   *
+   * @return privilege instance representation
+   */
+  @GET
+  @Path("{privilegeId}")
+  @Produces("text/plain")
+  public Response getPrivilege(@Context HttpHeaders headers, @Context UriInfo ui,
+                                @PathParam("privilegeId") String privilegeId) {
+
+    return handleRequest(headers, null, ui, Request.Type.GET, createPrivilegeResource(privilegeId));
+  }
+
+  /**
+   * Handles: GET  /privileges
+   * Get all privileges.
+   *
+   * @param headers  http headers
+   * @param ui       uri info
+   *
+   * @return privilege collection representation
+   */
+  @GET
+  @Produces("text/plain")
+  public Response getPrivileges(@Context HttpHeaders headers, @Context UriInfo ui) {
+    return handleRequest(headers, null, ui, Request.Type.GET, createPrivilegeResource(null));
+  }
+
+  /**
+   * Handles: POST /privileges
+   * Create a privilege.
+   *
+   * @param headers    http headers
+   * @param ui         uri info
+   *
+   * @return information regarding the created privilege
+   */
+  @POST
+  @Produces("text/plain")
+  public Response createPrivilege(String body, @Context HttpHeaders headers, @Context UriInfo ui) {
+
+    return handleRequest(headers, body, ui, Request.Type.POST, createPrivilegeResource(null));
+  }
+
+  /**
+   * Handles: PUT /privileges/{privilegeID}
+   * Update a specific privilege.
+   *
+   * @param headers   http headers
+   * @param ui        uri info
+   * @param privilegeId  privilege id
+   *
+   * @return information regarding the updated privilege
+   */
+  @PUT
+  @Path("{privilegeId}")
+  @Produces("text/plain")
+  public Response updatePrivilege(String body, @Context HttpHeaders headers, @Context UriInfo ui,
+                                   @PathParam("privilegeId") String privilegeId) {
+
+    return handleRequest(headers, body, ui, Request.Type.PUT, createPrivilegeResource(privilegeId));
+  }
+
+  /**
+   * Handles: DELETE /privileges
+   * Delete privileges.
+   *
+   * @param headers   http headers
+   * @param ui        uri info
+   *
+   * @return information regarding the deleted privileges
+   */
+  @DELETE
+  @Produces("text/plain")
+  public Response deletePrivileges(@Context HttpHeaders headers, @Context UriInfo ui) {
+
+    return handleRequest(headers, null, ui, Request.Type.DELETE, createPrivilegeResource(null));
+  }
+
+  /**
+   * Handles: DELETE /privileges/{privilegeID}
+   * Delete a specific privilege.
+   *
+   * @param headers   http headers
+   * @param ui        uri info
+   * @param privilegeId  privilege id
+   *
+   * @return information regarding the deleted privilege
+   */
+  @DELETE
+  @Path("{privilegeId}")
+  @Produces("text/plain")
+  public Response deletePrivilege(@Context HttpHeaders headers, @Context UriInfo ui,
+                                  @PathParam("privilegeId") String privilegeId) {
+
+    return handleRequest(headers, null, ui, Request.Type.DELETE, createPrivilegeResource(privilegeId));
+  }
+
+
+  // ----- PrivilegeService --------------------------------------------------
+
+  /**
+   * Create a privilege resource.
+   *
+   * @param privilegeId privilege name
+   *
+   * @return a privilege resource instance
+   */
+  protected abstract ResourceInstance createPrivilegeResource(String privilegeId);
+}

+ 7 - 0
ambari-server/src/main/java/org/apache/ambari/server/api/services/ViewInstanceService.java

@@ -226,6 +226,13 @@ public class ViewInstanceService extends BaseService {
     return service;
   }
 
+  /**
+   * Gets the admin privilege service
+   */
+  @Path("{instanceName}/privileges")
+  public PrivilegeService getPrivilegeService(@PathParam ("instanceName") String instanceName) {
+    return new ViewPrivilegeService(viewName, version, instanceName);
+  }
 
   // ----- helper methods ----------------------------------------------------
 

+ 55 - 0
ambari-server/src/main/java/org/apache/ambari/server/api/services/ViewPrivilegeService.java

@@ -0,0 +1,55 @@
+/**
+ * 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 privileges and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services;
+
+import org.apache.ambari.server.api.resources.ResourceInstance;
+import org.apache.ambari.server.controller.spi.Resource;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ *  Service responsible for view privilege resource requests.
+ */
+public class ViewPrivilegeService extends PrivilegeService {
+
+  private final String viewName;
+  private final String viewVersion;
+  private final String instanceName;
+
+  public ViewPrivilegeService(String viewName, String viewVersion, String instanceName) {
+    this.viewName = viewName;
+    this.viewVersion = viewVersion;
+    this.instanceName = instanceName;
+  }
+
+  // ----- PrivilegeService --------------------------------------------------
+
+  @Override
+  protected ResourceInstance createPrivilegeResource(String privilegeId) {
+    Map<Resource.Type,String> mapIds = new HashMap<Resource.Type, String>();
+    mapIds.put(Resource.Type.View, viewName);
+    mapIds.put(Resource.Type.ViewVersion, viewVersion);
+    mapIds.put(Resource.Type.ViewInstance, instanceName);
+    mapIds.put(Resource.Type.ViewPrivilege, privilegeId);
+
+    return createResource(Resource.Type.ViewPrivilege, mapIds);
+  }
+}
+

+ 15 - 1
ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java

@@ -47,6 +47,8 @@ import org.apache.ambari.server.controller.internal.AbstractControllerResourcePr
 import org.apache.ambari.server.controller.internal.AlertDefinitionResourceProvider;
 import org.apache.ambari.server.controller.internal.BlueprintResourceProvider;
 import org.apache.ambari.server.controller.internal.ClusterResourceProvider;
+import org.apache.ambari.server.controller.internal.PermissionResourceProvider;
+import org.apache.ambari.server.controller.internal.PrivilegeResourceProvider;
 import org.apache.ambari.server.controller.internal.StackDefinedPropertyProvider;
 import org.apache.ambari.server.controller.internal.StackDependencyResourceProvider;
 import org.apache.ambari.server.controller.nagios.NagiosPropertyProvider;
@@ -54,7 +56,14 @@ import org.apache.ambari.server.orm.GuiceJpaInitializer;
 import org.apache.ambari.server.orm.PersistenceType;
 import org.apache.ambari.server.orm.dao.AlertDefinitionDAO;
 import org.apache.ambari.server.orm.dao.BlueprintDAO;
+import org.apache.ambari.server.orm.dao.GroupDAO;
 import org.apache.ambari.server.orm.dao.MetainfoDAO;
+import org.apache.ambari.server.orm.dao.PermissionDAO;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrivilegeDAO;
+import org.apache.ambari.server.orm.dao.ResourceDAO;
+import org.apache.ambari.server.orm.dao.ResourceTypeDAO;
+import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.dao.ViewDAO;
 import org.apache.ambari.server.orm.dao.ViewInstanceDAO;
 import org.apache.ambari.server.orm.entities.MetainfoEntity;
@@ -528,8 +537,13 @@ public class AmbariServer {
         injector.getInstance(Gson.class), ambariMetaInfo);
     StackDependencyResourceProvider.init(ambariMetaInfo);
     ClusterResourceProvider.init(injector.getInstance(BlueprintDAO.class), ambariMetaInfo);
-    ViewRegistry.init(injector.getInstance(ViewDAO.class), injector.getInstance(ViewInstanceDAO.class));
     AlertDefinitionResourceProvider.init(injector.getInstance(AlertDefinitionDAO.class));
+    PermissionResourceProvider.init(injector.getInstance(PermissionDAO.class));
+    PrivilegeResourceProvider.init(injector.getInstance(PrivilegeDAO.class), injector.getInstance(UserDAO.class),
+        injector.getInstance(GroupDAO.class), injector.getInstance(PrincipalDAO.class),
+        injector.getInstance(PermissionDAO.class), injector.getInstance(ResourceDAO.class));
+    ViewRegistry.init(injector.getInstance(ViewDAO.class), injector.getInstance(ViewInstanceDAO.class),
+        injector.getInstance(ResourceDAO.class), injector.getInstance(ResourceTypeDAO.class));
   }
   
   /**

+ 79 - 0
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java

@@ -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 privileges and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.controller.internal;
+
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Resource provider for Ambari privileges.
+ */
+public class AmbariPrivilegeResourceProvider extends PrivilegeResourceProvider<Object> {
+
+  /**
+   * The property ids for an Ambari privilege resource.
+   */
+  private static Set<String> propertyIds = new HashSet<String>();
+  static {
+    propertyIds.add(PRIVILEGE_ID_PROPERTY_ID);
+    propertyIds.add(PERMISSION_NAME_PROPERTY_ID);
+    propertyIds.add(PRINCIPAL_NAME_PROPERTY_ID);
+    propertyIds.add(PRINCIPAL_TYPE_PROPERTY_ID);
+  }
+
+  /**
+   * The key property ids for a privilege resource.
+   */
+  private static Map<Resource.Type, String> keyPropertyIds = new HashMap<Resource.Type, String>();
+  static {
+    keyPropertyIds.put(Resource.Type.AmbariPrivilege, PRIVILEGE_ID_PROPERTY_ID);
+  }
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct an AmbariPrivilegeResourceProvider.
+   */
+  public AmbariPrivilegeResourceProvider() {
+    super(propertyIds, keyPropertyIds, Resource.Type.AmbariPrivilege);
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  public Map<Resource.Type, String> getKeyPropertyIds() {
+    return keyPropertyIds;
+  }
+
+
+  // ----- PrivilegeResourceProvider -----------------------------------------
+
+  @Override
+  public Map<Long, Object> getResourceEntities(Map<String, Object> properties) {
+    // the singleton Ambari entity is implied
+    return Collections.singletonMap(ResourceEntity.AMBARI_RESOURCE_ID, null);
+  }
+}

+ 4 - 0
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java

@@ -71,6 +71,10 @@ public class DefaultProviderModule extends AbstractProviderModule {
         return new StackDependencyResourceProvider(propertyIds, keyPropertyIds);
       case Permission:
         return new PermissionResourceProvider();
+      case AmbariPrivilege:
+        return new AmbariPrivilegeResourceProvider();
+      case ViewPrivilege:
+        return new ViewPrivilegeResourceProvider();
       default:
         return AbstractControllerResourceProvider.getResourceProvider(type, propertyIds,
             keyPropertyIds, managementController);

+ 43 - 37
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PermissionResourceProvider.java

@@ -27,6 +27,8 @@ import org.apache.ambari.server.controller.spi.Resource;
 import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
 import org.apache.ambari.server.controller.spi.SystemException;
 import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
+import org.apache.ambari.server.orm.dao.PermissionDAO;
+import org.apache.ambari.server.orm.entities.PermissionEntity;
 
 import java.util.HashMap;
 import java.util.HashSet;
@@ -37,6 +39,12 @@ import java.util.Set;
  * Resource provider for permission instances.
  */
 public class PermissionResourceProvider extends AbstractResourceProvider {
+
+  /**
+   * Data access object used to obtain permission entities.
+   */
+  protected static PermissionDAO permissionDAO;
+
   /**
    * Permission property id constants.
    */
@@ -64,49 +72,25 @@ public class PermissionResourceProvider extends AbstractResourceProvider {
   }
 
 
+  // ----- Constructors ------------------------------------------------------
+
   /**
-   * Builtin permissions
+   * Construct a permission resource provider.
    */
-  private static final Set<Resource> builtinPermissions = new HashSet<Resource>();
-
-  static {
-    // AMBARI.ADMIN
-    Resource resource = new ResourceImpl(Resource.Type.Permission);
-    resource.setProperty(PERMISSION_ID_PROPERTY_ID, 0);
-    resource.setProperty(PERMISSION_NAME_PROPERTY_ID, "ADMIN");
-    resource.setProperty(RESOURCE_NAME_PROPERTY_ID, "AMBARI");
-    builtinPermissions.add(resource);
-
-    // CLUSTER.READ
-    resource = new ResourceImpl(Resource.Type.Permission);
-    resource.setProperty(PERMISSION_ID_PROPERTY_ID, 1);
-    resource.setProperty(PERMISSION_NAME_PROPERTY_ID, "READ");
-    resource.setProperty(RESOURCE_NAME_PROPERTY_ID, "CLUSTER");
-    builtinPermissions.add(resource);
-
-    // CLUSTER.OPERATE
-    resource = new ResourceImpl(Resource.Type.Permission);
-    resource.setProperty(PERMISSION_ID_PROPERTY_ID, 2);
-    resource.setProperty(PERMISSION_NAME_PROPERTY_ID, "OPERATE");
-    resource.setProperty(RESOURCE_NAME_PROPERTY_ID, "CLUSTER");
-    builtinPermissions.add(resource);
-
-    // CLUSTER.OPERATE
-    resource = new ResourceImpl(Resource.Type.Permission);
-    resource.setProperty(PERMISSION_ID_PROPERTY_ID, 3);
-    resource.setProperty(PERMISSION_NAME_PROPERTY_ID, "USE");
-    resource.setProperty(RESOURCE_NAME_PROPERTY_ID, "VIEW");
-    builtinPermissions.add(resource);
+  public PermissionResourceProvider() {
+    super(propertyIds, keyPropertyIds);
   }
 
 
-  // ----- Constructors ------------------------------------------------------
+  // ----- PermissionResourceProvider ----------------------------------------
 
   /**
-   * Construct a permission resource provider.
+   * Static initialization.
+   *
+   * @param dao  permission data access object
    */
-  public PermissionResourceProvider() {
-    super(propertyIds, keyPropertyIds);
+  public static void init(PermissionDAO dao) {
+    permissionDAO = dao;
   }
 
 
@@ -122,8 +106,16 @@ public class PermissionResourceProvider extends AbstractResourceProvider {
   @Override
   public Set<Resource> getResources(Request request, Predicate predicate)
       throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
-    // TODO : add custom permissions.
-    return new HashSet<Resource>(builtinPermissions);
+
+    Set<Resource> resources    = new HashSet<Resource>();
+    Set<String>   requestedIds = getRequestPropertyIds(request, predicate);
+
+    for(PermissionEntity permissionEntity : permissionDAO.findAll()){
+
+      resources.add(toResource(permissionEntity, requestedIds));
+    }
+
+    return resources;
   }
 
   @Override
@@ -150,4 +142,18 @@ public class PermissionResourceProvider extends AbstractResourceProvider {
   protected Set<String> getPKPropertyIds() {
     return new HashSet<String>(keyPropertyIds.values());
   }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  // convert the given permission entity to a resource
+  private Resource toResource(PermissionEntity entity, Set<String> requestedIds) {
+    Resource resource = new ResourceImpl(Resource.Type.Permission);
+
+    setResourceProperty(resource, PERMISSION_ID_PROPERTY_ID, entity.getId(), requestedIds);
+    setResourceProperty(resource, PERMISSION_NAME_PROPERTY_ID, entity.getPermissionName(), requestedIds);
+    setResourceProperty(resource, RESOURCE_NAME_PROPERTY_ID, entity.getResourceType().getName(), requestedIds);
+
+    return resource;
+  }
 }

+ 376 - 0
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PrivilegeResourceProvider.java

@@ -0,0 +1,376 @@
+/**
+ * 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 privileges and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.controller.internal;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.DuplicateResourceException;
+import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
+import org.apache.ambari.server.controller.spi.NoSuchResourceException;
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.RequestStatus;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
+import org.apache.ambari.server.controller.spi.SystemException;
+import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+import org.apache.ambari.server.orm.dao.GroupDAO;
+import org.apache.ambari.server.orm.dao.PermissionDAO;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrivilegeDAO;
+import org.apache.ambari.server.orm.dao.ResourceDAO;
+import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.GroupEntity;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
+import org.apache.ambari.server.orm.entities.PrivilegeEntity;
+import org.apache.ambari.server.orm.entities.UserEntity;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Abstract resource provider for privilege resources.
+ */
+public abstract class PrivilegeResourceProvider<T> extends AbstractResourceProvider {
+
+  /**
+   * Data access object used to obtain privilege entities.
+   */
+  protected static PrivilegeDAO privilegeDAO;
+
+  /**
+   * Data access object used to obtain user entities.
+   */
+  protected static UserDAO userDAO;
+
+  /**
+   * Data access object used to obtain group entities.
+   */
+  protected static GroupDAO groupDAO;
+
+  /**
+   * Data access object used to obtain principal entities.
+   */
+  protected static PrincipalDAO principalDAO;
+
+  /**
+   * Data access object used to obtain permission entities.
+   */
+  protected static PermissionDAO permissionDAO;
+
+  /**
+   * Data access object used to obtain resource entities.
+   */
+  protected static ResourceDAO resourceDAO;
+
+  /**
+   * Privilege property id constants.
+   */
+  public static final String PRIVILEGE_ID_PROPERTY_ID    = "PrivilegeInfo/privilege_id";
+  public static final String PERMISSION_NAME_PROPERTY_ID = "PrivilegeInfo/permission_name";
+  public static final String PRINCIPAL_NAME_PROPERTY_ID  = "PrivilegeInfo/principal_name";
+  public static final String PRINCIPAL_TYPE_PROPERTY_ID  = "PrivilegeInfo/principal_type";
+
+  /**
+   * The privilege resource type.
+   */
+  private final Resource.Type resourceType;
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a privilege resource provider.
+   */
+  public PrivilegeResourceProvider(Set<String> propertyIds,
+                                   Map<Resource.Type, String> keyPropertyIds,
+                                   Resource.Type resourceType) {
+    super(propertyIds, keyPropertyIds);
+    this.resourceType = resourceType;
+  }
+
+
+  // ----- PrivilegeResourceProvider ----------------------------------------
+
+  /**
+   * Static initialization.
+   *
+   * @param privDAO  the privilege data access object
+   * @param usrDAO   the user data access object
+   * @param grpDAO   the group data access object
+   * @param prinDAO  the principal data access object
+   * @param permDAO  the permission data access object
+   * @param resDAO   the resource data access object
+   */
+  public static void init(PrivilegeDAO privDAO, UserDAO usrDAO, GroupDAO grpDAO, PrincipalDAO prinDAO,
+                          PermissionDAO permDAO, ResourceDAO resDAO) {
+    privilegeDAO  = privDAO;
+    userDAO       = usrDAO;
+    groupDAO      = grpDAO;
+    principalDAO  = prinDAO;
+    permissionDAO = permDAO;
+    resourceDAO   = resDAO;
+  }
+
+  /**
+   * Get the entities for the owning resources from the given properties.
+   *
+   * @param properties  the set of properties
+   *
+   * @return the entities
+   */
+  public abstract Map<Long, T> getResourceEntities(Map<String, Object> properties);
+
+
+  // ----- ResourceProvider --------------------------------------------------
+
+  @Override
+  public RequestStatus createResources(Request request)
+      throws SystemException, UnsupportedPropertyException,
+      ResourceAlreadyExistsException, NoSuchParentResourceException {
+    for (Map<String, Object> properties : request.getProperties()) {
+      createResources(getCreateCommand(properties));
+    }
+    notifyCreate(Resource.Type.ViewInstance, request);
+
+    return getRequestStatus(null);
+  }
+
+  @Override
+  public Set<Resource> getResources(Request request, Predicate predicate)
+      throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
+    Set<Resource> resources    = new HashSet<Resource>();
+    Set<String>   requestedIds = getRequestPropertyIds(request, predicate);
+    Set<Long>     resourceIds  = new HashSet<Long>();
+
+    Set<Map<String, Object>> propertyMaps = getPropertyMaps(predicate);
+
+    if (propertyMaps.isEmpty()) {
+      propertyMaps.add(Collections.<String, Object>emptyMap());
+    }
+
+    for (Map<String, Object> properties : propertyMaps) {
+      Map<Long, T> resourceEntities = getResourceEntities(properties);
+
+      resourceIds.addAll(resourceEntities.keySet());
+
+      Map<Long, PrivilegeEntity> entityMap     = new HashMap<Long, PrivilegeEntity>();
+      List<PrincipalEntity>      principalList = new LinkedList<PrincipalEntity>();
+
+
+      List<PrivilegeEntity> entities = privilegeDAO.findAll();
+
+      for(PrivilegeEntity privilegeEntity : entities){
+        if (resourceIds.contains(privilegeEntity.getResource().getId())) {
+          PrincipalEntity principal = privilegeEntity.getPrincipal();
+          entityMap.put(principal.getId(), privilegeEntity);
+          principalList.add(principal);
+        }
+      }
+
+      Map<Long, UserEntity> userEntities = new HashMap<Long, UserEntity>();
+      List<UserEntity>      userList     = userDAO.findUsersByPrincipal(principalList);
+
+      for (UserEntity userEntity : userList) {
+        userEntities.put(userEntity.getPrincipal().getId(), userEntity);
+      }
+
+      Map<Long, GroupEntity> groupEntities = new HashMap<Long, GroupEntity>();
+      List<GroupEntity>      groupList     = groupDAO.findGroupsByPrincipal(principalList);
+
+      for (GroupEntity groupEntity : groupList) {
+        groupEntities.put(groupEntity.getPrincipal().getId(), groupEntity);
+      }
+
+      for(PrivilegeEntity privilegeEntity : entityMap.values()){
+        Resource resource = toResource(privilegeEntity, userEntities, groupEntities, resourceEntities, requestedIds);
+        if (predicate == null || predicate.evaluate(resource)) {
+          resources.add(resource);
+        }
+      }
+    }
+
+    return resources;
+  }
+
+  @Override
+  public RequestStatus updateResources(Request request, Predicate predicate)
+      throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
+    throw new UnsupportedOperationException("Not supported.");
+  }
+
+  @Override
+  public RequestStatus deleteResources(Predicate predicate)
+      throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
+    modifyResources(getDeleteCommand(predicate));
+    notifyDelete(Resource.Type.ViewInstance, predicate);
+    return getRequestStatus(null);
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  protected Set<String> getPKPropertyIds() {
+    return new HashSet<String>(getKeyPropertyIds().values());
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  /**
+   * Check to see if the given privilege entity's permission is allowable for the
+   * resource type.
+   *
+   * @param entity  the privilege entity
+   *
+   * @throws AmbariException if the the privilege permission is not allowable for the resource type
+   */
+  protected boolean checkResourceTypes(PrivilegeEntity entity) throws AmbariException {
+    Integer resourceType           = entity.getResource().getResourceType().getId();
+    Integer permissionResourceType = entity.getPermission().getResourceType().getId();
+
+    return resourceType.equals(permissionResourceType);
+  }
+
+  /**
+   * Convert the given privilege entity into a Resource.
+   *
+   * @param privilegeEntity   the privilege entity to be converted
+   * @param userEntities      the map of user entities keyed by resource id
+   * @param groupEntities     the map of group entities keyed by resource id
+   * @param resourceEntities  the map of resource entities keyed by resource id
+   * @param requestedIds      the requested property ids
+   *
+   * @return the resource
+   */
+  protected Resource toResource(PrivilegeEntity privilegeEntity,
+                                Map<Long, UserEntity> userEntities,
+                                Map<Long, GroupEntity> groupEntities,
+                                Map<Long, T> resourceEntities,
+                                Set<String> requestedIds) {
+    Resource resource = new ResourceImpl(resourceType);
+
+    setResourceProperty(resource, PRIVILEGE_ID_PROPERTY_ID,
+        privilegeEntity.getId(), requestedIds);
+    setResourceProperty(resource, PERMISSION_NAME_PROPERTY_ID,
+        privilegeEntity.getPermission().getPermissionName(), requestedIds);
+
+    PrincipalEntity principal   = privilegeEntity.getPrincipal();
+    Long            principalId = principal.getId();
+
+    if (userEntities.containsKey(principalId)) {
+      UserEntity userEntity = userEntities.get(principalId);
+      setResourceProperty(resource, PRINCIPAL_NAME_PROPERTY_ID, userEntity.getUserName(), requestedIds);
+    } else if (groupEntities.containsKey(principalId)){
+      GroupEntity groupEntity = groupEntities.get(principalId);
+      setResourceProperty(resource, PRINCIPAL_NAME_PROPERTY_ID, groupEntity.getGroupName(), requestedIds);
+    }
+
+    setResourceProperty(resource, PRINCIPAL_TYPE_PROPERTY_ID, principal.getPrincipalType().getName(), requestedIds);
+    return resource;
+  }
+
+  /**
+   * Convert the given map of properties to a privilege entity for the resource
+   * identified by the given id.
+   *
+   * @param properties  the property map
+   * @param resourceId  the resource id
+   *
+   * @return the new privilege entity
+   */
+  protected PrivilegeEntity toEntity(Map<String, Object> properties, Long resourceId) {
+    PrivilegeEntity entity = new PrivilegeEntity();
+
+    String permissionName = (String) properties.get(PERMISSION_NAME_PROPERTY_ID);
+
+    entity.setPermission(permissionDAO.findPermissionByName(permissionName));
+    entity.setResource(resourceDAO.findById(resourceId));
+
+    String principalName = (String) properties.get(PRINCIPAL_NAME_PROPERTY_ID);
+    String principalType = (String) properties.get(PRINCIPAL_TYPE_PROPERTY_ID);
+
+    if (PrincipalTypeEntity.GROUP_PRINCIPAL_TYPE_NAME.equalsIgnoreCase(principalType)) {
+      GroupEntity groupEntity = groupDAO.findGroupByName(principalName);
+      entity.setPrincipal(principalDAO.findById(groupEntity.getPrincipal().getId()));
+    } else if (PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME.equalsIgnoreCase(principalType)) {
+      UserEntity userEntity = userDAO.findLocalUserByName(principalName);
+      entity.setPrincipal(principalDAO.findById(userEntity.getPrincipal().getId()));
+    }
+    return entity;
+  }
+
+  // Create a create command with the given properties map.
+  private Command<Void> getCreateCommand(final Map<String, Object> properties) {
+    return new Command<Void>() {
+      @Override
+      public Void invoke() throws AmbariException {
+
+        // for a create there should only be one resource ...
+        Set<Long> resourceIds = getResourceEntities(properties).keySet();
+        Long      resourceId  = resourceIds.iterator().next();
+
+        PrivilegeEntity entity = toEntity(properties, resourceId);
+
+        if (privilegeDAO.exists(entity)) {
+            throw new DuplicateResourceException("The privilege already exists.");
+        }
+        if (!checkResourceTypes(entity)) {
+          throw new AmbariException("Can't grant " + entity.getPermission().getResourceType().getName() +
+              " permission on a " + entity.getResource().getResourceType().getName() + " resource.");
+        }
+
+        privilegeDAO.create(entity);
+        return null;
+      }
+    };
+  }
+
+  // Create a delete command with the given predicate.
+  private Command<Void> getDeleteCommand(final Predicate predicate) {
+    return new Command<Void>() {
+      @Override
+      public Void invoke() throws AmbariException {
+        try {
+          Set<Resource> resources = getResources(PropertyHelper.getReadRequest(), predicate);
+          for (Resource resource : resources) {
+
+            PrivilegeEntity entity =
+                privilegeDAO.findById((Integer) resource.getPropertyValue(PRIVILEGE_ID_PROPERTY_ID));
+
+            if (entity != null) {
+              privilegeDAO.remove(entity);
+            }
+          }
+        } catch (Exception e) {
+          throw new AmbariException("Caught exception deleting privilege.", e);
+        }
+        return null;
+      }
+    };
+  }
+}
+

+ 161 - 0
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ViewPrivilegeResourceProvider.java

@@ -0,0 +1,161 @@
+/**
+ * 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 privileges and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.controller.internal;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.orm.entities.GroupEntity;
+import org.apache.ambari.server.orm.entities.PrivilegeEntity;
+import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
+import org.apache.ambari.server.orm.entities.UserEntity;
+import org.apache.ambari.server.orm.entities.ViewEntity;
+import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
+import org.apache.ambari.server.view.ViewRegistry;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Resource provider for view privilege resources.
+ */
+public class ViewPrivilegeResourceProvider extends PrivilegeResourceProvider<ViewInstanceEntity> {
+
+  /**
+   * View privilege property id constants.
+   */
+  public static final String PRIVILEGE_VIEW_NAME_PROPERTY_ID     = "PrivilegeInfo/view_name";
+  public static final String PRIVILEGE_VIEW_VERSION_PROPERTY_ID  = "PrivilegeInfo/version";
+  public static final String PRIVILEGE_INSTANCE_NAME_PROPERTY_ID = "PrivilegeInfo/instance_name";
+
+  /**
+   * The property ids for a privilege resource.
+   */
+  private static Set<String> propertyIds = new HashSet<String>();
+  static {
+    propertyIds.add(PRIVILEGE_VIEW_NAME_PROPERTY_ID);
+    propertyIds.add(PRIVILEGE_VIEW_VERSION_PROPERTY_ID);
+    propertyIds.add(PRIVILEGE_INSTANCE_NAME_PROPERTY_ID);
+    propertyIds.add(PRIVILEGE_ID_PROPERTY_ID);
+    propertyIds.add(PERMISSION_NAME_PROPERTY_ID);
+    propertyIds.add(PRINCIPAL_NAME_PROPERTY_ID);
+    propertyIds.add(PRINCIPAL_TYPE_PROPERTY_ID);
+  }
+
+  /**
+   * The key property ids for a privilege resource.
+   */
+  private static Map<Resource.Type, String> keyPropertyIds = new HashMap<Resource.Type, String>();
+  static {
+    keyPropertyIds.put(Resource.Type.View, PRIVILEGE_VIEW_NAME_PROPERTY_ID);
+    keyPropertyIds.put(Resource.Type.ViewVersion, PRIVILEGE_VIEW_VERSION_PROPERTY_ID);
+    keyPropertyIds.put(Resource.Type.ViewInstance, PRIVILEGE_INSTANCE_NAME_PROPERTY_ID);
+    keyPropertyIds.put(Resource.Type.ViewPrivilege, PRIVILEGE_ID_PROPERTY_ID);
+  }
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct an ViewPrivilegeResourceProvider.
+   */
+  public ViewPrivilegeResourceProvider() {
+    super(propertyIds, keyPropertyIds, Resource.Type.ViewPrivilege);
+  }
+
+
+  // ----- AbstractResourceProvider ------------------------------------------
+
+  @Override
+  public Map<Resource.Type, String> getKeyPropertyIds() {
+    return keyPropertyIds;
+  }
+
+
+  // ----- PrivilegeResourceProvider -----------------------------------------
+
+  @Override
+  public Map<Long, ViewInstanceEntity> getResourceEntities(Map<String, Object> properties) {
+    ViewRegistry viewRegistry = ViewRegistry.getInstance();
+
+    String viewName     = (String) properties.get(PRIVILEGE_VIEW_NAME_PROPERTY_ID);
+    String viewVersion  = (String) properties.get(PRIVILEGE_VIEW_VERSION_PROPERTY_ID);
+    String instanceName = (String) properties.get(PRIVILEGE_INSTANCE_NAME_PROPERTY_ID);
+
+    if (viewName != null && viewVersion != null && instanceName != null) {
+      ViewInstanceEntity viewInstanceEntity =
+          viewRegistry.getInstanceDefinition(viewName, viewVersion, instanceName);
+
+      return Collections.singletonMap(viewInstanceEntity.getResource().getId(), viewInstanceEntity);
+    }
+
+    Set<ViewEntity> viewEntities = new HashSet<ViewEntity>();
+
+    if (viewVersion != null) {
+      ViewEntity viewEntity = viewRegistry.getDefinition(viewName, viewVersion);
+      if (viewEntity != null) {
+        viewEntities.add(viewEntity);
+      }
+    } else {
+      for (ViewEntity viewEntity : viewRegistry.getDefinitions()) {
+        if (viewName == null || viewEntity.getCommonName().equals(viewName)) {
+          viewEntities.add(viewEntity);
+        }
+      }
+    }
+
+    Map<Long, ViewInstanceEntity> resourceEntities = new HashMap<Long, ViewInstanceEntity>();
+
+    for (ViewEntity viewEntity : viewEntities) {
+      for (ViewInstanceEntity viewInstanceEntity : viewEntity.getInstances()) {
+        resourceEntities.put(viewInstanceEntity.getResource().getId(), viewInstanceEntity);
+      }
+    }
+    return resourceEntities;
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  @Override
+  protected boolean checkResourceTypes(PrivilegeEntity entity) throws AmbariException {
+    return super.checkResourceTypes(entity) ||
+        entity.getPermission().getResourceType().getId().equals(ResourceTypeEntity.VIEW_RESOURCE_TYPE);
+  }
+
+  @Override
+  protected Resource toResource(PrivilegeEntity privilegeEntity,
+                                Map<Long, UserEntity> userEntities,
+                                Map<Long, GroupEntity> groupEntities,
+                                Map<Long, ViewInstanceEntity> resourceEntities, Set<String> requestedIds) {
+    Resource resource = super.toResource(privilegeEntity, userEntities, groupEntities, resourceEntities, requestedIds);
+    if (resource != null) {
+
+      ViewInstanceEntity viewInstanceEntity = resourceEntities.get(privilegeEntity.getResource().getId());
+      ViewEntity         viewEntity         = viewInstanceEntity.getViewEntity();
+
+      setResourceProperty(resource, PRIVILEGE_VIEW_NAME_PROPERTY_ID, viewEntity.getCommonName(), requestedIds);
+      setResourceProperty(resource, PRIVILEGE_VIEW_VERSION_PROPERTY_ID, viewEntity.getVersion(), requestedIds);
+      setResourceProperty(resource, PRIVILEGE_INSTANCE_NAME_PROPERTY_ID, viewInstanceEntity.getName(), requestedIds);
+    }
+    return resource;
+  }
+}
+

+ 7 - 3
ambari-server/src/main/java/org/apache/ambari/server/controller/spi/Resource.java

@@ -22,8 +22,6 @@ package org.apache.ambari.server.controller.spi;
 import java.util.LinkedHashMap;
 import java.util.Map;
 
-import org.apache.ambari.server.controller.spi.Resource.Type;
-
 /**
  * The resource object represents a requested resource.  The resource
  * contains a collection of values for the requested properties.
@@ -113,7 +111,10 @@ public interface Resource {
     Blueprint,
     HostComponentProcess,
     Permission,
-    AlertDefinition;
+    AlertDefinition,
+    AmbariPrivilege,
+    ClusterPrivilege,
+    ViewPrivilege;
 
     /**
      * Get the {@link Type} that corresponds to this InternalType.
@@ -186,6 +187,9 @@ public interface Resource {
     public static final Type HostComponentProcess = InternalType.HostComponentProcess.getType();
     public static final Type Permission = InternalType.Permission.getType();
     public static final Type AlertDefinition = InternalType.AlertDefinition.getType();
+    public static final Type AmbariPrivilege = InternalType.AmbariPrivilege.getType();
+    public static final Type ClusterPrivilege = InternalType.ClusterPrivilege.getType();
+    public static final Type ViewPrivilege = InternalType.ViewPrivilege.getType();
 
     /**
      * The type name.

+ 18 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/GroupDAO.java

@@ -17,6 +17,7 @@
  */
 package org.apache.ambari.server.orm.dao;
 
+import java.util.Collections;
 import java.util.List;
 
 import javax.persistence.EntityManager;
@@ -30,6 +31,7 @@ import com.google.inject.Inject;
 import com.google.inject.Provider;
 import com.google.inject.Singleton;
 import com.google.inject.persist.Transactional;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
 
 @Singleton
 public class GroupDAO {
@@ -60,6 +62,22 @@ public class GroupDAO {
     }
   }
 
+  /**
+   * Find the group entities for the given list of principals
+   *
+   * @param principalList  the list of principal entities
+   *
+   * @return the list of groups matching the query
+   */
+  public List<GroupEntity> findGroupsByPrincipal(List<PrincipalEntity> principalList) {
+    if (principalList == null || principalList.isEmpty()) {
+      return Collections.emptyList();
+    }
+    TypedQuery<GroupEntity> query = entityManagerProvider.get().createQuery("SELECT grp FROM GroupEntity grp WHERE grp.principal IN :principalList", GroupEntity.class);
+    query.setParameter("principalList", principalList);
+    return daoUtils.selectList(query);
+  }
+
   @Transactional
   public void create(GroupEntity group) {
     group.setGroupName(group.getGroupName().toLowerCase());

+ 81 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PermissionDAO.java

@@ -0,0 +1,81 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import org.apache.ambari.server.orm.entities.PermissionEntity;
+
+import javax.persistence.EntityManager;
+import javax.persistence.NoResultException;
+import javax.persistence.TypedQuery;
+import java.util.List;
+
+/**
+ * Permission Data Access Object.
+ */
+@Singleton
+public class PermissionDAO {
+  /**
+   * JPA entity manager
+   */
+  @Inject
+  Provider<EntityManager> entityManagerProvider;
+  @Inject
+  DaoUtils daoUtils;
+
+  /**
+   * Find a permission entity with the given id.
+   *
+   * @param id  type id
+   *
+   * @return  a matching permission entity or null
+   */
+  public PermissionEntity findById(Integer id) {
+    return entityManagerProvider.get().find(PermissionEntity.class, id);
+  }
+
+  /**
+   * Find all permission entities.
+   *
+   * @return all entities or an empty List
+   */
+  public List<PermissionEntity> findAll() {
+    TypedQuery<PermissionEntity> query = entityManagerProvider.get().createQuery("SELECT resource FROM PermissionEntity resource", PermissionEntity.class);
+    return daoUtils.selectList(query);
+  }
+
+  /**
+   * Find a permission entity by name.
+   *
+   * @param name  the permission name
+   *
+   * @return  a matching permission entity or null
+   */
+  public PermissionEntity findPermissionByName(String name) {
+    final TypedQuery<PermissionEntity> query = entityManagerProvider.get().createNamedQuery("permissionByName", PermissionEntity.class);
+    query.setParameter("permissionname", name);
+    try {
+      return query.getSingleResult();
+    } catch (NoResultException e) {
+      return null;
+    }
+  }
+}

+ 87 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrincipalDAO.java

@@ -0,0 +1,87 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import com.google.inject.persist.Transactional;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+import java.util.List;
+
+/**
+ * Principal Data Access Object.
+ */
+@Singleton
+public class PrincipalDAO {
+  /**
+   * JPA entity manager
+   */
+  @Inject
+  Provider<EntityManager> entityManagerProvider;
+  @Inject
+  DaoUtils daoUtils;
+
+  /**
+   * Find a principal with the given id.
+   *
+   *
+   * @param id  type id
+   *
+   * @return  a matching principal type  or null
+   */
+  public PrincipalEntity findById(Long id) {
+    return entityManagerProvider.get().find(PrincipalEntity.class, id);
+  }
+
+  /**
+   * Find all principals.
+   *
+   * @return all principals or an empty List
+   */
+  public List<PrincipalEntity> findAll() {
+    TypedQuery<PrincipalEntity> query = entityManagerProvider.get().createQuery("SELECT principal FROM PrincipalEntity principal", PrincipalEntity.class);
+    return daoUtils.selectList(query);
+  }
+
+  /**
+   * Make an instance managed and persistent.
+   *
+   * @param entity  entity to store
+   */
+  @Transactional
+  public void create(PrincipalEntity entity) {
+    entityManagerProvider.get().persist(entity);
+  }
+
+  /**
+   * Merge the given entity.
+   *
+   * @param entity  the entity
+   *
+   * @return the managed entity
+   */
+  @Transactional
+  public PrincipalEntity merge(PrincipalEntity entity) {
+    return entityManagerProvider.get().merge(entity);
+  }
+}

+ 84 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrincipalTypeDAO.java

@@ -0,0 +1,84 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import com.google.inject.persist.Transactional;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+import java.util.List;
+
+/**
+ * Principal Type Data Access Object.
+ */
+@Singleton
+public class PrincipalTypeDAO {
+  /**
+   * JPA entity manager
+   */
+  @Inject
+  Provider<EntityManager> entityManagerProvider;
+
+  /**
+   * Utilities.
+   */
+  @Inject
+  DaoUtils daoUtils;
+
+  /**
+   * Find a principal type with the given id.
+   *
+   * @param id  type id
+   *
+   * @return  a matching principal type  or null
+   */
+  public PrincipalTypeEntity findById(Integer id) {
+    return entityManagerProvider.get().find(PrincipalTypeEntity.class, id);
+  }
+
+  /**
+   * Find all principal types.
+   *
+   * @return all principal types or an empty List
+   */
+  public List<PrincipalTypeEntity> findAll() {
+    TypedQuery<PrincipalTypeEntity> query = entityManagerProvider.get().createQuery("SELECT principalType FROM PrincipalTypeEntity principalType", PrincipalTypeEntity.class);
+    return daoUtils.selectList(query);
+  }
+
+  /**
+   * Make an instance managed and persistent.
+   *
+   * @param entity  entity to store
+   */
+  @Transactional
+  public void create(PrincipalTypeEntity entity) {
+    entityManagerProvider.get().persist(entity);
+  }
+
+  @Transactional
+  public PrincipalTypeEntity merge(PrincipalTypeEntity entity) {
+    return entityManagerProvider.get().merge(entity);
+  }
+}
+

+ 114 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrivilegeDAO.java

@@ -0,0 +1,114 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import com.google.inject.persist.Transactional;
+import org.apache.ambari.server.orm.entities.PrivilegeEntity;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+import java.util.List;
+
+/**
+ * Privilege Data Access Object.
+ */
+@Singleton
+public class PrivilegeDAO {
+  /**
+   * JPA entity manager
+   */
+  @Inject
+  Provider<EntityManager> entityManagerProvider;
+  @Inject
+  DaoUtils daoUtils;
+
+  /**
+   * Find a resource with the given id.
+   *
+   * @param id  type id
+   *
+   * @return  a matching resource type  or null
+   */
+  public PrivilegeEntity findById(Integer id) {
+    return entityManagerProvider.get().find(PrivilegeEntity.class, id);
+  }
+
+  /**
+   * Find all resources.
+   *
+   * @return all resources or an empty List
+   */
+  public List<PrivilegeEntity> findAll() {
+    TypedQuery<PrivilegeEntity> query = entityManagerProvider.get().createQuery("SELECT privilege FROM PrivilegeEntity privilege", PrivilegeEntity.class);
+    return daoUtils.selectList(query);
+  }
+
+  /**
+   * Determine whether or not the given privilege entity already exists.
+   *
+   * @param entity  the privilege entity
+   *
+   * @return true if the given privilege entity already exists
+   */
+  public boolean exists(PrivilegeEntity entity) {
+    TypedQuery<PrivilegeEntity> query = entityManagerProvider.get().createQuery(
+        "SELECT privilege FROM PrivilegeEntity privilege WHERE privilege.principal = :principal AND privilege.resource = :resource AND privilege.permission = :permission", PrivilegeEntity.class);
+
+    query.setParameter("principal", entity.getPrincipal());
+    query.setParameter("resource", entity.getResource());
+    query.setParameter("permission", entity.getPermission());
+
+    List<PrivilegeEntity> privilegeEntities = daoUtils.selectList(query);
+    return !(privilegeEntities == null || privilegeEntities.isEmpty());
+  }
+
+  /**
+   * Make an instance managed and persistent.
+   *
+   * @param entity  entity to persist
+   */
+  @Transactional
+  public void create(PrivilegeEntity entity) {
+    entityManagerProvider.get().persist(entity);
+  }
+
+  /**
+   * Merge the state of the given entity into the current persistence context.
+   *
+   * @param entity  entity to merge
+   *
+   * @return the merged entity
+   */
+  @Transactional
+  public PrivilegeEntity merge(PrivilegeEntity entity) {
+    return entityManagerProvider.get().merge(entity);
+  }
+  /**
+   * Remove the entity instance.
+   *
+   * @param entity  entity to remove
+   */
+  @Transactional
+  public void remove(PrivilegeEntity entity) {
+    entityManagerProvider.get().remove(merge(entity));
+  }
+}

+ 80 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ResourceDAO.java

@@ -0,0 +1,80 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import com.google.inject.persist.Transactional;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+import java.util.List;
+
+/**
+ * Admin resource Data Access Object.
+ */
+@Singleton
+public class ResourceDAO {
+  /**
+   * JPA entity manager
+   */
+  @Inject
+  Provider<EntityManager> entityManagerProvider;
+  @Inject
+  DaoUtils daoUtils;
+
+  /**
+   * Find a resource with the given id.
+   *
+   * @param id  type id
+   *
+   * @return  a matching resource type  or null
+   */
+  public ResourceEntity findById(Long id) {
+    return entityManagerProvider.get().find(ResourceEntity.class, id);
+  }
+
+  /**
+   * Find all resources.
+   *
+   * @return all resources or an empty List
+   */
+  public List<ResourceEntity> findAll() {
+    TypedQuery<ResourceEntity> query = entityManagerProvider.get().createQuery("SELECT resource FROM ResourceEntity resource", ResourceEntity.class);
+    return daoUtils.selectList(query);
+  }
+
+  /**
+   * Make an instance managed and persistent.
+   *
+   * @param entity  entity to store
+   */
+  @Transactional
+  public void create(ResourceEntity entity) {
+    entityManagerProvider.get().persist(entity);
+  }
+
+
+  @Transactional
+  public ResourceEntity merge(ResourceEntity entity) {
+    return entityManagerProvider.get().merge(entity);
+  }
+}

+ 102 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ResourceTypeDAO.java

@@ -0,0 +1,102 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Inject;
+import com.google.inject.Provider;
+import com.google.inject.Singleton;
+import com.google.inject.persist.Transactional;
+import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
+
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+import java.util.List;
+
+/**
+ * Resource Type Data Access Object.
+ */
+@Singleton
+public class ResourceTypeDAO {
+  /**
+   * JPA entity manager
+   */
+  @Inject
+  Provider<EntityManager> entityManagerProvider;
+  @Inject
+  DaoUtils daoUtils;
+
+  /**
+   * Find a resource type with the given id.
+   *
+   * @param id  type id
+   *
+   * @return  a matching resource type or null
+   */
+  public ResourceTypeEntity findById(Integer id) {
+    return entityManagerProvider.get().find(ResourceTypeEntity.class, id);
+  }
+
+  /**
+   * Find a resource type with the given name.
+   *
+   * @param name  type name
+   *
+   * @return  a matching resource type or null
+   */
+  public ResourceTypeEntity findByName(String name) {
+    TypedQuery<ResourceTypeEntity> query = entityManagerProvider.get().createQuery(
+        "SELECT resourceType FROM ResourceTypeEntity resourceType WHERE resourceType.name = ?1",
+        ResourceTypeEntity.class);
+    return daoUtils.selectSingle(query, name);
+  }
+
+  /**
+   * Find all resource types.
+   *
+   * @return all resource types or an empty List
+   */
+  public List<ResourceTypeEntity> findAll() {
+    TypedQuery<ResourceTypeEntity> query = entityManagerProvider.get().createQuery("SELECT resourceType FROM ResourceTypeEntity resourceType", ResourceTypeEntity.class);
+    return daoUtils.selectList(query);
+  }
+
+  /**
+   * Make an instance managed and persistent.
+   *
+   * @param entity  entity to store
+   */
+  @Transactional
+  public void create(ResourceTypeEntity entity) {
+    entityManagerProvider.get().persist(entity);
+  }
+
+  /**
+   * Merge the given entity.
+   *
+   * @param entity  the entity
+   *
+   * @return the managed entity
+   */
+  @Transactional
+  public ResourceTypeEntity merge(ResourceTypeEntity entity) {
+    return entityManagerProvider.get().merge(entity);
+  }
+
+}
+

+ 18 - 1
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java

@@ -22,11 +22,13 @@ import com.google.inject.Provider;
 import com.google.inject.Singleton;
 import com.google.inject.persist.Transactional;
 import org.apache.ambari.server.orm.RequiresSession;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 
 import javax.persistence.EntityManager;
 import javax.persistence.NoResultException;
 import javax.persistence.TypedQuery;
+import java.util.Collections;
 import java.util.List;
 import org.apache.ambari.server.orm.entities.RoleEntity;
 
@@ -78,6 +80,22 @@ public class UserDAO {
     }
   }
 
+  /**
+   * Find the user entities for the given list of admin principal entities.
+   *
+   * @param principalList  the list of principal entities
+   *
+   * @return the matching list of user entities
+   */
+  public List<UserEntity> findUsersByPrincipal(List<PrincipalEntity> principalList) {
+    if (principalList == null || principalList.isEmpty()) {
+      return Collections.emptyList();
+    }
+    TypedQuery<UserEntity> query = entityManagerProvider.get().createQuery("SELECT user FROM UserEntity user WHERE user.principal IN :principalList", UserEntity.class);
+    query.setParameter("principalList", principalList);
+    return daoUtils.selectList(query);
+  }
+
   @Transactional
   public void create(UserEntity user) {
     user.setUserName(user.getUserName().toLowerCase());
@@ -99,5 +117,4 @@ public class UserDAO {
   public void removeByPK(Integer userPK) {
     remove(findByPK(userPK));
   }
-
 }

+ 12 - 12
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ViewInstanceDAO.java

@@ -73,42 +73,42 @@ public class ViewInstanceDAO {
    * Refresh the state of the instance from the database,
    * overwriting changes made to the entity, if any.
    *
-   * @param ViewInstanceEntity  entity to refresh
+   * @param viewInstanceEntity  entity to refresh
    */
   @Transactional
-  public void refresh(ViewInstanceEntity ViewInstanceEntity) {
-    entityManagerProvider.get().refresh(ViewInstanceEntity);
+  public void refresh(ViewInstanceEntity viewInstanceEntity) {
+    entityManagerProvider.get().refresh(viewInstanceEntity);
   }
 
   /**
    * Make an instance managed and persistent.
    *
-   * @param ViewInstanceEntity  entity to persist
+   * @param viewInstanceEntity  entity to persist
    */
   @Transactional
-  public void create(ViewInstanceEntity ViewInstanceEntity) {
-    entityManagerProvider.get().persist(ViewInstanceEntity);
+  public void create(ViewInstanceEntity viewInstanceEntity) {
+    entityManagerProvider.get().persist(viewInstanceEntity);
   }
 
   /**
    * Merge the state of the given entity into the current persistence context.
    *
-   * @param ViewInstanceEntity  entity to merge
+   * @param viewInstanceEntity  entity to merge
    * @return the merged entity
    */
   @Transactional
-  public ViewInstanceEntity merge(ViewInstanceEntity ViewInstanceEntity) {
-    return entityManagerProvider.get().merge(ViewInstanceEntity);
+  public ViewInstanceEntity merge(ViewInstanceEntity viewInstanceEntity) {
+    return entityManagerProvider.get().merge(viewInstanceEntity);
   }
 
   /**
    * Remove the entity instance.
    *
-   * @param ViewInstanceEntity  entity to remove
+   * @param viewInstanceEntity  entity to remove
    */
   @Transactional
-  public void remove(ViewInstanceEntity ViewInstanceEntity) {
-    entityManagerProvider.get().remove(merge(ViewInstanceEntity));
+  public void remove(ViewInstanceEntity viewInstanceEntity) {
+    entityManagerProvider.get().remove(merge(viewInstanceEntity));
   }
 
   /**

+ 33 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/GroupEntity.java

@@ -25,9 +25,12 @@ import javax.persistence.Entity;
 import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
 import javax.persistence.NamedQueries;
 import javax.persistence.NamedQuery;
 import javax.persistence.OneToMany;
+import javax.persistence.OneToOne;
 import javax.persistence.Table;
 import javax.persistence.TableGenerator;
 import javax.persistence.UniqueConstraint;
@@ -60,6 +63,15 @@ public class GroupEntity {
   @OneToMany(mappedBy = "group", cascade = CascadeType.ALL)
   private Set<MemberEntity> memberEntities;
 
+  @OneToOne
+  @JoinColumns({
+      @JoinColumn(name = "principal_id", referencedColumnName = "principal_id", nullable = false),
+  })
+  private PrincipalEntity principal;
+
+
+  // ----- GroupEntity -------------------------------------------------------
+
   public Integer getGroupId() {
     return groupId;
   }
@@ -96,6 +108,27 @@ public class GroupEntity {
     this.memberEntities = memberEntities;
   }
 
+  /**
+   * Get the admin principal entity.
+   *
+   * @return the principal entity
+   */
+  public PrincipalEntity getPrincipal() {
+    return principal;
+  }
+
+  /**
+   * Set the admin principal entity.
+   *
+   * @param principal  the principal entity
+   */
+  public void setPrincipal(PrincipalEntity principal) {
+    this.principal = principal;
+  }
+
+
+  // ----- Object overrides --------------------------------------------------
+
   @Override
   public boolean equals(Object o) {
     if (this == o) return true;

+ 155 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PermissionEntity.java

@@ -0,0 +1,155 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+
+/**
+ * Represents an admin permission.
+ */
+@Table(name = "adminpermission")
+@Entity
+@TableGenerator(name = "permission_id_generator",
+    table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "value"
+    , pkColumnValue = "permission_id_seq"
+    , initialValue = 5
+    , allocationSize = 1
+)
+
+@NamedQueries({
+    @NamedQuery(name = "permissionByName", query = "SELECT permission_entity FROM PermissionEntity permission_entity where permission_entity.permissionName=:permissionname")
+})
+public class PermissionEntity {
+
+  /**
+   * The permission id.
+   */
+  @Id
+  @Column(name = "permission_id")
+  @GeneratedValue(strategy = GenerationType.TABLE, generator = "permission_id_generator")
+  private Integer id;
+
+
+  /**
+   * The permission name.
+   */
+  @Column(name = "permission_name")
+  private String permissionName;
+
+  @ManyToOne
+  @JoinColumns({
+      @JoinColumn(name = "resource_type_id", referencedColumnName = "resource_type_id", nullable = false),
+  })
+  private ResourceTypeEntity resourceType;
+
+
+  // ----- PermissionEntity ---------------------------------------------------
+
+  /**
+   * Get the permission id.
+   *
+   * @return the permission id.
+   */
+  public Integer getId() {
+    return id;
+  }
+
+  /**
+   * Set the permission id.
+   *
+   * @param id  the type id.
+   */
+  public void setId(Integer id) {
+    this.id = id;
+  }
+
+  /**
+   * Get the permission name.
+   *
+   * @return the permission name
+   */
+  public String getPermissionName() {
+    return permissionName;
+  }
+
+  /**
+   * Set the permission name.
+   *
+   * @param permissionName  the permission name
+   */
+  public void setPermissionName(String permissionName) {
+    this.permissionName = permissionName;
+  }
+
+  /**
+   * Get the resource type entity.
+   *
+   * @return  the resource type entity
+   */
+  public ResourceTypeEntity getResourceType() {
+    return resourceType;
+  }
+
+  /**
+   * Set the resource type entity.
+   *
+   * @param resourceType  the resource type entity
+   */
+  public void setResourceType(ResourceTypeEntity resourceType) {
+    this.resourceType = resourceType;
+  }
+
+
+  // ----- Object overrides --------------------------------------------------
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    PermissionEntity that = (PermissionEntity) o;
+
+    if (!id.equals(that.id)) return false;
+    if (permissionName != null ? !permissionName.equals(that.permissionName) : that.permissionName != null)
+      return false;
+    if (resourceType != null ? !resourceType.equals(that.resourceType) : that.resourceType != null) return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    int result = id.hashCode();
+    result = 31 * result + (permissionName != null ? permissionName.hashCode() : 0);
+    result = 31 * result + (resourceType != null ? resourceType.hashCode() : 0);
+    return result;
+  }
+}

+ 109 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrincipalEntity.java

@@ -0,0 +1,109 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import javax.persistence.*;
+
+/**
+ * Represents an admin principal.
+ */
+@Table(name = "adminprincipal")
+@Entity
+@TableGenerator(name = "principal_id_generator",
+    table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "value"
+    , pkColumnValue = "principal_id_seq"
+    , initialValue = 2
+    , allocationSize = 1
+)
+public class PrincipalEntity {
+
+  /**
+   * The type id.
+   */
+  @Id
+  @Column(name = "principal_id")
+  @GeneratedValue(strategy = GenerationType.TABLE, generator = "principal_id_generator")
+  private Long id;
+
+  @ManyToOne
+  @JoinColumns({
+      @JoinColumn(name = "principal_type_id", referencedColumnName = "principal_type_id", nullable = false)
+  })
+  private PrincipalTypeEntity principalType;
+
+
+  // ----- PrincipalEntity ---------------------------------------------------
+
+  /**
+   * Get the principal type id.
+   *
+   * @return the principal type id.
+   */
+  public Long getId() {
+    return id;
+  }
+
+  /**
+   * Set the principal id.
+   *
+   * @param id  the type id.
+   */
+  public void setId(Long id) {
+    this.id = id;
+  }
+
+  /**
+   * Get the principal type entity.
+   *
+   * @return  the principal type entity
+   */
+  public PrincipalTypeEntity getPrincipalType() {
+    return principalType;
+  }
+
+  /**
+   * Set the principal type entity.
+   *
+   * @param principalType  the principal type entity
+   */
+  public void setPrincipalType(PrincipalTypeEntity principalType) {
+    this.principalType = principalType;
+  }
+
+
+  // ----- Object overrides --------------------------------------------------
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    PrincipalEntity that = (PrincipalEntity) o;
+
+    return id.equals(that.id) && !(principalType != null ?
+        !principalType.equals(that.principalType) : that.principalType != null);
+  }
+
+  @Override
+  public int hashCode() {
+    int result = id.hashCode();
+    result = 31 * result + (principalType != null ? principalType.hashCode() : 0);
+    return result;
+  }
+}

+ 120 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrincipalTypeEntity.java

@@ -0,0 +1,120 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import javax.persistence.*;
+
+/**
+ * Represents a principal type.
+ */
+@Table(name = "adminprincipaltype")
+@Entity
+@TableGenerator(name = "principal_type_id_generator",
+    table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "value"
+    , pkColumnValue = "principal_type_id_seq"
+    , initialValue = 3
+    , allocationSize = 1
+)
+public class PrincipalTypeEntity {
+
+  /**
+   * Principal type constants.
+   */
+  public static final int USER_PRINCIPAL_TYPE  = 1;
+  public static final int GROUP_PRINCIPAL_TYPE = 2;
+
+  public static final String USER_PRINCIPAL_TYPE_NAME  = "USER";
+  public static final String GROUP_PRINCIPAL_TYPE_NAME = "GROUP";
+
+  /**
+   * The type id.
+   */
+  @Id
+  @Column(name = "principal_type_id")
+  @GeneratedValue(strategy = GenerationType.TABLE, generator = "principal_type_id_generator")
+  private Integer id;
+
+  /**
+   * The type name.
+   */
+  @Column(name = "principal_type_name")
+  private String name;
+
+
+  // ----- PrincipalTypeEntity -----------------------------------------------
+
+  /**
+   * Get the principal type id.
+   *
+   * @return the principal type id.
+   */
+  public Integer getId() {
+    return id;
+  }
+
+  /**
+   * Set the principal type id.
+   *
+   * @param id  the type id.
+   */
+  public void setId(Integer id) {
+    this.id = id;
+  }
+
+  /**
+   * Get the principal type name.
+   *
+   * @return the principal type name;
+   */
+  public String getName() {
+    return name;
+  }
+
+  /**
+   * Set the principal type name.
+   *
+   * @param name  the principal type name.
+   */
+  public void setName(String name) {
+    this.name = name;
+  }
+
+
+  // ------ Object overrides -------------------------------------------------
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    PrincipalTypeEntity that = (PrincipalTypeEntity) o;
+
+    if (!id.equals(that.id)) return false;
+    if (name != null ? !name.equals(that.name) : that.name != null) return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    int result = id.hashCode();
+    result = 31 * result + (name != null ? name.hashCode() : 0);
+    return result;
+  }
+}

+ 182 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrivilegeEntity.java

@@ -0,0 +1,182 @@
+/**
+ * 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 privileges and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.orm.entities;
+
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+
+/**
+ * Represents an admin privilege.
+ */
+@Table(name = "adminprivilege")
+@Entity
+@TableGenerator(name = "privilege_id_generator",
+    table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "value"
+    , pkColumnValue = "privilege_id_seq"
+    , initialValue = 1
+    , allocationSize = 1
+)
+public class PrivilegeEntity {
+
+  /**
+   * The privilege id.
+   */
+  @Id
+  @Column(name = "privilege_id")
+  @GeneratedValue(strategy = GenerationType.TABLE, generator = "privilege_id_generator")
+  private Integer id;
+
+  /**
+   * The permission.
+   */
+  @ManyToOne
+  @JoinColumns({
+      @JoinColumn(name = "permission_id", referencedColumnName = "permission_id", nullable = false),
+  })
+  private PermissionEntity permission;
+
+  /**
+   * The resource.
+   */
+  @ManyToOne
+  @JoinColumns({
+      @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false),
+  })
+  private ResourceEntity resource;
+
+  /**
+   * The principal.
+   */
+  @ManyToOne
+  @JoinColumns({
+      @JoinColumn(name = "principal_id", referencedColumnName = "principal_id", nullable = false),
+  })
+  private PrincipalEntity principal;
+
+
+  // ----- PrivilegeEntity ---------------------------------------------------
+
+  /**
+   * Get the privilege id.
+   *
+   * @return the privilege id.
+   */
+  public Integer getId() {
+    return id;
+  }
+
+  /**
+   * Set the privilege id.
+   *
+   * @param id  the type id.
+   */
+  public void setId(Integer id) {
+    this.id = id;
+  }
+
+  /**
+   * Get the associated permission entity.
+   *
+   * @return the permission entity
+   */
+  public PermissionEntity getPermission() {
+    return permission;
+  }
+
+  /**
+   * Set the permission entity.
+   *
+   * @param permission  the permission entity
+   */
+  public void setPermission(PermissionEntity permission) {
+    this.permission = permission;
+  }
+
+  /**
+   * Get the associated resource entity.
+   *
+   * @return the resource entity
+   */
+  public ResourceEntity getResource() {
+    return resource;
+  }
+
+  /**
+   * Set the resource entity.
+   *
+   * @param resource  the resource entity
+   */
+  public void setResource(ResourceEntity resource) {
+    this.resource = resource;
+  }
+
+  /**
+   * Get the associated principal entity.
+   *
+   * @return the principal entity
+   */
+  public PrincipalEntity getPrincipal() {
+    return principal;
+  }
+
+  /**
+   * Set the principal entity.
+   *
+   * @param principal  the principal entity
+   */
+  public void setPrincipal(PrincipalEntity principal) {
+    this.principal = principal;
+  }
+
+
+  // ----- Object overrides --------------------------------------------------
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    PrivilegeEntity that = (PrivilegeEntity) o;
+
+    if (!id.equals(that.id)) return false;
+    if (permission != null ? !permission.equals(that.permission) : that.permission != null) return false;
+    if (principal != null ? !principal.equals(that.principal) : that.principal != null) return false;
+    if (resource != null ? !resource.equals(that.resource) : that.resource != null) return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    int result = id.hashCode();
+    result = 31 * result + (permission != null ? permission.hashCode() : 0);
+    result = 31 * result + (resource != null ? resource.hashCode() : 0);
+    result = 31 * result + (principal != null ? principal.hashCode() : 0);
+    return result;
+  }
+}

+ 115 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ResourceEntity.java

@@ -0,0 +1,115 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import javax.persistence.*;
+
+/**
+ * Represents a resource.
+ */
+@Table(name = "adminresource")
+@Entity
+@TableGenerator(name = "resource_id_generator",
+    table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "value"
+    , pkColumnValue = "resource_id_seq"
+    , initialValue = 2
+    , allocationSize = 1
+)
+public class ResourceEntity {
+
+  /**
+   * The Ambari admin resource ID.
+   */
+  public final static long AMBARI_RESOURCE_ID = 1L;
+
+  /**
+   * The type id.
+   */
+  @Id
+  @Column(name = "resource_id")
+  @GeneratedValue(strategy = GenerationType.TABLE, generator = "resource_id_generator")
+  private Long id;
+
+  @ManyToOne
+  @JoinColumns({
+      @JoinColumn(name = "resource_type_id", referencedColumnName = "resource_type_id", nullable = false)
+  })
+  private ResourceTypeEntity resourceType;
+
+
+  // ----- ResourceEntity ---------------------------------------------------
+
+  /**
+   * Get the resource type id.
+   *
+   * @return the resource type id.
+   */
+  public Long getId() {
+    return id;
+  }
+
+  /**
+   * Set the resource id.
+   *
+   * @param id  the type id.
+   */
+  public void setId(Long id) {
+    this.id = id;
+  }
+
+  /**
+   * Get the resource type entity.
+   *
+   * @return  the resource type entity
+   */
+  public ResourceTypeEntity getResourceType() {
+    return resourceType;
+  }
+
+  /**
+   * Set the resource type entity.
+   *
+   * @param resourceType  the resource type entity
+   */
+  public void setResourceType(ResourceTypeEntity resourceType) {
+    this.resourceType = resourceType;
+  }
+
+
+  // ----- Object overrides --------------------------------------------------
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    ResourceEntity that = (ResourceEntity) o;
+
+    return id.equals(that.id) && !(resourceType != null ?
+        !resourceType.equals(that.resourceType) : that.resourceType != null);
+
+  }
+
+  @Override
+  public int hashCode() {
+    int result = id.hashCode();
+    result = 31 * result + (resourceType != null ? resourceType.hashCode() : 0);
+    return result;
+  }
+}

+ 103 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ResourceTypeEntity.java

@@ -0,0 +1,103 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import javax.persistence.*;
+
+/**
+ * Represents a resource type.
+ */
+@Table(name = "adminresourcetype")
+@Entity
+@TableGenerator(name = "resource_type_id_generator",
+    table = "ambari_sequences", pkColumnName = "sequence_name", valueColumnName = "value"
+    , pkColumnValue = "resource_type_id_seq"
+    , initialValue = 4
+    , allocationSize = 1
+)
+public class ResourceTypeEntity {
+
+  /**
+   * Admin resource type id constants.
+   */
+  public static final int AMBARI_RESOURCE_TYPE  = 1;
+  public static final int CLUSTER_RESOURCE_TYPE = 2;
+  public static final int VIEW_RESOURCE_TYPE    = 3;
+
+  /**
+   * Admin resource type name constants.
+   */
+  public static final String AMBARI_RESOURCE_TYPE_NAME  = "AMBARI";
+  public static final String CLUSTER_RESOURCE_TYPE_NAME = "CLUSTER";
+  public static final String VIEW_RESOURCE_TYPE_NAME    = "VIEW";
+
+  /**
+   * The type id.
+   */
+  @Id
+  @Column(name = "resource_type_id")
+  @GeneratedValue(strategy = GenerationType.TABLE, generator = "resource_type_id_generator")
+  private Integer id;
+
+  /**
+   * The type name.
+   */
+  @Column(name = "resource_type_name")
+  private String name;
+
+
+  // ----- ResourceTypeEntity -----------------------------------------------
+
+  /**
+   * Get the resource type id.
+   *
+   * @return the resource type id.
+   */
+  public Integer getId() {
+    return id;
+  }
+
+  /**
+   * Set the resource type id.
+   *
+   * @param id  the type id.
+   */
+  public void setId(Integer id) {
+    this.id = id;
+  }
+
+  /**
+   * Get the resource type name.
+   *
+   * @return the resource type name;
+   */
+  public String getName() {
+    return name;
+  }
+
+  /**
+   * Set the resource type name.
+   *
+   * @param name  the resource type name.
+   */
+  public void setName(String name) {
+    this.name = name;
+  }
+}
+

+ 30 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java

@@ -65,6 +65,15 @@ public class UserEntity {
   @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
   private Set<MemberEntity> memberEntities;
 
+  @OneToOne
+  @JoinColumns({
+      @JoinColumn(name = "principal_id", referencedColumnName = "principal_id", nullable = false),
+  })
+  private PrincipalEntity principal;
+
+
+  // ----- UserEntity --------------------------------------------------------
+
   public Integer getUserId() {
     return userId;
   }
@@ -137,6 +146,27 @@ public class UserEntity {
     }
   }
 
+  /**
+   * Get the admin principal entity.
+   *
+   * @return the principal entity
+   */
+  public PrincipalEntity getPrincipal() {
+    return principal;
+  }
+
+  /**
+   * Set the admin principal entity.
+   *
+   * @param principal  the principal entity
+   */
+  public void setPrincipal(PrincipalEntity principal) {
+    this.principal = principal;
+  }
+
+
+  // ----- Object overrides --------------------------------------------------
+
   @Override
   public boolean equals(Object o) {
     if (this == o) return true;

+ 27 - 1
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewEntity.java

@@ -32,6 +32,9 @@ import javax.persistence.CascadeType;
 import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
 import javax.persistence.NamedQuery;
 import javax.persistence.OneToMany;
 import javax.persistence.Table;
@@ -118,6 +121,11 @@ public class ViewEntity implements ViewDefinition {
   @OneToMany(cascade = CascadeType.ALL, mappedBy = "view")
   private Collection<ViewInstanceEntity> instances = new HashSet<ViewInstanceEntity>();
 
+  @ManyToOne
+  @JoinColumns({
+      @JoinColumn(name = "resource_type_id", referencedColumnName = "resource_type_id", nullable = false),
+  })
+  private ResourceTypeEntity resourceType;
 
   // ----- Transient data ----------------------------------------------------
 
@@ -607,8 +615,26 @@ public class ViewEntity implements ViewDefinition {
     return mask;
   }
 
+  /**
+   * Get the admin resource type entity.
+   *
+   * @return the resource type entity
+   */
+  public ResourceTypeEntity getResourceType() {
+    return resourceType;
+  }
+
+  /**
+   * Set the admin resource type entity.
+   *
+   * @param resourceType  the resource type entity
+   */
+  public void setResourceType(ResourceTypeEntity resourceType) {
+    this.resourceType = resourceType;
+  }
+
 
-  // ----- helper methods ----------------------------------------------------
+// ----- helper methods ----------------------------------------------------
 
   /**
    * Get the internal view name from the given common name and version.

+ 26 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewInstanceEntity.java

@@ -32,9 +32,11 @@ import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
 import javax.persistence.ManyToOne;
 import javax.persistence.NamedQuery;
 import javax.persistence.OneToMany;
+import javax.persistence.OneToOne;
 import javax.persistence.Table;
 import javax.persistence.TableGenerator;
 import javax.persistence.Transient;
@@ -144,6 +146,12 @@ public class ViewInstanceEntity implements ViewInstanceDefinition {
   @JoinColumn(name = "view_name", referencedColumnName = "view_name", nullable = false)
   private ViewEntity view;
 
+  @OneToOne
+  @JoinColumns({
+      @JoinColumn(name = "resource_id", referencedColumnName = "resource_id", nullable = false),
+  })
+  private ResourceEntity resource;
+
 
   // ----- transient data ----------------------------------------------------
 
@@ -642,6 +650,24 @@ public class ViewInstanceEntity implements ViewInstanceDefinition {
     return userNameProvider.getUsername();
   }
 
+  /**
+   * Get the admin resource entity.
+   *
+   * @return the resource entity
+   */
+  public ResourceEntity getResource() {
+    return resource;
+  }
+
+  /**
+   * Set the admin resource entity.
+   *
+   * @param resource  the resource entity
+   */
+  public void setResource(ResourceEntity resource) {
+    this.resource = resource;
+  }
+
   /**
    * Validate the state of the instance.
    *

+ 26 - 4
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java

@@ -19,10 +19,13 @@ package org.apache.ambari.server.security.authorization;
 
 import com.google.inject.Inject;
 import com.google.inject.persist.Transactional;
-import org.apache.ambari.server.AmbariException;
 import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
 import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.slf4j.Logger;
@@ -43,16 +46,21 @@ public class AmbariLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
   private AuthorizationHelper authorizationHelper;
   UserDAO userDAO;
   RoleDAO roleDAO;
+  PrincipalDAO principalDAO;
+  PrincipalTypeDAO principalTypeDAO;
 
   private static final String AMBARI_ADMIN_LDAP_ATTRIBUTE_KEY = "ambari_admin";
 
   @Inject
   public AmbariLdapAuthoritiesPopulator(Configuration configuration, AuthorizationHelper authorizationHelper,
-                                        UserDAO userDAO, RoleDAO roleDAO) {
+                                        UserDAO userDAO, RoleDAO roleDAO,
+                                        PrincipalDAO principalDAO, PrincipalTypeDAO principalTypeDAO) {
     this.configuration = configuration;
     this.authorizationHelper = authorizationHelper;
     this.userDAO = userDAO;
     this.roleDAO = roleDAO;
+    this.principalDAO = principalDAO;
+    this.principalTypeDAO = principalTypeDAO;
   }
 
   @Override
@@ -95,9 +103,22 @@ public class AmbariLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
    */
   @Transactional
   void createLdapUser(String username) {
+    // create an admin principal to represent this user
+    PrincipalTypeEntity principalTypeEntity = principalTypeDAO.findById(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
+    if (principalTypeEntity == null) {
+      principalTypeEntity = new PrincipalTypeEntity();
+      principalTypeEntity.setId(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
+      principalTypeEntity.setName(PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME);
+      principalTypeDAO.create(principalTypeEntity);
+    }
+    PrincipalEntity principalEntity = new PrincipalEntity();
+    principalEntity.setPrincipalType(principalTypeEntity);
+    principalDAO.create(principalEntity);
+
     UserEntity newUser = new UserEntity();
     newUser.setLdapUser(true);
     newUser.setUserName(username);
+    newUser.setPrincipal(principalEntity);
 
     userDAO.create(newUser);
 
@@ -143,8 +164,9 @@ public class AmbariLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
 
   /**
    * Remove role "roleName" from user "user"
-   * @param user
-   * @param roleName
+   *
+   * @param user      the user entity
+   * @param roleName  the role name
    */
   @Transactional
   void removeRole(UserEntity user, String roleName) {

+ 36 - 0
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/Users.java

@@ -27,10 +27,14 @@ import org.apache.ambari.server.AmbariException;
 import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.orm.dao.GroupDAO;
 import org.apache.ambari.server.orm.dao.MemberDAO;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
 import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.entities.GroupEntity;
 import org.apache.ambari.server.orm.entities.MemberEntity;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.slf4j.Logger;
@@ -62,6 +66,10 @@ public class Users {
   @Inject
   protected MemberDAO memberDAO;
   @Inject
+  protected PrincipalDAO principalDAO;
+  @Inject
+  protected PrincipalTypeDAO principalTypeDAO;
+  @Inject
   protected PasswordEncoder passwordEncoder;
   @Inject
   protected Configuration configuration;
@@ -181,10 +189,24 @@ public class Users {
    */
   @Transactional
   public synchronized void createUser(String userName, String password) {
+
+    // create an admin principal to represent this user
+    PrincipalTypeEntity principalTypeEntity = principalTypeDAO.findById(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
+    if (principalTypeEntity == null) {
+      principalTypeEntity = new PrincipalTypeEntity();
+      principalTypeEntity.setId(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
+      principalTypeEntity.setName(PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME);
+      principalTypeDAO.create(principalTypeEntity);
+    }
+    PrincipalEntity principalEntity = new PrincipalEntity();
+    principalEntity.setPrincipalType(principalTypeEntity);
+    principalDAO.create(principalEntity);
+
     UserEntity userEntity = new UserEntity();
     userEntity.setUserName(userName);
     userEntity.setUserPassword(passwordEncoder.encode(password));
     userEntity.setRoleEntities(new HashSet<RoleEntity>());
+    userEntity.setPrincipal(principalEntity);
 
     RoleEntity roleEntity = roleDAO.findByName(getUserRole());
     if (roleEntity == null) {
@@ -248,8 +270,22 @@ public class Users {
    */
   @Transactional
   public synchronized void createGroup(String groupName) {
+    // create an admin principal to represent this group
+    PrincipalTypeEntity principalTypeEntity = principalTypeDAO.findById(PrincipalTypeEntity.GROUP_PRINCIPAL_TYPE);
+    if (principalTypeEntity == null) {
+      principalTypeEntity = new PrincipalTypeEntity();
+      principalTypeEntity.setId(PrincipalTypeEntity.GROUP_PRINCIPAL_TYPE);
+      principalTypeEntity.setName(PrincipalTypeEntity.GROUP_PRINCIPAL_TYPE_NAME);
+      principalTypeDAO.create(principalTypeEntity);
+    }
+    PrincipalEntity principalEntity = new PrincipalEntity();
+    principalEntity.setPrincipalType(principalTypeEntity);
+    principalDAO.create(principalEntity);
+
     final GroupEntity groupEntity = new GroupEntity();
     groupEntity.setGroupName(groupName);
+    groupEntity.setPrincipal(principalEntity);
+
     groupDAO.create(groupEntity);
   }
 

+ 87 - 5
ambari-server/src/main/java/org/apache/ambari/server/upgrade/UpgradeCatalog170.java

@@ -19,6 +19,8 @@
 package org.apache.ambari.server.upgrade;
 
 import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
 
 import org.apache.ambari.server.AmbariException;
 import org.apache.ambari.server.orm.DBAccessor;
@@ -62,6 +64,80 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
 
   @Override
   protected void executeDDLUpdates() throws AmbariException, SQLException {
+
+    List<DBAccessor.DBColumnInfo> columns;
+
+    // add admin tables and initial values prior to adding referencing columns on existing tables
+    columns = new ArrayList<DBAccessor.DBColumnInfo>();
+    columns.add(new DBAccessor.DBColumnInfo("principal_type_id", Integer.class, 1, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("principal_type_name", String.class, null, null, false));
+
+    dbAccessor.createTable("adminprincipaltype", columns, "principal_type_id");
+
+    dbAccessor.executeQuery("insert into adminprincipaltype (principal_type_id, principal_type_name)\n" +
+        "  select 1, 'USER'\n" +
+        "  union all\n" +
+        "  select 2, 'GROUP'", true);
+
+    columns = new ArrayList<DBAccessor.DBColumnInfo>();
+    columns.add(new DBAccessor.DBColumnInfo("principal_id", Long.class, null, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("principal_type_id", Integer.class, 1, null, false));
+
+    dbAccessor.createTable("adminprincipal", columns, "principal_id");
+
+    dbAccessor.executeQuery("insert into adminprincipal (principal_id, principal_type_id)\n" +
+        "  select 1, 1", true);
+
+    columns = new ArrayList<DBAccessor.DBColumnInfo>();
+    columns.add(new DBAccessor.DBColumnInfo("resource_type_id", Integer.class, 1, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("resource_type_name", String.class, null, null, false));
+
+    dbAccessor.createTable("adminresourcetype", columns, "resource_type_id");
+
+    dbAccessor.executeQuery("insert into adminresourcetype (resource_type_id, resource_type_name)\n" +
+        "  select 1, 'AMBARI'\n" +
+        "  union all\n" +
+        "  select 2, 'CLUSTER'\n" +
+        "  union all\n" +
+        "  select 3, 'VIEW'", true);
+
+    columns = new ArrayList<DBAccessor.DBColumnInfo>();
+    columns.add(new DBAccessor.DBColumnInfo("resource_id", Long.class, null, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("resource_type_id", Integer.class, 1, null, false));
+
+    dbAccessor.createTable("adminresource", columns, "resource_id");
+
+    dbAccessor.executeQuery("insert into adminresource (resource_id, resource_type_id)\n" +
+        "  select 1, 1", true);
+
+    columns = new ArrayList<DBAccessor.DBColumnInfo>();
+    columns.add(new DBAccessor.DBColumnInfo("permission_id", Long.class, null, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("permission_name", String.class, null, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("resource_type_id", Integer.class, 1, null, false));
+
+    dbAccessor.createTable("adminpermission", columns, "permission_id");
+
+    dbAccessor.executeQuery("insert into adminpermission(permission_id, permission_name, resource_type_id)\n" +
+        "  select 1, 'AMBARI.ADMIN', 1\n" +
+        "  union all\n" +
+        "  select 2, 'CLUSTER.READ', 2\n" +
+        "  union all\n" +
+        "  select 3, 'CLUSTER.OPERATE', 2\n" +
+        "  union all\n" +
+        "  select 4, 'VIEW.USE', 3", true);
+
+    columns = new ArrayList<DBAccessor.DBColumnInfo>();
+    columns.add(new DBAccessor.DBColumnInfo("privilege_id", Long.class, null, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("permission_id", Long.class, null, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("resource_id", Long.class, null, null, false));
+    columns.add(new DBAccessor.DBColumnInfo("principal_id", Long.class, null, null, false));
+
+    dbAccessor.createTable("adminprivilege", columns, "privilege_id");
+
+    dbAccessor.executeQuery("insert into adminprivilege (privilege_id, permission_id, resource_id, principal_id)\n" +
+        "  select 1, 1, 1, 1", true);
+
+
     DBAccessor.DBColumnInfo clusterConfigAttributesColumn = new DBAccessor.DBColumnInfo(
         "config_attributes", String.class, 32000, null, true);
     dbAccessor.addColumn("clusterconfig", clusterConfigAttributesColumn);
@@ -72,15 +148,21 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
     dbAccessor.addColumn("viewparameter", new DBAccessor.DBColumnInfo("masked",
       Character.class, 1, null, true));
     dbAccessor.addColumn("users", new DBAccessor.DBColumnInfo("active",
-      Integer.class, 1, 1, false));    
+      Integer.class, 1, 1, false));
+    dbAccessor.addColumn("users", new DBAccessor.DBColumnInfo("principal_id",
+        Long.class, 1, 1, false));
+    dbAccessor.addColumn("viewmain", new DBAccessor.DBColumnInfo("resource_type_id",
+        Integer.class, 1, 1, false));
+    dbAccessor.addColumn("viewinstance", new DBAccessor.DBColumnInfo("resource_id",
+        Long.class, 1, 1, false));
   }
 
 
   // ----- UpgradeCatalog ----------------------------------------------------
 
   @Override
-  protected void executeDMLUpdates() throws AmbariException, SQLException {}
-  
-  protected void addMissingConfigs() throws AmbariException {}
-
+  protected void executeDMLUpdates() throws AmbariException, SQLException {
+    // TODO : create admin principals for existing users and groups.
+    // TODO : create admin resources for existing clusters and view instances
+  }
 }

+ 94 - 8
ambari-server/src/main/java/org/apache/ambari/server/view/ViewRegistry.java

@@ -29,8 +29,12 @@ import org.apache.ambari.server.api.services.ViewExternalSubResourceService;
 import org.apache.ambari.server.api.services.ViewSubResourceService;
 import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.orm.dao.ResourceDAO;
+import org.apache.ambari.server.orm.dao.ResourceTypeDAO;
 import org.apache.ambari.server.orm.dao.ViewDAO;
 import org.apache.ambari.server.orm.dao.ViewInstanceDAO;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
 import org.apache.ambari.server.orm.entities.ViewEntity;
 import org.apache.ambari.server.orm.entities.ViewEntityEntity;
 import org.apache.ambari.server.orm.entities.ViewInstanceDataEntity;
@@ -107,6 +111,12 @@ public class ViewRegistry {
   private Map<ViewEntity, Map<String, ViewInstanceEntity>> viewInstanceDefinitions =
       new HashMap<ViewEntity, Map<String, ViewInstanceEntity>>();
 
+  /**
+   * Mapping of view instances keyed by resource id.
+   */
+  private Map<Long, ViewInstanceEntity> viewInstances =
+      new HashMap<Long, ViewInstanceEntity>();
+
   /**
    * Mapping of view names to sub-resources.
    */
@@ -144,6 +154,16 @@ public class ViewRegistry {
    */
   private static ViewInstanceDAO instanceDAO;
 
+  /**
+   * Admin resource data access object.
+   */
+  private static ResourceDAO resourceDAO;
+
+  /**
+   * Admin resource type data access object.
+   */
+  private static ResourceTypeDAO resourceTypeDAO;
+
 
   // ----- Constructors ------------------------------------------------------
 
@@ -208,14 +228,25 @@ public class ViewRegistry {
   }
 
   /**
-   * Get the instance definition for the given view name and instance name.
+   * Get the instance definition for the given resource id.
    *
-   * @param viewName      the view name
-   * @param version       the version
-   * @param instanceName  the instance name
+   * @param resourceId  the resource id.
    *
-   * @return the view instance definition for the given view and instance name
+   * @return the view instance for the given resource id
    */
+  public ViewInstanceEntity getInstanceDefinition(Long resourceId) {
+    return viewInstances.get(resourceId);
+  }
+
+  /**
+    * Get the instance definition for the given view name and instance name.
+    *
+    * @param viewName      the view name
+    * @param version       the version
+    * @param instanceName  the instance name
+    *
+    * @return the view instance definition for the given view and instance name
+    */
   public ViewInstanceEntity getInstanceDefinition(String viewName, String version, String instanceName) {
     Map<String, ViewInstanceEntity> viewInstanceDefinitionMap =
         viewInstanceDefinitions.get(getDefinition(viewName, version));
@@ -241,6 +272,7 @@ public class ViewRegistry {
       view.onCreate(instanceDefinition);
     }
     instanceDefinitions.put(instanceDefinition.getName(), instanceDefinition);
+    viewInstances.put(instanceDefinition.getResource().getId(), instanceDefinition);
   }
 
   /**
@@ -260,6 +292,7 @@ public class ViewRegistry {
           view.onDestroy(instanceDefinition);
         }
         instanceDefinitions.remove(instanceName);
+        viewInstances.remove(instanceDefinition.getResource().getId());
       }
     }
   }
@@ -399,6 +432,14 @@ public class ViewRegistry {
               version + "/" + instanceName);
         }
         instanceEntity.validate(viewEntity);
+
+        // create an admin resource to represent this view instance
+        ResourceEntity resourceEntity = new ResourceEntity();
+        resourceEntity.setResourceType(viewEntity.getResourceType());
+        resourceDAO.create(resourceEntity);
+
+        instanceEntity.setResource(resourceEntity);
+
         instanceDAO.merge(instanceEntity);
 
         ViewInstanceEntity persistedInstance = instanceDAO.findByName(ViewEntity.getViewName(viewName, version), instanceName);
@@ -844,6 +885,25 @@ public class ViewRegistry {
       if (LOG.isDebugEnabled()) {
         LOG.debug("Creating View " + viewName + ".");
       }
+      // get or create an admin resource type to represent this view
+      ResourceTypeEntity resourceTypeEntity = resourceTypeDAO.findByName(viewName);
+      if (resourceTypeEntity == null) {
+        resourceTypeEntity = new ResourceTypeEntity();
+        resourceTypeEntity.setName(view.getName());
+        resourceTypeDAO.create(resourceTypeEntity);
+      }
+
+      view.setResourceType(resourceTypeEntity);
+
+      for( ViewInstanceEntity instance : view.getInstances()) {
+
+        // create an admin resource to represent this view instance
+        ResourceEntity resourceEntity = new ResourceEntity();
+        resourceEntity.setResourceType(resourceTypeEntity);
+        resourceDAO.create(resourceEntity);
+
+        instance.setResource(resourceEntity);
+      }
       // ... merge it
       viewDAO.merge(view);
 
@@ -886,6 +946,10 @@ public class ViewRegistry {
       instance.setData(persistedInstance.getData());
       instance.setProperties(persistedInstance.getProperties());
       instance.setEntities(persistedInstance.getEntities());
+
+      if (instance.getResource() == null) {
+        instance.setResource(persistedInstance.getResource());
+      }
     }
 
     // these instances appear in the archive but have been deleted
@@ -1010,12 +1074,16 @@ public class ViewRegistry {
   /**
    * Static initialization of DAO.
    *
-   * @param viewDAO      view data access object
-   * @param instanceDAO  view instance data access object
+   * @param viewDAO          view data access object
+   * @param instanceDAO      view instance data access object
+   * @param resourceDAO      resource data access object
+   * @param resourceTypeDAO  resource type data access object
    */
-  public static void init(ViewDAO viewDAO, ViewInstanceDAO instanceDAO) {
+  public static void init(ViewDAO viewDAO, ViewInstanceDAO instanceDAO, ResourceDAO resourceDAO, ResourceTypeDAO resourceTypeDAO) {
     setViewDAO(viewDAO);
     setInstanceDAO(instanceDAO);
+    setResourceDAO(resourceDAO);
+    setResourceTypeDAO(resourceTypeDAO);
   }
 
   /**
@@ -1036,6 +1104,24 @@ public class ViewRegistry {
     ViewRegistry.instanceDAO = instanceDAO;
   }
 
+  /**
+   * Set the resource DAO.
+   *
+   * @param resourceDAO  the resource DAO
+   */
+  protected static void setResourceDAO(ResourceDAO resourceDAO) {
+    ViewRegistry.resourceDAO = resourceDAO;
+  }
+
+  /**
+   * Set the resource type DAO.
+   *
+   * @param resourceTypeDAO  the resource type DAO
+   */
+  protected static void setResourceTypeDAO(ResourceTypeDAO resourceTypeDAO) {
+    ViewRegistry.resourceTypeDAO = resourceTypeDAO;
+  }
+
 
   // ----- inner class : ViewRegistryHelper ----------------------------------
 

+ 58 - 6
ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql

@@ -37,8 +37,8 @@ CREATE TABLE hoststate (agent_version VARCHAR(255) NOT NULL, available_mem BIGIN
 CREATE TABLE servicecomponentdesiredstate (component_name VARCHAR(255) NOT NULL, cluster_id BIGINT NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, desired_state VARCHAR(255) NOT NULL, service_name VARCHAR(255) NOT NULL, PRIMARY KEY (component_name, cluster_id, service_name));
 CREATE TABLE servicedesiredstate (cluster_id BIGINT NOT NULL, desired_host_role_mapping INTEGER NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, desired_state VARCHAR(255) NOT NULL, service_name VARCHAR(255) NOT NULL, maintenance_state VARCHAR(32) NOT NULL DEFAULT 'ACTIVE', PRIMARY KEY (cluster_id, service_name));
 CREATE TABLE roles (role_name VARCHAR(255) NOT NULL, PRIMARY KEY (role_name));
-CREATE TABLE users (user_id INTEGER, create_time TIMESTAMP DEFAULT NOW(), ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, user_password VARCHAR(255), active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id));
-CREATE TABLE groups (group_id INTEGER, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id));
+CREATE TABLE users (user_id INTEGER, principal_id BIGINT NOT NULL, create_time TIMESTAMP DEFAULT NOW(), ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, user_password VARCHAR(255), active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id));
+CREATE TABLE groups (group_id INTEGER, principal_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id));
 CREATE TABLE members (member_id INTEGER, group_id INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (member_id));
 CREATE TABLE execution_command (task_id BIGINT NOT NULL, command LONGBLOB, PRIMARY KEY (task_id));
 CREATE TABLE host_role_command (task_id BIGINT NOT NULL, attempt_count SMALLINT NOT NULL, event LONGTEXT NOT NULL, exitcode INTEGER NOT NULL, host_name VARCHAR(255) NOT NULL, last_attempt_time BIGINT NOT NULL, request_id BIGINT NOT NULL, role VARCHAR(255), role_command VARCHAR(255), stage_id BIGINT NOT NULL, start_time BIGINT NOT NULL, end_time BIGINT, status VARCHAR(255), std_error LONGBLOB, std_out LONGBLOB, structured_out LONGBLOB, command_detail VARCHAR(255), custom_command_name VARCHAR(255), PRIMARY KEY (task_id));
@@ -64,13 +64,19 @@ CREATE TABLE hostgroup (blueprint_name VARCHAR(255) NOT NULL, name VARCHAR(255)
 CREATE TABLE hostgroup_component (blueprint_name VARCHAR(255) NOT NULL, hostgroup_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(blueprint_name, hostgroup_name, name));
 CREATE TABLE blueprint_configuration (blueprint_name VARCHAR(255) NOT NULL, type_name VARCHAR(255) NOT NULL, config_data VARCHAR(32000) NOT NULL , PRIMARY KEY(blueprint_name, type_name));
 CREATE TABLE hostgroup_configuration (blueprint_name VARCHAR(255) NOT NULL, hostgroup_name VARCHAR(255) NOT NULL, type_name VARCHAR(255) NOT NULL, config_data TEXT NOT NULL, PRIMARY KEY(blueprint_name, hostgroup_name, type_name));
-CREATE TABLE viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
+CREATE TABLE viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), resource_type_id INTEGER NOT NULL, icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
 CREATE TABLE viewinstancedata (view_instance_id BIGINT, view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, user_name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(VIEW_INSTANCE_ID, NAME, USER_NAME));
-CREATE TABLE viewinstance (view_instance_id BIGINT, view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
+CREATE TABLE viewinstance (view_instance_id BIGINT, resource_id BIGINT NOT NULL, view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
 CREATE TABLE viewinstanceproperty (view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(view_name, view_instance_name, name));
 CREATE TABLE viewparameter (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, description VARCHAR(255), required CHAR(1), masked CHAR(1), PRIMARY KEY(view_name, name));
 CREATE TABLE viewresource (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, plural_name VARCHAR(255), id_property VARCHAR(255), subResource_names VARCHAR(255), provider VARCHAR(255), service VARCHAR(255), resource VARCHAR(255), PRIMARY KEY(view_name, name));
 CREATE TABLE viewentity (id BIGINT NOT NULL, view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, class_name VARCHAR(255) NOT NULL, id_property VARCHAR(255), PRIMARY KEY(id));
+CREATE TABLE adminresourcetype (resource_type_id INTEGER NOT NULL, resource_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(resource_type_id));
+CREATE TABLE adminresource (resource_id BIGINT NOT NULL, resource_type_id INTEGER NOT NULL, PRIMARY KEY(resource_id));
+CREATE TABLE adminprincipaltype (principal_type_id INTEGER NOT NULL, principal_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(principal_type_id));
+CREATE TABLE adminprincipal (principal_id BIGINT NOT NULL, principal_type_id INTEGER NOT NULL, PRIMARY KEY(principal_id));
+CREATE TABLE adminpermission (permission_id BIGINT NOT NULL, permission_name VARCHAR(255) NOT NULL, resource_type_id INTEGER NOT NULL, PRIMARY KEY(permission_id));
+CREATE TABLE adminprivilege (privilege_id BIGINT, permission_id BIGINT NOT NULL, resource_id BIGINT NOT NULL, principal_id BIGINT NOT NULL, PRIMARY KEY(privilege_id));
 
 ALTER TABLE users ADD CONSTRAINT UNQ_users_0 UNIQUE (user_name, ldap_user);
 ALTER TABLE groups ADD CONSTRAINT UNQ_groups_0 UNIQUE (group_name, ldap_group);
@@ -120,6 +126,16 @@ ALTER TABLE viewinstance ADD CONSTRAINT FK_viewinst_view_name FOREIGN KEY (view_
 ALTER TABLE viewinstanceproperty ADD CONSTRAINT FK_viewinstprop_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES viewinstance(view_name, name);
 ALTER TABLE viewinstancedata ADD CONSTRAINT FK_viewinstdata_view_name FOREIGN KEY (view_instance_id, view_name, view_instance_name) REFERENCES viewinstance(view_instance_id, view_name, name);
 ALTER TABLE viewentity ADD CONSTRAINT FK_viewentity_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES viewinstance(view_name, name);
+ALTER TABLE adminresource ADD CONSTRAINT FK_resource_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE adminprincipal ADD CONSTRAINT FK_principal_principal_type_id FOREIGN KEY (principal_type_id) REFERENCES adminprincipaltype(principal_type_id);
+ALTER TABLE adminpermission ADD CONSTRAINT FK_permission_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_permission_id FOREIGN KEY (permission_id) REFERENCES adminpermission(permission_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE viewmain ADD CONSTRAINT FK_view_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE viewinstance ADD CONSTRAINT FK_viewinstance_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE users ADD CONSTRAINT FK_users_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE groups ADD CONSTRAINT FK_groups_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
 
 
 INSERT INTO ambari_sequences(sequence_name, value) values ('cluster_id_seq', 1);
@@ -133,18 +149,54 @@ INSERT INTO ambari_sequences(sequence_name, value) values ('resourcefilter_id_se
 INSERT INTO ambari_sequences(sequence_name, value) values ('viewentity_id_seq', 0);
 INSERT INTO ambari_sequences(sequence_name, value) values ('operation_level_id_seq', 1);
 INSERT INTO ambari_sequences(sequence_name, value) values ('view_instance_id_seq', 1);
+INSERT INTO ambari_sequences(sequence_name, value) values ('resource_type_id_seq', 4);
+INSERT INTO ambari_sequences(sequence_name, value) values ('resource_id_seq', 2);
+INSERT INTO ambari_sequences(sequence_name, value) values ('principal_type_id_seq', 3);
+INSERT INTO ambari_sequences(sequence_name, value) values ('principal_id_seq', 2);
+INSERT INTO ambari_sequences(sequence_name, value) values ('permission_id_seq', 5);
+INSERT INTO ambari_sequences(sequence_name, value) values ('privilege_id_seq', 1);
+
+insert into adminresourcetype (resource_type_id, resource_type_name)
+  select 1, 'AMBARI'
+  union all
+  select 2, 'CLUSTER'
+  union all
+  select 3, 'VIEW';
+
+insert into adminresource (resource_id, resource_type_id)
+  select 1, 1;
 
 insert into roles(role_name)
   select 'admin'
   union all
   select 'user';
 
-insert into users(user_id, user_name, user_password)
-  select 1,'admin','538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
+insert into adminprincipaltype (principal_type_id, principal_type_name)
+  select 1, 'USER'
+  union all
+  select 2, 'GROUP';
+
+insert into adminprincipal (principal_id, principal_type_id)
+  select 1, 1;
+
+insert into users(user_id, principal_id, user_name, user_password)
+  select 1, 1, 'admin','538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
 
 insert into user_roles(role_name, user_id)
   select 'admin',1;
 
+insert into adminpermission(permission_id, permission_name, resource_type_id)
+  select 1, 'AMBARI.ADMIN', 1
+  union all
+  select 2, 'CLUSTER.READ', 2
+  union all
+  select 3, 'CLUSTER.OPERATE', 2
+  union all
+  select 4, 'VIEW.USE', 3;
+
+insert into adminprivilege (privilege_id, permission_id, resource_id, principal_id)
+  select 1, 1, 1, 1;
+
 insert into metainfo(`metainfo_key`, `metainfo_value`)
   select 'version','${ambariVersion}';
 

+ 57 - 6
ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql

@@ -27,8 +27,8 @@ CREATE TABLE hoststate (agent_version VARCHAR2(255) NULL, available_mem NUMBER(1
 CREATE TABLE servicecomponentdesiredstate (component_name VARCHAR2(255) NOT NULL, cluster_id NUMBER(19) NOT NULL, desired_stack_version VARCHAR2(255) NULL, desired_state VARCHAR2(255) NOT NULL, service_name VARCHAR2(255) NOT NULL, PRIMARY KEY (component_name, cluster_id, service_name));
 CREATE TABLE servicedesiredstate (cluster_id NUMBER(19) NOT NULL, desired_host_role_mapping NUMBER(10) NOT NULL, desired_stack_version VARCHAR2(255) NULL, desired_state VARCHAR2(255) NOT NULL, service_name VARCHAR2(255) NOT NULL, maintenance_state VARCHAR2(32) NOT NULL, PRIMARY KEY (cluster_id, service_name));
 CREATE TABLE roles (role_name VARCHAR2(255) NOT NULL, PRIMARY KEY (role_name));
-CREATE TABLE users (user_id NUMBER(10) NOT NULL, create_time TIMESTAMP NULL, ldap_user NUMBER(10) DEFAULT 0, user_name VARCHAR2(255) NULL, user_password VARCHAR2(255) NULL, active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id));
-CREATE TABLE groups (group_id NUMBER(10) NOT NULL, group_name VARCHAR2(255) NOT NULL, ldap_group NUMBER(10) DEFAULT 0, PRIMARY KEY (group_id));
+CREATE TABLE users (user_id NUMBER(10) NOT NULL, principal_id NUMBER(19) NOT NULL, create_time TIMESTAMP NULL, ldap_user NUMBER(10) DEFAULT 0, user_name VARCHAR2(255) NULL, user_password VARCHAR2(255) NULL, active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id));
+CREATE TABLE groups (group_id NUMBER(10) NOT NULL, principal_id NUMBER(19) NOT NULL, group_name VARCHAR2(255) NOT NULL, ldap_group NUMBER(10) DEFAULT 0, PRIMARY KEY (group_id));
 CREATE TABLE members (member_id NUMBER(10), group_id NUMBER(10) NOT NULL, user_id NUMBER(10) NOT NULL, PRIMARY KEY (member_id));
 CREATE TABLE execution_command (task_id NUMBER(19) NOT NULL, command BLOB NULL, PRIMARY KEY (task_id));
 CREATE TABLE host_role_command (task_id NUMBER(19) NOT NULL, attempt_count NUMBER(5) NOT NULL, event CLOB NULL, exitcode NUMBER(10) NOT NULL, host_name VARCHAR2(255) NOT NULL, last_attempt_time NUMBER(19) NOT NULL, request_id NUMBER(19) NOT NULL, role VARCHAR2(255) NULL, role_command VARCHAR2(255) NULL, stage_id NUMBER(19) NOT NULL, start_time NUMBER(19) NOT NULL, end_time NUMBER(19), status VARCHAR2(255) NULL, std_error BLOB NULL, std_out BLOB NULL, structured_out BLOB NULL,  command_detail VARCHAR2(255) NULL, custom_command_name VARCHAR2(255) NULL, PRIMARY KEY (task_id));
@@ -54,13 +54,19 @@ CREATE TABLE hostgroup (blueprint_name VARCHAR2(255) NOT NULL, name VARCHAR2(255
 CREATE TABLE hostgroup_component (blueprint_name VARCHAR2(255) NOT NULL, hostgroup_name VARCHAR2(255) NOT NULL, name VARCHAR2(255) NOT NULL, PRIMARY KEY(blueprint_name, hostgroup_name, name));
 CREATE TABLE blueprint_configuration (blueprint_name VARCHAR2(255) NOT NULL, type_name VARCHAR2(255) NOT NULL, config_data CLOB NOT NULL , PRIMARY KEY(blueprint_name, type_name));
 CREATE TABLE hostgroup_configuration (blueprint_name VARCHAR2(255) NOT NULL, hostgroup_name VARCHAR2(255) NOT NULL, type_name VARCHAR2(255) NOT NULL, config_data CLOB NOT NULL, PRIMARY KEY(blueprint_name, hostgroup_name, type_name));
-CREATE TABLE viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
+CREATE TABLE viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), resource_type_id NUMBER(10) NOT NULL, icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
 CREATE TABLE viewinstancedata (view_instance_id NUMBER(19), view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, user_name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(view_instance_id, name, user_name));
-CREATE TABLE viewinstance (view_instance_id NUMBER(19), view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
+CREATE TABLE viewinstance (view_instance_id NUMBER(19), resource_id NUMBER(19) NOT NULL, view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
 CREATE TABLE viewinstanceproperty (view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(view_name, view_instance_name, name));
 CREATE TABLE viewparameter (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, description VARCHAR(255), required CHAR(1), masked CHAR(1), PRIMARY KEY(view_name, name));
 CREATE TABLE viewresource (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, plural_name VARCHAR(255), id_property VARCHAR(255), subResource_names VARCHAR(255), provider VARCHAR(255), service VARCHAR(255), "resource" VARCHAR(255), PRIMARY KEY(view_name, name));
 CREATE TABLE viewentity (id NUMBER(19) NOT NULL, view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, class_name VARCHAR(255) NOT NULL, id_property VARCHAR(255), PRIMARY KEY(id));
+CREATE TABLE adminresourcetype (resource_type_id NUMBER(10) NOT NULL, resource_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(resource_type_id));
+CREATE TABLE adminresource (resource_id NUMBER(19) NOT NULL, resource_type_id NUMBER(10) NOT NULL, PRIMARY KEY(resource_id));
+CREATE TABLE adminprincipaltype (principal_type_id NUMBER(10) NOT NULL, principal_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(principal_type_id));
+CREATE TABLE adminprincipal (principal_id NUMBER(19) NOT NULL, principal_type_id NUMBER(10) NOT NULL, PRIMARY KEY(principal_id));
+CREATE TABLE adminpermission (permission_id NUMBER(19) NOT NULL, permission_name VARCHAR(255) NOT NULL, resource_type_id NUMBER(10) NOT NULL, PRIMARY KEY(permission_id));
+CREATE TABLE adminprivilege (privilege_id NUMBER(19), permission_id NUMBER(19) NOT NULL, resource_id NUMBER(19) NOT NULL, principal_id NUMBER(19) NOT NULL, PRIMARY KEY(privilege_id));
 
 ALTER TABLE users ADD CONSTRAINT UNQ_users_0 UNIQUE (user_name, ldap_user);
 ALTER TABLE groups ADD CONSTRAINT UNQ_groups_0 UNIQUE (group_name, ldap_group);
@@ -110,6 +116,16 @@ ALTER TABLE viewinstance ADD CONSTRAINT FK_viewinst_view_name FOREIGN KEY (view_
 ALTER TABLE viewinstanceproperty ADD CONSTRAINT FK_viewinstprop_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES viewinstance(view_name, name);
 ALTER TABLE viewinstancedata ADD CONSTRAINT FK_viewinstdata_view_name FOREIGN KEY (view_instance_id, view_name, view_instance_name) REFERENCES viewinstance(view_instance_id, view_name, name);
 ALTER TABLE viewentity ADD CONSTRAINT FK_viewentity_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES viewinstance(view_name, name);
+ALTER TABLE adminresource ADD CONSTRAINT FK_resource_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE adminprincipal ADD CONSTRAINT FK_principal_principal_type_id FOREIGN KEY (principal_type_id) REFERENCES adminprincipaltype(principal_type_id);
+ALTER TABLE adminpermission ADD CONSTRAINT FK_permission_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_permission_id FOREIGN KEY (permission_id) REFERENCES adminpermission(permission_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE viewmain ADD CONSTRAINT FK_view_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE viewinstance ADD CONSTRAINT FK_viewinstance_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE users ADD CONSTRAINT FK_users_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE groups ADD CONSTRAINT FK_groups_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
 
 INSERT INTO ambari_sequences(sequence_name, value) values ('host_role_command_id_seq', 0);
 INSERT INTO ambari_sequences(sequence_name, value) values ('user_id_seq', 1);
@@ -122,20 +138,55 @@ INSERT INTO ambari_sequences(sequence_name, value) values ('resourcefilter_id_se
 INSERT INTO ambari_sequences(sequence_name, value) values ('viewentity_id_seq', 0);
 INSERT INTO ambari_sequences(sequence_name, value) values ('operation_level_id_seq', 1);
 INSERT INTO ambari_sequences(sequence_name, value) values ('view_instance_id_seq', 1);
+INSERT INTO ambari_sequences(sequence_name, value) values ('resource_type_id_seq', 4);
+INSERT INTO ambari_sequences(sequence_name, value) values ('resource_id_seq', 2);
+INSERT INTO ambari_sequences(sequence_name, value) values ('principal_type_id_seq', 3);
+INSERT INTO ambari_sequences(sequence_name, value) values ('principal_id_seq', 2);
+INSERT INTO ambari_sequences(sequence_name, value) values ('permission_id_seq', 5);
+INSERT INTO ambari_sequences(sequence_name, value) values ('privilege_id_seq', 1);
+
 INSERT INTO metainfo("metainfo_key", "metainfo_value") values ('version', '${ambariVersion}');
 
+insert into adminresourcetype (resource_type_id, resource_type_name)
+  select 1, 'AMBARI'
+  union all
+  select 2, 'CLUSTER'
+  union all
+  select 3, 'VIEW';
+
+insert into adminresource (resource_id, resource_type_id)
+  select 1, 1;
+
 insert into Roles(role_name)
 select 'admin' from dual
 union all
 select 'user' from dual;
 
-insert into Users(user_id, user_name, user_password)
-select 1,'admin','538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00' from dual;
+insert into adminprincipaltype (principal_type_id, principal_type_name)
+  select 1, 'USER'
+  union all
+  select 2, 'GROUP';
+
+insert into adminprincipal (principal_id, principal_type_id)
+  select 1, 1;
+
+insert into Users(user_id, principal_id, user_name, user_password)
+select 1,1,'admin','538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00' from dual;
 
 insert into user_roles(role_name, user_id)
 select 'admin',1 from dual;
 
+insert into adminpermission(permission_id, permission_name, resource_type_id)
+  select 1, 'AMBARI.ADMIN', 1
+  union all
+  select 2, 'CLUSTER.READ', 2
+  union all
+  select 3, 'CLUSTER.OPERATE', 2
+  union all
+  select 4, 'VIEW.USE', 3;
 
+insert into adminprivilege (privilege_id, permission_id, resource_id, principal_id)
+  select 1, 1, 1, 1;
 
 commit;
 

+ 67 - 8
ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql

@@ -16,7 +16,7 @@
 -- limitations under the License.
 --
 
-------create tables and grant privileges to db user---------
+------create tables ang grant privileges to db user---------
 CREATE TABLE clusters (cluster_id BIGINT NOT NULL, cluster_info VARCHAR(255) NOT NULL, cluster_name VARCHAR(100) NOT NULL UNIQUE, provisioning_state VARCHAR(255) NOT NULL DEFAULT 'INIT', desired_cluster_state VARCHAR(255) NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, PRIMARY KEY (cluster_id));
 
 CREATE TABLE clusterconfig (version_tag VARCHAR(255) NOT NULL, type_name VARCHAR(255) NOT NULL, cluster_id BIGINT NOT NULL, config_data VARCHAR(32000) NOT NULL, config_attributes VARCHAR(32000), create_timestamp BIGINT NOT NULL, PRIMARY KEY (cluster_id, type_name, version_tag));
@@ -41,9 +41,9 @@ CREATE TABLE servicedesiredstate (cluster_id BIGINT NOT NULL, desired_host_role_
 
 CREATE TABLE roles (role_name VARCHAR(255) NOT NULL, PRIMARY KEY (role_name));
 
-CREATE TABLE users (user_id INTEGER, ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, create_time TIMESTAMP DEFAULT NOW(), user_password VARCHAR(255), PRIMARY KEY (user_id), active INTEGER NOT NULL DEFAULT 1, UNIQUE (ldap_user, user_name));
+CREATE TABLE users (user_id INTEGER, principal_id BIGINT NOT NULL, ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, create_time TIMESTAMP DEFAULT NOW(), user_password VARCHAR(255), PRIMARY KEY (user_id), active INTEGER NOT NULL DEFAULT 1, UNIQUE (ldap_user, user_name));
 
-CREATE TABLE groups (group_id INTEGER, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id), UNIQUE (ldap_group, group_name));
+CREATE TABLE groups (group_id INTEGER, principal_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id), UNIQUE (ldap_group, group_name));
 
 CREATE TABLE members (member_id INTEGER, group_id INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (member_id), UNIQUE(group_id, user_id));
 
@@ -89,14 +89,21 @@ CREATE TABLE hostgroup_component (blueprint_name VARCHAR(255) NOT NULL, hostgrou
 CREATE TABLE blueprint_configuration (blueprint_name varchar(255) NOT NULL, type_name varchar(255) NOT NULL, config_data varchar(32000) NOT NULL , PRIMARY KEY(blueprint_name, type_name));
 CREATE TABLE hostgroup_configuration (blueprint_name VARCHAR(255) NOT NULL, hostgroup_name VARCHAR(255) NOT NULL, type_name VARCHAR(255) NOT NULL, config_data TEXT NOT NULL, PRIMARY KEY(blueprint_name, hostgroup_name, type_name));
 
-CREATE TABLE viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
+CREATE TABLE viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), resource_type_id INTEGER NOT NULL, icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
 CREATE TABLE viewinstancedata (view_instance_id BIGINT, view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, user_name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(view_instance_id, name, user_name));
-CREATE TABLE viewinstance (view_instance_id BIGINT, view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
+CREATE TABLE viewinstance (view_instance_id BIGINT, resource_id BIGINT NOT NULL, view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
 CREATE TABLE viewinstanceproperty (view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(view_name, view_instance_name, name));
 CREATE TABLE viewparameter (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, description VARCHAR(255), required CHAR(1), masked CHAR(1), PRIMARY KEY(view_name, name));
 CREATE TABLE viewresource (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, plural_name VARCHAR(255), id_property VARCHAR(255), subResource_names VARCHAR(255), provider VARCHAR(255), service VARCHAR(255), resource VARCHAR(255), PRIMARY KEY(view_name, name));
 CREATE TABLE viewentity (id BIGINT NOT NULL, view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, class_name VARCHAR(255) NOT NULL, id_property VARCHAR(255), PRIMARY KEY(id));
 
+CREATE TABLE adminresourcetype (resource_type_id INTEGER NOT NULL, resource_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(resource_type_id));
+CREATE TABLE adminresource (resource_id BIGINT NOT NULL, resource_type_id INTEGER NOT NULL, PRIMARY KEY(resource_id));
+CREATE TABLE adminprincipaltype (principal_type_id INTEGER NOT NULL, principal_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(principal_type_id));
+CREATE TABLE adminprincipal (principal_id BIGINT NOT NULL, principal_type_id INTEGER NOT NULL, PRIMARY KEY(principal_id));
+CREATE TABLE adminpermission (permission_id BIGINT NOT NULL, permission_name VARCHAR(255) NOT NULL, resource_type_id INTEGER NOT NULL, PRIMARY KEY(permission_id));
+CREATE TABLE adminprivilege (privilege_id BIGINT, permission_id BIGINT NOT NULL, resource_id BIGINT NOT NULL, principal_id BIGINT NOT NULL, PRIMARY KEY(privilege_id));
+
 --------altering tables by creating foreign keys----------
 ALTER TABLE members ADD CONSTRAINT FK_members_group_id FOREIGN KEY (group_id) REFERENCES groups (group_id);
 ALTER TABLE members ADD CONSTRAINT FK_members_user_id FOREIGN KEY (user_id) REFERENCES users (user_id);
@@ -142,6 +149,16 @@ ALTER TABLE viewinstance ADD CONSTRAINT FK_viewinst_view_name FOREIGN KEY (view_
 ALTER TABLE viewinstanceproperty ADD CONSTRAINT FK_viewinstprop_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES viewinstance(view_name, name);
 ALTER TABLE viewinstancedata ADD CONSTRAINT FK_viewinstdata_view_name FOREIGN KEY (view_instance_id, view_name, view_instance_name) REFERENCES viewinstance(view_instance_id, view_name, name);
 ALTER TABLE viewentity ADD CONSTRAINT FK_viewentity_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES viewinstance(view_name, name);
+ALTER TABLE adminresource ADD CONSTRAINT FK_resource_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE adminprincipal ADD CONSTRAINT FK_principal_principal_type_id FOREIGN KEY (principal_type_id) REFERENCES adminprincipaltype(principal_type_id);
+ALTER TABLE adminpermission ADD CONSTRAINT FK_permission_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_permission_id FOREIGN KEY (permission_id) REFERENCES adminpermission(permission_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE viewmain ADD CONSTRAINT FK_view_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE viewinstance ADD CONSTRAINT FK_viewinstance_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE adminprivilege ADD CONSTRAINT FK_privilege_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE users ADD CONSTRAINT FK_users_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE groups ADD CONSTRAINT FK_groups_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
 
 -- Alerting Framework
 CREATE TABLE alert_definition (
@@ -258,19 +275,61 @@ BEGIN;
   union all
   select 'operation_level_id_seq', 1
   union all
-  select 'view_instance_id_seq', 1;
+  select 'view_instance_id_seq', 1
+  union all
+  select 'resource_type_id_seq', 4
+  union all
+  select 'resource_id_seq', 2
+  union all
+  select 'principal_type_id_seq', 3
+  union all
+  select 'principal_id_seq', 2
+  union all
+  select 'permission_id_seq', 5
+  union all
+  select 'privilege_id_seq', 1;
+
+  INSERT INTO adminresourcetype (resource_type_id, resource_type_name)
+  SELECT 1, 'AMBARI'
+  UNION ALL
+  SELECT 2, 'CLUSTER'
+  UNION ALL
+  SELECT 3, 'VIEW';
+
+  INSERT INTO adminresource (resource_id, resource_type_id)
+  SELECT 1, 1;
 
   INSERT INTO Roles (role_name)
   SELECT 'admin'
   UNION ALL
   SELECT 'user';
 
-  INSERT INTO Users (user_id, user_name, user_password)
-  SELECT 1, 'admin', '538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
+  INSERT INTO adminprincipaltype (principal_type_id, principal_type_name)
+  SELECT 1, 'USER'
+  UNION ALL
+  SELECT 2, 'GROUP';
+
+  INSERT INTO adminprincipal (principal_id, principal_type_id)
+  SELECT 1, 1;
+
+  INSERT INTO Users (user_id, principal_id, user_name, user_password)
+  SELECT 1, 1, 'admin', '538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
 
   INSERT INTO user_roles (role_name, user_id)
   SELECT 'admin', 1;
 
+  INSERT INTO adminpermission(permission_id, permission_name, resource_type_id)
+  SELECT 1, 'AMBARI.ADMIN', 1
+  UNION ALL
+  SELECT 2, 'CLUSTER.READ', 2
+  UNION ALL
+  SELECT 3, CLUSTER.OPERATE'', 2
+  UNION ALL
+  SELECT 4, 'VIEW.USE', 3;
+
+  INSERT INTO adminprivilege (privilege_id, permission_id, resource_id, principal_id)
+  SELECT 1, 1, 1, 1;
+
   INSERT INTO metainfo (metainfo_key, metainfo_value)
   SELECT 'version', '${ambariVersion}';
 COMMIT;

+ 72 - 7
ambari-server/src/main/resources/Ambari-DDL-Postgres-EMBEDDED-CREATE.sql

@@ -64,10 +64,10 @@ GRANT ALL PRIVILEGES ON TABLE ambari.servicedesiredstate TO :username;
 CREATE TABLE ambari.roles (role_name VARCHAR(255) NOT NULL, PRIMARY KEY (role_name));
 GRANT ALL PRIVILEGES ON TABLE ambari.roles TO :username;
 
-CREATE TABLE ambari.users (user_id INTEGER, ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, create_time TIMESTAMP DEFAULT NOW(), user_password VARCHAR(255), active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id), UNIQUE (ldap_user, user_name));
+CREATE TABLE ambari.users (user_id INTEGER, principal_id BIGINT NOT NULL, ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, create_time TIMESTAMP DEFAULT NOW(), user_password VARCHAR(255), active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id), UNIQUE (ldap_user, user_name));
 GRANT ALL PRIVILEGES ON TABLE ambari.users TO :username;
 
-CREATE TABLE ambari.groups (group_id INTEGER, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id), UNIQUE (ldap_group, group_name));
+CREATE TABLE ambari.groups (group_id INTEGER, principal_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id), UNIQUE (ldap_group, group_name));
 GRANT ALL PRIVILEGES ON TABLE ambari.groups TO :username;
 
 CREATE TABLE ambari.members (member_id INTEGER, group_id INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (member_id), UNIQUE(group_id, user_id));
@@ -138,9 +138,9 @@ GRANT ALL PRIVILEGES ON TABLE ambari.hostgroup_component TO :username;
 GRANT ALL PRIVILEGES ON TABLE ambari.blueprint_configuration TO :username;
 GRANT ALL PRIVILEGES ON TABLE ambari.hostgroup_configuration TO :username;
 
-CREATE TABLE ambari.viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
+CREATE TABLE ambari.viewmain (view_name VARCHAR(255) NOT NULL, label VARCHAR(255), version VARCHAR(255), resource_type_id INTEGER NOT NULL, icon VARCHAR(255), icon64 VARCHAR(255), archive VARCHAR(255), mask VARCHAR(255), PRIMARY KEY(view_name));
 CREATE TABLE ambari.viewinstancedata (view_instance_id BIGINT, view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, user_name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(view_instance_id, name, user_name));
-CREATE TABLE ambari.viewinstance (view_instance_id BIGINT, view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
+CREATE TABLE ambari.viewinstance (view_instance_id BIGINT, resource_id BIGINT NOT NULL, view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, label VARCHAR(255), description VARCHAR(255), visible CHAR(1), icon VARCHAR(255), icon64 VARCHAR(255), PRIMARY KEY(view_instance_id));
 CREATE TABLE ambari.viewinstanceproperty (view_name VARCHAR(255) NOT NULL, view_instance_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(2000) NOT NULL, PRIMARY KEY(view_name, view_instance_name, name));
 CREATE TABLE ambari.viewparameter (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, description VARCHAR(255), required CHAR(1), masked CHAR(1), PRIMARY KEY(view_name, name));
 CREATE TABLE ambari.viewresource (view_name VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, plural_name VARCHAR(255), id_property VARCHAR(255), subResource_names VARCHAR(255), provider VARCHAR(255), service VARCHAR(255), resource VARCHAR(255), PRIMARY KEY(view_name, name));
@@ -153,6 +153,19 @@ GRANT ALL PRIVILEGES ON TABLE ambari.viewparameter TO :username;
 GRANT ALL PRIVILEGES ON TABLE ambari.viewresource TO :username;
 GRANT ALL PRIVILEGES ON TABLE ambari.viewentity TO :username;
 
+CREATE TABLE ambari.adminresourcetype (resource_type_id INTEGER NOT NULL, resource_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(resource_type_id));
+CREATE TABLE ambari.adminresource (resource_id BIGINT NOT NULL, resource_type_id INTEGER NOT NULL, PRIMARY KEY(resource_id));
+CREATE TABLE ambari.adminprincipaltype (principal_type_id INTEGER NOT NULL, principal_type_name VARCHAR(255) NOT NULL, PRIMARY KEY(principal_type_id));
+CREATE TABLE ambari.adminprincipal (principal_id BIGINT NOT NULL, principal_type_id INTEGER NOT NULL, PRIMARY KEY(principal_id));
+CREATE TABLE ambari.adminpermission (permission_id BIGINT NOT NULL, permission_name VARCHAR(255) NOT NULL, resource_type_id INTEGER NOT NULL, PRIMARY KEY(permission_id));
+CREATE TABLE ambari.adminprivilege (privilege_id BIGINT, permission_id BIGINT NOT NULL, resource_id BIGINT NOT NULL, principal_id BIGINT NOT NULL, PRIMARY KEY(privilege_id));
+GRANT ALL PRIVILEGES ON TABLE ambari.adminresourcetype TO :username;
+GRANT ALL PRIVILEGES ON TABLE ambari.adminresource TO :username;
+GRANT ALL PRIVILEGES ON TABLE ambari.adminprincipaltype TO :username;
+GRANT ALL PRIVILEGES ON TABLE ambari.adminprincipal TO :username;
+GRANT ALL PRIVILEGES ON TABLE ambari.adminpermission TO :username;
+GRANT ALL PRIVILEGES ON TABLE ambari.adminprivilege TO :username;
+
 --------altering tables by creating foreign keys----------
 ALTER TABLE members ADD CONSTRAINT FK_members_group_id FOREIGN KEY (group_id) REFERENCES groups (group_id);
 ALTER TABLE members ADD CONSTRAINT FK_members_user_id FOREIGN KEY (user_id) REFERENCES users (user_id);
@@ -199,6 +212,16 @@ ALTER TABLE ambari.viewinstance ADD CONSTRAINT FK_viewinst_view_name FOREIGN KEY
 ALTER TABLE ambari.viewinstanceproperty ADD CONSTRAINT FK_viewinstprop_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES ambari.viewinstance(view_name, name);
 ALTER TABLE ambari.viewinstancedata ADD CONSTRAINT FK_viewinstdata_view_name FOREIGN KEY (view_instance_id, view_name, view_instance_name) REFERENCES ambari.viewinstance(view_instance_id, view_name, name);
 ALTER TABLE ambari.viewentity ADD CONSTRAINT FK_viewentity_view_name FOREIGN KEY (view_name, view_instance_name) REFERENCES ambari.viewinstance(view_name, name);
+ALTER TABLE ambari.adminresource ADD CONSTRAINT FK_resource_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE ambari.adminprincipal ADD CONSTRAINT FK_principal_principal_type_id FOREIGN KEY (principal_type_id) REFERENCES adminprincipaltype(principal_type_id);
+ALTER TABLE ambari.adminpermission ADD CONSTRAINT FK_permission_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE ambari.adminprivilege ADD CONSTRAINT FK_privilege_permission_id FOREIGN KEY (permission_id) REFERENCES adminpermission(permission_id);
+ALTER TABLE ambari.adminprivilege ADD CONSTRAINT FK_privilege_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE viewmain ADD CONSTRAINT FK_view_resource_type_id FOREIGN KEY (resource_type_id) REFERENCES adminresourcetype(resource_type_id);
+ALTER TABLE ambari.viewinstance ADD CONSTRAINT FK_viewinstance_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id);
+ALTER TABLE ambari.adminprivilege ADD CONSTRAINT FK_privilege_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE ambari.users ADD CONSTRAINT FK_users_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
+ALTER TABLE ambari.groups ADD CONSTRAINT FK_groups_principal_id FOREIGN KEY (principal_id) REFERENCES adminprincipal(principal_id);
 
 -- Alerting Framework
 CREATE TABLE ambari.alert_definition (
@@ -325,20 +348,62 @@ INSERT INTO ambari.ambari_sequences (sequence_name, "value")
   union all
   select 'operation_level_id_seq', 1
   union all
-  select 'view_instance_id_seq', 1;
+  select 'view_instance_id_seq', 1
+  union all
+  select 'resource_type_id_seq', 4
+  union all
+  select 'resource_id_seq', 2
+  union all
+  select 'principal_type_id_seq', 3
+  union all
+  select 'principal_id_seq', 2
+  union all
+  select 'permission_id_seq', 5
+  union all
+  select 'privilege_id_seq', 1;
+
 
+INSERT INTO ambari.adminresourcetype (resource_type_id, resource_type_name)
+  SELECT 1, 'AMBARI'
+  UNION ALL
+  SELECT 2, 'CLUSTER'
+  UNION ALL
+  SELECT 3, 'VIEW';
+
+INSERT INTO ambari.adminresource (resource_id, resource_type_id)
+  SELECT 1, 1;
 
 INSERT INTO ambari.Roles (role_name)
   SELECT 'admin'
   UNION ALL
   SELECT 'user';
 
-INSERT INTO ambari.Users (user_id, user_name, user_password)
-  SELECT 1, 'admin', '538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
+INSERT INTO ambari.adminprincipaltype (principal_type_id, principal_type_name)
+  SELECT 1, 'USER'
+  UNION ALL
+  SELECT 2, 'GROUP';
+
+INSERT INTO ambari.adminprincipal (principal_id, principal_type_id)
+  SELECT 1, 1;
+
+INSERT INTO ambari.Users (user_id, principal_id, user_name, user_password)
+  SELECT 1, 1, 'admin', '538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
 
 INSERT INTO ambari.user_roles (role_name, user_id)
   SELECT 'admin', 1;
 
+INSERT INTO ambari.adminpermission(permission_id, permission_name, resource_type_id)
+  SELECT 1, 'AMBARI.ADMIN', 1
+  UNION ALL
+  SELECT 2, 'CLUSTER.READ', 2
+  UNION ALL
+  SELECT 3, 'CLUSTER.OPERATE', 2
+  UNION ALL
+  SELECT 4, 'VIEW.USE', 3;
+
+INSERT INTO ambari.adminprivilege (privilege_id, permission_id, resource_id, principal_id)
+  SELECT 1, 1, 1, 1;
+
 INSERT INTO ambari.metainfo (metainfo_key, metainfo_value)
   SELECT 'version', '${ambariVersion}';
 COMMIT;

+ 6 - 0
ambari-server/src/main/resources/META-INF/persistence.xml

@@ -62,6 +62,12 @@
     <class>org.apache.ambari.server.orm.entities.AlertHistoryEntity</class>
     <class>org.apache.ambari.server.orm.entities.AlertNoticeEntity</class>
     <class>org.apache.ambari.server.orm.entities.AlertTargetEntity</class>
+    <class>org.apache.ambari.server.orm.entities.ResourceTypeEntity</class>
+    <class>org.apache.ambari.server.orm.entities.ResourceEntity</class>
+    <class>org.apache.ambari.server.orm.entities.PrincipalTypeEntity</class>
+    <class>org.apache.ambari.server.orm.entities.PrincipalEntity</class>
+    <class>org.apache.ambari.server.orm.entities.PermissionEntity</class>
+    <class>org.apache.ambari.server.orm.entities.PrivilegeEntity</class>
 
     <properties>
       <!--<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/ambari" />-->

+ 50 - 0
ambari-server/src/test/java/org/apache/ambari/server/api/resources/PrivilegeResourceDefinitionTest.java

@@ -0,0 +1,50 @@
+/**
+ * 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.ambari.server.api.resources;
+
+import org.apache.ambari.server.controller.spi.Resource;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Set;
+
+/**
+ * PrivilegeResourceDefinition tests.
+ */
+public class PrivilegeResourceDefinitionTest {
+  @Test
+  public void testGetPluralName() throws Exception {
+    PrivilegeResourceDefinition privilegeResourceDefinition = new PrivilegeResourceDefinition(Resource.Type.AmbariPrivilege);
+    Assert.assertEquals("privileges", privilegeResourceDefinition.getPluralName());
+  }
+
+  @Test
+  public void testGetSingularName() throws Exception {
+    PrivilegeResourceDefinition privilegeResourceDefinition = new PrivilegeResourceDefinition(Resource.Type.AmbariPrivilege);
+    Assert.assertEquals("privilege", privilegeResourceDefinition.getSingularName());
+  }
+
+  @Test
+  public void testGetSubResourceDefinitions() throws Exception {
+    PrivilegeResourceDefinition privilegeResourceDefinition = new PrivilegeResourceDefinition(Resource.Type.AmbariPrivilege);
+    Set<SubResourceDefinition> subResourceDefinitions = privilegeResourceDefinition.getSubResourceDefinitions ();
+
+    Assert.assertEquals(0, subResourceDefinitions.size());
+  }
+}

+ 2 - 2
ambari-server/src/test/java/org/apache/ambari/server/api/resources/ViewInstanceResourceDefinitionTest.java

@@ -46,11 +46,11 @@ public class ViewInstanceResourceDefinitionTest {
     ViewInstanceResourceDefinition viewInstanceResourceDefinition = getViewInstanceResourceDefinition();
     Set<SubResourceDefinition> subResourceDefinitions = viewInstanceResourceDefinition.getSubResourceDefinitions();
 
-    Assert.assertEquals(2, subResourceDefinitions.size());
+    Assert.assertEquals(3, subResourceDefinitions.size());
 
     for (SubResourceDefinition subResourceDefinition : subResourceDefinitions) {
       Resource.Type type = subResourceDefinition.getType();
-      Assert.assertTrue(type.name().equals("sub1") || type.name().equals("sub2"));
+      Assert.assertTrue(type.name().equals("sub1") || type.name().equals("sub2") || type.equals(Resource.Type.ViewPrivilege));
     }
   }
 

+ 106 - 0
ambari-server/src/test/java/org/apache/ambari/server/api/services/PrivilegeServiceTest.java

@@ -0,0 +1,106 @@
+/**
+ * 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.ambari.server.api.services;
+
+import org.apache.ambari.server.api.resources.ResourceInstance;
+import org.apache.ambari.server.api.services.parsers.RequestBodyParser;
+import org.apache.ambari.server.api.services.serializers.ResultSerializer;
+
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.UriInfo;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+
+/**
+ * Unit tests for PrivilegeService.
+ */
+public class PrivilegeServiceTest extends BaseServiceTest {
+
+
+  public List<ServiceTestInvocation> getTestInvocations() throws Exception {
+    List<ServiceTestInvocation> listInvocations = new ArrayList<ServiceTestInvocation>();
+
+    //getPrivilege
+    PrivilegeService service = new TestPrivilegeService("id");
+    Method m = service.getClass().getMethod("getPrivilege", HttpHeaders.class, UriInfo.class, String.class);
+    Object[] args = new Object[] {getHttpHeaders(), getUriInfo(), "id"};
+    listInvocations.add(new ServiceTestInvocation(Request.Type.GET, service, m, args, null));
+
+    //getPrivileges
+    service = new TestPrivilegeService(null);
+    m = service.getClass().getMethod("getPrivileges", HttpHeaders.class, UriInfo.class);
+    args = new Object[] {getHttpHeaders(), getUriInfo()};
+    listInvocations.add(new ServiceTestInvocation(Request.Type.GET, service, m, args, null));
+
+    //createPrivilege
+    service = new TestPrivilegeService(null);
+    m = service.getClass().getMethod("createPrivilege", String.class, HttpHeaders.class, UriInfo.class);
+    args = new Object[] {"body", getHttpHeaders(), getUriInfo()};
+    listInvocations.add(new ServiceTestInvocation(Request.Type.POST, service, m, args, "body"));
+
+    //updatePrivilege
+    service = new TestPrivilegeService("id");
+    m = service.getClass().getMethod("updatePrivilege", String.class, HttpHeaders.class, UriInfo.class, String.class);
+    args = new Object[] {"body", getHttpHeaders(), getUriInfo(), "id"};
+    listInvocations.add(new ServiceTestInvocation(Request.Type.PUT, service, m, args, "body"));
+
+    //deletePrivilege
+    service = new TestPrivilegeService("id");
+    m = service.getClass().getMethod("deletePrivilege", HttpHeaders.class, UriInfo.class, String.class);
+    args = new Object[] {getHttpHeaders(), getUriInfo(), "id"};
+    listInvocations.add(new ServiceTestInvocation(Request.Type.DELETE, service, m, args, null));
+
+    return listInvocations;
+  }
+
+
+  private class TestPrivilegeService extends PrivilegeService {
+    private String id;
+
+    private TestPrivilegeService(String id) {
+      this.id = id;
+    }
+
+    @Override
+    protected ResourceInstance createPrivilegeResource(String id) {
+      assertEquals(this.id, id);
+      return getTestResource();
+    }
+
+    @Override
+    RequestFactory getRequestFactory() {
+      return getTestRequestFactory();
+    }
+
+    @Override
+    protected RequestBodyParser getBodyParser() {
+      return getTestBodyParser();
+    }
+
+    @Override
+    protected ResultSerializer getResultSerializer() {
+      return getTestResultSerializer();
+    }
+  }
+}

+ 141 - 0
ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProviderTest.java

@@ -0,0 +1,141 @@
+/**
+ * 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.ambari.server.controller.internal;
+
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+import org.apache.ambari.server.orm.dao.GroupDAO;
+import org.apache.ambari.server.orm.dao.PermissionDAO;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrivilegeDAO;
+import org.apache.ambari.server.orm.dao.ResourceDAO;
+import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.GroupEntity;
+import org.apache.ambari.server.orm.entities.PermissionEntity;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
+import org.apache.ambari.server.orm.entities.PrivilegeEntity;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+import org.apache.ambari.server.orm.entities.UserEntity;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import static org.easymock.EasyMock.createNiceMock;
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+import static org.easymock.EasyMock.verify;
+
+/**
+ * AmbariPrivilegeResourceProvider tests.
+ */
+public class AmbariPrivilegeResourceProviderTest {
+  private final static PrivilegeDAO privilegeDAO = createStrictMock(PrivilegeDAO.class);
+  private final static UserDAO userDAO = createStrictMock(UserDAO.class);
+  private final static GroupDAO groupDAO = createStrictMock(GroupDAO.class);
+  private final static PrincipalDAO principalDAO = createStrictMock(PrincipalDAO.class);
+  private final static PermissionDAO permissionDAO = createStrictMock(PermissionDAO.class);
+  private final static ResourceDAO resourceDAO = createStrictMock(ResourceDAO.class);
+
+  @BeforeClass
+  public static void initClass() {
+    AmbariPrivilegeResourceProvider.init(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO);
+  }
+
+  @Before
+  public void resetGlobalMocks() {
+    reset(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO);
+  }
+
+  @Test
+  public void testGetResources() throws Exception {
+
+    List<PrivilegeEntity> privilegeEntities = new LinkedList<PrivilegeEntity>();
+
+    PrivilegeEntity privilegeEntity = createNiceMock(PrivilegeEntity.class);
+    ResourceEntity resourceEntity = createNiceMock(ResourceEntity.class);
+    UserEntity userEntity = createNiceMock(UserEntity.class);
+    PrincipalEntity principalEntity = createNiceMock(PrincipalEntity.class);
+    PrincipalTypeEntity principalTypeEntity = createNiceMock(PrincipalTypeEntity.class);
+    PermissionEntity permissionEntity = createNiceMock(PermissionEntity.class);
+
+    List<PrincipalEntity> principalEntities = new LinkedList<PrincipalEntity>();
+    principalEntities.add(principalEntity);
+
+    List<UserEntity> userEntities = new LinkedList<UserEntity>();
+    userEntities.add(userEntity);
+
+    privilegeEntities.add(privilegeEntity);
+
+    expect(privilegeDAO.findAll()).andReturn(privilegeEntities);
+    expect(privilegeEntity.getResource()).andReturn(resourceEntity).anyTimes();
+    expect(privilegeEntity.getPrincipal()).andReturn(principalEntity).anyTimes();
+    expect(privilegeEntity.getPermission()).andReturn(permissionEntity).anyTimes();
+    expect(resourceEntity.getId()).andReturn(1L).anyTimes();
+    expect(principalEntity.getId()).andReturn(1L).anyTimes();
+    expect(userEntity.getPrincipal()).andReturn(principalEntity).anyTimes();
+    expect(userEntity.getUserName()).andReturn("joe").anyTimes();
+    expect(permissionEntity.getPermissionName()).andReturn("AMBARI.ADMIN").anyTimes();
+    expect(principalEntity.getPrincipalType()).andReturn(principalTypeEntity).anyTimes();
+    expect(principalTypeEntity.getName()).andReturn("USER").anyTimes();
+
+    expect(userDAO.findUsersByPrincipal(principalEntities)).andReturn(userEntities);
+    expect(groupDAO.findGroupsByPrincipal(principalEntities)).andReturn(Collections.<GroupEntity>emptyList());
+
+    replay(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO, privilegeEntity, resourceEntity,
+        userEntity, principalEntity, permissionEntity, principalTypeEntity);
+
+    PrivilegeResourceProvider provider = new AmbariPrivilegeResourceProvider();
+    Set<Resource> resources = provider.getResources(PropertyHelper.getReadRequest(), null);
+
+    Assert.assertEquals(1, resources.size());
+
+    Resource resource = resources.iterator().next();
+
+    Assert.assertEquals("AMBARI.ADMIN", resource.getPropertyValue(AmbariPrivilegeResourceProvider.PERMISSION_NAME_PROPERTY_ID));
+    Assert.assertEquals("joe", resource.getPropertyValue(AmbariPrivilegeResourceProvider.PRINCIPAL_NAME_PROPERTY_ID));
+    Assert.assertEquals("USER", resource.getPropertyValue(AmbariPrivilegeResourceProvider.PRINCIPAL_TYPE_PROPERTY_ID));
+
+    verify(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO, privilegeEntity, resourceEntity,
+        userEntity, principalEntity, permissionEntity, principalTypeEntity);
+  }
+
+  @Test
+  public void testUpdateResources() throws Exception {
+    PrivilegeResourceProvider provider = new AmbariPrivilegeResourceProvider();
+
+    Request request = createNiceMock(Request.class);
+
+    try {
+      provider.updateResources(request, null);
+      Assert.fail("expected UnsupportedOperationException");
+    } catch (UnsupportedOperationException e) {
+      // expected
+    }
+  }
+}

+ 46 - 1
ambari-server/src/test/java/org/apache/ambari/server/controller/internal/PermissionResourceProviderTest.java

@@ -21,17 +21,42 @@ package org.apache.ambari.server.controller.internal;
 import org.apache.ambari.server.controller.spi.Request;
 import org.apache.ambari.server.controller.spi.Resource;
 import org.apache.ambari.server.controller.utilities.PropertyHelper;
+import org.apache.ambari.server.orm.dao.PermissionDAO;
+import org.apache.ambari.server.orm.entities.PermissionEntity;
+import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
 import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.Test;
 
+import java.util.LinkedList;
+import java.util.List;
 import java.util.Set;
 
 import static org.easymock.EasyMock.createNiceMock;
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+import static org.easymock.EasyMock.verify;
 
 /**
  * PermissionResourceProvider tests.
  */
 public class PermissionResourceProviderTest {
+
+  private final static PermissionDAO dao = createStrictMock(PermissionDAO.class);
+
+  @BeforeClass
+  public static void initClass() {
+    PermissionResourceProvider.init(dao);
+  }
+
+  @Before
+  public void resetGlobalMocks() {
+    reset(dao);
+  }
+
   @Test
   public void testCreateResources() throws Exception {
     PermissionResourceProvider provider = new PermissionResourceProvider();
@@ -48,10 +73,30 @@ public class PermissionResourceProviderTest {
 
   @Test
   public void testGetResources() throws Exception {
+    List<PermissionEntity> permissionEntities = new LinkedList<PermissionEntity>();
+
+    PermissionEntity permissionEntity = createNiceMock(PermissionEntity.class);
+    ResourceTypeEntity resourceTypeEntity = createNiceMock(ResourceTypeEntity.class);
+
+    permissionEntities.add(permissionEntity);
+
+    expect(dao.findAll()).andReturn(permissionEntities);
+    expect(permissionEntity.getId()).andReturn(99);
+    expect(permissionEntity.getPermissionName()).andReturn("AMBARI.ADMIN");
+    expect(permissionEntity.getResourceType()).andReturn(resourceTypeEntity);
+    expect(resourceTypeEntity.getName()).andReturn("AMBARI");
+
+    replay(dao, permissionEntity, resourceTypeEntity);
     PermissionResourceProvider provider = new PermissionResourceProvider();
     Set<Resource> resources = provider.getResources(PropertyHelper.getReadRequest(), null);
     // built in permissions
-    Assert.assertEquals(4, resources.size());
+    Assert.assertEquals(1, resources.size());
+    Resource resource = resources.iterator().next();
+
+    Assert.assertEquals(99, resource.getPropertyValue(PermissionResourceProvider.PERMISSION_ID_PROPERTY_ID));
+    Assert.assertEquals("AMBARI.ADMIN", resource.getPropertyValue(PermissionResourceProvider.PERMISSION_NAME_PROPERTY_ID));
+    Assert.assertEquals("AMBARI", resource.getPropertyValue(PermissionResourceProvider.RESOURCE_NAME_PROPERTY_ID));
+    verify(dao, permissionEntity, resourceTypeEntity);
   }
 
   @Test

+ 167 - 0
ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ViewPrivilegeResourceProviderTest.java

@@ -0,0 +1,167 @@
+/**
+ * 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.ambari.server.controller.internal;
+
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.utilities.PropertyHelper;
+import org.apache.ambari.server.orm.dao.GroupDAO;
+import org.apache.ambari.server.orm.dao.PermissionDAO;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrivilegeDAO;
+import org.apache.ambari.server.orm.dao.ResourceDAO;
+import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.GroupEntity;
+import org.apache.ambari.server.orm.entities.PermissionEntity;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
+import org.apache.ambari.server.orm.entities.PrivilegeEntity;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+import org.apache.ambari.server.orm.entities.UserEntity;
+import org.apache.ambari.server.orm.entities.ViewEntity;
+import org.apache.ambari.server.orm.entities.ViewEntityTest;
+import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
+import org.apache.ambari.server.orm.entities.ViewInstanceEntityTest;
+import org.apache.ambari.server.view.ViewRegistry;
+import org.apache.ambari.server.view.ViewRegistryTest;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import static org.easymock.EasyMock.createNiceMock;
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+import static org.easymock.EasyMock.verify;
+
+/**
+ * ViewPrivilegeResourceProvider tests.
+ */
+public class ViewPrivilegeResourceProviderTest {
+  private final static PrivilegeDAO privilegeDAO = createStrictMock(PrivilegeDAO.class);
+  private final static UserDAO userDAO = createStrictMock(UserDAO.class);
+  private final static GroupDAO groupDAO = createStrictMock(GroupDAO.class);
+  private final static PrincipalDAO principalDAO = createStrictMock(PrincipalDAO.class);
+  private final static PermissionDAO permissionDAO = createStrictMock(PermissionDAO.class);
+  private final static ResourceDAO resourceDAO = createStrictMock(ResourceDAO.class);
+
+  @BeforeClass
+  public static void initClass() {
+    AmbariPrivilegeResourceProvider.init(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO);
+  }
+
+  @Before
+  public void resetGlobalMocks() {
+    ViewRegistryTest.clear();
+    reset(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO);
+  }
+
+  @AfterClass
+  public static void afterClass() {
+    ViewRegistryTest.clear();
+  }
+
+  @Test
+  public void testGetResources() throws Exception {
+
+    ViewEntity viewDefinition = ViewEntityTest.getViewEntity();
+    ViewInstanceEntity viewInstanceDefinition = ViewInstanceEntityTest.getViewInstanceEntity();
+
+    viewDefinition.addInstanceDefinition(viewInstanceDefinition);
+
+    ViewRegistry registry = ViewRegistry.getInstance();
+
+    registry.addDefinition(viewDefinition);
+
+    registry.addInstanceDefinition(viewDefinition, viewInstanceDefinition);
+
+
+    List<PrivilegeEntity> privilegeEntities = new LinkedList<PrivilegeEntity>();
+
+    PrivilegeEntity privilegeEntity = createNiceMock(PrivilegeEntity.class);
+    ResourceEntity resourceEntity = createNiceMock(ResourceEntity.class);
+    UserEntity userEntity = createNiceMock(UserEntity.class);
+    PrincipalEntity principalEntity = createNiceMock(PrincipalEntity.class);
+    PrincipalTypeEntity principalTypeEntity = createNiceMock(PrincipalTypeEntity.class);
+    PermissionEntity permissionEntity = createNiceMock(PermissionEntity.class);
+
+    List<PrincipalEntity> principalEntities = new LinkedList<PrincipalEntity>();
+    principalEntities.add(principalEntity);
+
+    List<UserEntity> userEntities = new LinkedList<UserEntity>();
+    userEntities.add(userEntity);
+
+    privilegeEntities.add(privilegeEntity);
+
+    expect(privilegeDAO.findAll()).andReturn(privilegeEntities);
+    expect(privilegeEntity.getResource()).andReturn(resourceEntity).anyTimes();
+    expect(privilegeEntity.getPrincipal()).andReturn(principalEntity).anyTimes();
+    expect(privilegeEntity.getPermission()).andReturn(permissionEntity).anyTimes();
+    expect(resourceEntity.getId()).andReturn(20L).anyTimes();
+    expect(principalEntity.getId()).andReturn(20L).anyTimes();
+    expect(userEntity.getPrincipal()).andReturn(principalEntity).anyTimes();
+    expect(userEntity.getUserName()).andReturn("joe").anyTimes();
+    expect(permissionEntity.getPermissionName()).andReturn("VIEW.USE").anyTimes();
+    expect(principalEntity.getPrincipalType()).andReturn(principalTypeEntity).anyTimes();
+    expect(principalTypeEntity.getName()).andReturn("USER").anyTimes();
+
+    expect(userDAO.findUsersByPrincipal(principalEntities)).andReturn(userEntities);
+    expect(groupDAO.findGroupsByPrincipal(principalEntities)).andReturn(Collections.<GroupEntity>emptyList());
+
+    replay(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO, privilegeEntity, resourceEntity,
+        userEntity, principalEntity, permissionEntity, principalTypeEntity);
+
+    PrivilegeResourceProvider provider = new ViewPrivilegeResourceProvider();
+    Set<Resource> resources = provider.getResources(PropertyHelper.getReadRequest(), null);
+
+    Assert.assertEquals(1, resources.size());
+
+    Resource resource = resources.iterator().next();
+
+    Assert.assertEquals("VIEW.USE", resource.getPropertyValue(AmbariPrivilegeResourceProvider.PERMISSION_NAME_PROPERTY_ID));
+    Assert.assertEquals("joe", resource.getPropertyValue(AmbariPrivilegeResourceProvider.PRINCIPAL_NAME_PROPERTY_ID));
+    Assert.assertEquals("USER", resource.getPropertyValue(AmbariPrivilegeResourceProvider.PRINCIPAL_TYPE_PROPERTY_ID));
+
+    verify(privilegeDAO, userDAO, groupDAO, principalDAO, permissionDAO, resourceDAO, privilegeEntity, resourceEntity,
+        userEntity, principalEntity, permissionEntity, principalTypeEntity);
+  }
+
+  @Test
+  public void testUpdateResources() throws Exception {
+    PrivilegeResourceProvider provider = new ViewPrivilegeResourceProvider();
+
+    Request request = createNiceMock(Request.class);
+
+    try {
+      provider.updateResources(request, null);
+      Assert.fail("expected UnsupportedOperationException");
+    } catch (UnsupportedOperationException e) {
+      // expected
+    }
+  }
+}
+

+ 15 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/OrmTestHelper.java

@@ -108,6 +108,15 @@ public class OrmTestHelper {
 
   @Transactional
   public void createTestUsers() {
+    PrincipalTypeEntity principalTypeEntity = new PrincipalTypeEntity();
+    principalTypeEntity.setName(PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME);
+    getEntityManager().persist(principalTypeEntity);
+
+    PrincipalEntity principalEntity = new PrincipalEntity();
+    principalEntity.setPrincipalType(principalTypeEntity);
+
+    getEntityManager().persist(principalEntity);
+
     PasswordEncoder encoder = injector.getInstance(PasswordEncoder.class);
 
     RoleEntity adminRole = new RoleEntity();
@@ -116,6 +125,7 @@ public class OrmTestHelper {
     UserEntity admin = new UserEntity();
     admin.setUserName("administrator");
     admin.setUserPassword(encoder.encode("admin"));
+    admin.setPrincipal(principalEntity);
 
     Set<RoleEntity> roles = new HashSet<RoleEntity>();
     Set<UserEntity> users = new HashSet<UserEntity>();
@@ -129,9 +139,14 @@ public class OrmTestHelper {
     userDAO.create(admin);
     roleDAO.create(adminRole);
 
+    principalEntity = new PrincipalEntity();
+    principalEntity.setPrincipalType(principalTypeEntity);
+    getEntityManager().persist(principalEntity);
+
     UserEntity userWithoutRoles = new UserEntity();
     userWithoutRoles.setUserName("userWithoutRoles");
     userWithoutRoles.setUserPassword(encoder.encode("test"));
+    userWithoutRoles.setPrincipal(principalEntity);
     userDAO.create(userWithoutRoles);
 
   }

+ 61 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/dao/PrincipalDAOTest.java

@@ -0,0 +1,61 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Provider;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+
+/**
+ * PrincipalDAO tests
+ */
+public class PrincipalDAOTest {
+  Provider<EntityManager> entityManagerProvider = createStrictMock(Provider.class);
+  EntityManager entityManager = createStrictMock(EntityManager.class);
+
+  @Before
+  public void init() {
+    reset(entityManagerProvider);
+    expect(entityManagerProvider.get()).andReturn(entityManager).atLeastOnce();
+    replay(entityManagerProvider);
+  }
+
+  @Test
+  public void testFindById() throws Exception {
+    PrincipalEntity entity = new PrincipalEntity();
+
+    // set expectations
+    expect(entityManager.find(PrincipalEntity.class, 99L)).andReturn(entity);
+    replay(entityManager);
+
+    PrincipalDAO dao = new PrincipalDAO();
+    dao.entityManagerProvider = entityManagerProvider;
+
+    Assert.assertEquals(entity, dao.findById(99L));
+  }
+}

+ 61 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/dao/PrincipalTypeDAOTest.java

@@ -0,0 +1,61 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Provider;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+
+/**
+ * PrincipalTypeDAO tests
+ */
+public class PrincipalTypeDAOTest {
+  Provider<EntityManager> entityManagerProvider = createStrictMock(Provider.class);
+  EntityManager entityManager = createStrictMock(EntityManager.class);
+
+  @Before
+  public void init() {
+    reset(entityManagerProvider);
+    expect(entityManagerProvider.get()).andReturn(entityManager).atLeastOnce();
+    replay(entityManagerProvider);
+  }
+
+  @Test
+  public void testFindById() throws Exception {
+    PrincipalTypeEntity entity = new PrincipalTypeEntity();
+
+    // set expectations
+    expect(entityManager.find(PrincipalTypeEntity.class, 99)).andReturn(entity);
+    replay(entityManager);
+
+    PrincipalTypeDAO dao = new PrincipalTypeDAO();
+    dao.entityManagerProvider = entityManagerProvider;
+
+    Assert.assertEquals(entity, dao.findById(99));
+  }
+}

+ 61 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/dao/ResourceDAOTest.java

@@ -0,0 +1,61 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Provider;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+
+/**
+ * ResourceDAO tests
+ */
+public class ResourceDAOTest {
+  Provider<EntityManager> entityManagerProvider = createStrictMock(Provider.class);
+  EntityManager entityManager = createStrictMock(EntityManager.class);
+
+  @Before
+  public void init() {
+    reset(entityManagerProvider);
+    expect(entityManagerProvider.get()).andReturn(entityManager).atLeastOnce();
+    replay(entityManagerProvider);
+  }
+
+  @Test
+  public void testFindById() throws Exception {
+    ResourceEntity entity = new ResourceEntity();
+
+    // set expectations
+    expect(entityManager.find(ResourceEntity.class, 99L)).andReturn(entity);
+    replay(entityManager);
+
+    ResourceDAO dao = new ResourceDAO();
+    dao.entityManagerProvider = entityManagerProvider;
+
+    Assert.assertEquals(entity, dao.findById(99L));
+  }
+}

+ 61 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/dao/ResourceTypeDAOTest.java

@@ -0,0 +1,61 @@
+/**
+ * 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.ambari.server.orm.dao;
+
+import com.google.inject.Provider;
+import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.persistence.EntityManager;
+
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.reset;
+
+/**
+ * ResourceTypeDAO tests
+ */
+public class ResourceTypeDAOTest {
+  Provider<EntityManager> entityManagerProvider = createStrictMock(Provider.class);
+  EntityManager entityManager = createStrictMock(EntityManager.class);
+
+  @Before
+  public void init() {
+    reset(entityManagerProvider);
+    expect(entityManagerProvider.get()).andReturn(entityManager).atLeastOnce();
+    replay(entityManagerProvider);
+  }
+
+  @Test
+  public void testFindById() throws Exception {
+    ResourceTypeEntity entity = new ResourceTypeEntity();
+
+    // set expectations
+    expect(entityManager.find(ResourceTypeEntity.class, 99)).andReturn(entity);
+    replay(entityManager);
+
+    ResourceTypeDAO dao = new ResourceTypeDAO();
+    dao.entityManagerProvider = entityManagerProvider;
+
+    Assert.assertEquals(entity, dao.findById(99));
+  }
+}

+ 47 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/entities/PrincipalEntityTest.java

@@ -0,0 +1,47 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * PrincipalEntity tests.
+ */
+public class PrincipalEntityTest {
+  @Test
+  public void testSetGetId() throws Exception {
+    PrincipalEntity entity = new PrincipalEntity();
+
+    entity.setId(1L);
+    Assert.assertEquals(1L, (long) entity.getId());
+
+    entity.setId(99L);
+    Assert.assertEquals(99L, (long) entity.getId());
+  }
+
+  @Test
+  public void testSetGetPrincipalType() throws Exception {
+    PrincipalEntity entity = new PrincipalEntity();
+    PrincipalTypeEntity typeEntity = new PrincipalTypeEntity();
+
+    entity.setPrincipalType(typeEntity);
+    Assert.assertEquals(typeEntity, entity.getPrincipalType());
+  }
+}

+ 49 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/entities/PrincipalTypeEntityTest.java

@@ -0,0 +1,49 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * PrincipalTypeEntity tests.
+ */
+public class PrincipalTypeEntityTest {
+  @Test
+  public void testSetGetId() throws Exception {
+    PrincipalTypeEntity principalTypeEntity = new PrincipalTypeEntity();
+
+    principalTypeEntity.setId(1);
+    Assert.assertEquals(1L, (long) principalTypeEntity.getId());
+
+    principalTypeEntity.setId(99);
+    Assert.assertEquals(99L, (long) principalTypeEntity.getId());
+  }
+
+  @Test
+  public void testSetGetName() throws Exception {
+    PrincipalTypeEntity principalTypeEntity = new PrincipalTypeEntity();
+
+    principalTypeEntity.setName("foo");
+    Assert.assertEquals("foo", principalTypeEntity.getName());
+
+    principalTypeEntity.setName("bar");
+    Assert.assertEquals("bar", principalTypeEntity.getName());
+  }
+}

+ 47 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ResourceEntityTest.java

@@ -0,0 +1,47 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * ResourceEntity tests.
+ */
+public class ResourceEntityTest {
+  @Test
+  public void testSetGetId() throws Exception {
+    ResourceEntity entity = new ResourceEntity();
+
+    entity.setId(1L);
+    Assert.assertEquals(1L, (long) entity.getId());
+
+    entity.setId(99L);
+    Assert.assertEquals(99L, (long) entity.getId());
+  }
+
+  @Test
+  public void testSetGetResourceType() throws Exception {
+    ResourceEntity entity = new ResourceEntity();
+    ResourceTypeEntity typeEntity = new ResourceTypeEntity();
+
+    entity.setResourceType(typeEntity);
+    Assert.assertEquals(typeEntity, entity.getResourceType());
+  }
+}

+ 49 - 0
ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ResourceTypeEntityTest.java

@@ -0,0 +1,49 @@
+/**
+ * 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.ambari.server.orm.entities;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * ResourceTypeEntity tests.
+ */
+public class ResourceTypeEntityTest {
+  @Test
+  public void testSetGetId() throws Exception {
+    ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity();
+
+    resourceTypeEntity.setId(1);
+    Assert.assertEquals(1L, (long) resourceTypeEntity.getId());
+
+    resourceTypeEntity.setId(99);
+    Assert.assertEquals(99L, (long) resourceTypeEntity.getId());
+  }
+
+  @Test
+  public void testSetGetName() throws Exception {
+    ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity();
+
+    resourceTypeEntity.setName("foo");
+    Assert.assertEquals("foo", resourceTypeEntity.getName());
+
+    resourceTypeEntity.setName("bar");
+    Assert.assertEquals("bar", resourceTypeEntity.getName());
+  }
+}

+ 16 - 1
ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ViewEntityTest.java

@@ -55,7 +55,22 @@ public class ViewEntityTest {
     properties.put("p3", "v3");
 
     Configuration ambariConfig = new Configuration(properties);
-    return new ViewEntity(viewConfig, ambariConfig, ViewEntityTest.class.getClassLoader(), "view.jar");
+    ViewEntity viewEntity = new ViewEntity(viewConfig, ambariConfig, ViewEntityTest.class.getClassLoader(), "view.jar");
+
+    ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity();
+    resourceTypeEntity.setId(10);
+    resourceTypeEntity.setName(viewEntity.getName());
+
+    viewEntity.setResourceType(resourceTypeEntity);
+
+    long id = 20L;
+    for (ViewInstanceEntity viewInstanceEntity : viewEntity.getInstances()) {
+      ResourceEntity resourceEntity = new ResourceEntity();
+      resourceEntity.setId(id++);
+      resourceEntity.setResourceType(resourceTypeEntity);
+      viewInstanceEntity.setResource(resourceEntity);
+    }
+    return viewEntity;
   }
 
   @Test

+ 14 - 1
ambari-server/src/test/java/org/apache/ambari/server/orm/entities/ViewInstanceEntityTest.java

@@ -361,7 +361,20 @@ public class ViewInstanceEntityTest {
   public static ViewInstanceEntity getViewInstanceEntity() throws Exception {
     InstanceConfig instanceConfig = InstanceConfigTest.getInstanceConfigs().get(0);
     ViewEntity viewDefinition = ViewEntityTest.getViewEntity();
-    return new ViewInstanceEntity(viewDefinition, instanceConfig);
+    ViewInstanceEntity viewInstanceEntity = new ViewInstanceEntity(viewDefinition, instanceConfig);
+
+    ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity();
+    resourceTypeEntity.setId(10);
+    resourceTypeEntity.setName(viewDefinition.getName());
+
+    viewDefinition.setResourceType(resourceTypeEntity);
+
+    ResourceEntity resourceEntity = new ResourceEntity();
+    resourceEntity.setId(20L);
+    resourceEntity.setResourceType(resourceTypeEntity);
+    viewInstanceEntity.setResource(resourceEntity);
+
+    return viewInstanceEntity;
   }
 
   public static Set<ViewInstanceEntity> getViewInstanceEntities(ViewEntity viewDefinition) throws Exception {

+ 20 - 6
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestAmbariLdapAuthoritiesPopulator.java

@@ -18,8 +18,12 @@
 package org.apache.ambari.server.security.authorization;
 
 import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
 import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.easymock.Capture;
@@ -34,7 +38,6 @@ import java.util.Map;
 import java.util.Set;
 
 import static org.easymock.EasyMock.*;
-import static org.easymock.EasyMock.createMock;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
@@ -44,6 +47,8 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
   Configuration configuration = createMock(Configuration.class);
   UserDAO userDAO = createMock(UserDAO.class);
   RoleDAO roleDAO = createMock(RoleDAO.class);
+  PrincipalDAO principalDAO = createMock(PrincipalDAO.class);
+  PrincipalTypeDAO principalTypeDAO = createMock(PrincipalTypeDAO.class);
   LdapServerProperties ldapServerProperties = createMock(LdapServerProperties.class);
   DirContextOperations userData = createMock(DirContextOperations.class);
   UserEntity userEntity = createMock(UserEntity.class);
@@ -74,7 +79,7 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
     AmbariLdapAuthoritiesPopulator populator = createMockBuilder(AmbariLdapAuthoritiesPopulator.class)
         .addMockedMethod("createLdapUser")
         .withConstructor(
-            configuration, helper, userDAO, roleDAO
+            configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO
         ).createMock();
 
 
@@ -106,7 +111,7 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
         .addMockedMethod("addRole")
         .addMockedMethod("removeRole")
         .withConstructor(
-            configuration, helper, userDAO, roleDAO
+            configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO
         ).createMock();
 
     expect(userData.getObjectAttribute("ambari_admin")).andReturn(Boolean.TRUE).andReturn(Boolean.FALSE);
@@ -144,11 +149,12 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
         .addMockedMethod("addRole")
         .addMockedMethod("removeRole")
         .withConstructor(
-            configuration, helper, userDAO, roleDAO
+            configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO
         ).createMock();
 
     Capture<UserEntity> createEntity = new Capture<UserEntity>();
     Capture<UserEntity> addRoleEntity = new Capture<UserEntity>();
+    Capture<PrincipalEntity> principalEntity = new Capture<PrincipalEntity>();
 
     userDAO.create(capture(createEntity));
     expectLastCall();
@@ -156,6 +162,14 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
     populator.addRole(capture(addRoleEntity), eq(userRole));
     expectLastCall();
 
+    PrincipalTypeEntity principalTypeEntity = new PrincipalTypeEntity();
+    principalTypeEntity.setId(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
+    principalTypeEntity.setName(PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME);
+
+    expect(principalTypeDAO.findById(1)).andReturn(principalTypeEntity);
+
+    principalDAO.create(capture(principalEntity));
+
     replayAll();
 
     populator.createLdapUser(username);
@@ -176,7 +190,7 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
   @Test
   public void testAddRole() throws Exception {
     AmbariLdapAuthoritiesPopulator populator =
-        new AmbariLdapAuthoritiesPopulator(configuration, helper, userDAO, roleDAO);
+        new AmbariLdapAuthoritiesPopulator(configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO);
 
     RoleEntity roleEntity = createMock(RoleEntity.class);
     Set<UserEntity> userEntities = createMock(Set.class);
@@ -229,7 +243,7 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
     int userId = 123;
 
     AmbariLdapAuthoritiesPopulator populator =
-        new AmbariLdapAuthoritiesPopulator(configuration, helper, userDAO, roleDAO);
+        new AmbariLdapAuthoritiesPopulator(configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO);
 
     RoleEntity roleEntity = createMock(RoleEntity.class);
     Set<UserEntity> userEntities = createMock(Set.class);

+ 18 - 0
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestUsers.java

@@ -33,8 +33,12 @@ import org.apache.ambari.server.orm.GuiceJpaInitializer;
 import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
 import org.apache.ambari.server.orm.dao.GroupDAO;
 import org.apache.ambari.server.orm.dao.MemberDAO;
+import org.apache.ambari.server.orm.dao.PrincipalDAO;
+import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
 import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
+import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.junit.After;
@@ -64,6 +68,10 @@ public class TestUsers {
   @Inject
   protected RoleDAO roleDAO;
   @Inject
+  protected PrincipalTypeDAO principalTypeDAO;
+  @Inject
+  protected PrincipalDAO principalDAO;
+  @Inject
   protected PasswordEncoder passwordEncoder;
   private Properties properties;
 
@@ -284,11 +292,21 @@ public class TestUsers {
   }
 
   private void createLdapUser() {
+
+    PrincipalTypeEntity principalTypeEntity = new PrincipalTypeEntity();
+    principalTypeEntity.setName(PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME);
+    principalTypeDAO.create(principalTypeEntity);
+
+    PrincipalEntity principalEntity = new PrincipalEntity();
+    principalEntity.setPrincipalType(principalTypeEntity);
+    principalDAO.create(principalEntity);
+
     RoleEntity role = roleDAO.findByName(users.getUserRole());
     UserEntity ldapUser = new UserEntity();
 
     ldapUser.setUserName("ldapUser");
     ldapUser.setLdapUser(true);
+    ldapUser.setPrincipal(principalEntity);
 
     userDAO.create(ldapUser);
 

+ 90 - 25
ambari-server/src/test/java/org/apache/ambari/server/view/ViewRegistryTest.java

@@ -22,8 +22,12 @@ import org.apache.ambari.server.api.resources.SubResourceDefinition;
 import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.controller.spi.Resource;
 import org.apache.ambari.server.controller.spi.ResourceProvider;
+import org.apache.ambari.server.orm.dao.ResourceDAO;
+import org.apache.ambari.server.orm.dao.ResourceTypeDAO;
 import org.apache.ambari.server.orm.dao.ViewDAO;
 import org.apache.ambari.server.orm.dao.ViewInstanceDAO;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
 import org.apache.ambari.server.orm.entities.ViewEntity;
 import org.apache.ambari.server.orm.entities.ViewEntityTest;
 import org.apache.ambari.server.orm.entities.ViewInstanceDataEntity;
@@ -68,7 +72,6 @@ import static org.easymock.EasyMock.capture;
 import static org.easymock.EasyMock.createMock;
 import static org.easymock.EasyMock.createNiceMock;
 import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.expectLastCall;
 import static org.easymock.EasyMock.replay;
 import static org.easymock.EasyMock.verify;
 
@@ -155,6 +158,18 @@ public class ViewRegistryTest {
     InputStream is = createMock(InputStream.class);
     FileOutputStream fos = createMock(FileOutputStream.class);
 
+    ResourceTypeDAO rtDAO = createMock(ResourceTypeDAO.class);
+
+    ViewRegistry.setResourceTypeDAO(rtDAO);
+
+    ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity();
+    resourceTypeEntity.setId(10);
+    resourceTypeEntity.setName("MY_VIEW{1.0.0}");
+
+    ResourceDAO rDAO = createMock(ResourceDAO.class);
+
+    ViewRegistry.setResourceDAO(rDAO);
+
     ViewDAO vDAO = createMock(ViewDAO.class);
 
     ViewRegistry.setViewDAO(vDAO);
@@ -232,9 +247,15 @@ public class ViewRegistryTest {
 
     expect(vDAO.findAll()).andReturn(Collections.<ViewEntity>emptyList());
 
+    expect(rtDAO.findByName("MY_VIEW{1.0.0}")).andReturn(resourceTypeEntity);
+
+    Capture<ResourceEntity> resourceEntityCapture = new Capture<ResourceEntity>();
+    rDAO.create(capture(resourceEntityCapture));
+    rDAO.create(capture(resourceEntityCapture));
+
     // replay mocks
     replay(configuration, viewDir, extractedArchiveDir, viewArchive, archiveDir, entryFile, classesDir,
-        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO);
+        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO, rtDAO, rDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
     registry.setHelper(new TestViewRegistryHelper(viewConfigs, files, outputStreams, jarFiles));
@@ -246,7 +267,7 @@ public class ViewRegistryTest {
 
     // verify mocks
     verify(configuration, viewDir, extractedArchiveDir, viewArchive, archiveDir, entryFile, classesDir,
-        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO);
+        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO, rtDAO, rDAO);
   }
 
   @Test
@@ -267,6 +288,18 @@ public class ViewRegistryTest {
     InputStream is = createMock(InputStream.class);
     FileOutputStream fos = createMock(FileOutputStream.class);
 
+    ResourceTypeDAO rtDAO = createMock(ResourceTypeDAO.class);
+
+    ViewRegistry.setResourceTypeDAO(rtDAO);
+
+    ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity();
+    resourceTypeEntity.setId(10);
+    resourceTypeEntity.setName("MY_VIEW{1.0.0}");
+
+    ResourceDAO rDAO = createMock(ResourceDAO.class);
+
+    ViewRegistry.setResourceDAO(rDAO);
+
     ViewDAO vDAO = createMock(ViewDAO.class);
 
     ViewRegistry.setViewDAO(vDAO);
@@ -341,9 +374,15 @@ public class ViewRegistryTest {
 
     expect(vDAO.findAll()).andReturn(Collections.<ViewEntity>emptyList());
 
+    expect(rtDAO.findByName("MY_VIEW{1.0.0}")).andReturn(resourceTypeEntity);
+
+    Capture<ResourceEntity> resourceEntityCapture = new Capture<ResourceEntity>();
+    rDAO.create(capture(resourceEntityCapture));
+    rDAO.create(capture(resourceEntityCapture));
+
     // replay mocks
     replay(configuration, viewDir, extractedArchiveDir, viewArchive, archiveDir, entryFile, classesDir,
-        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO);
+        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO, rtDAO, rDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
     registry.setHelper(new TestViewRegistryHelper(viewConfigs, files, outputStreams, jarFiles));
@@ -354,7 +393,7 @@ public class ViewRegistryTest {
 
     // verify mocks
     verify(configuration, viewDir, extractedArchiveDir, viewArchive, archiveDir, entryFile, classesDir,
-        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO);
+        libDir, fileEntry, viewJarFile, enumeration, jarEntry, is, fos, vDAO, rtDAO, rDAO);
   }
 
   @Test
@@ -444,6 +483,17 @@ public class ViewRegistryTest {
 
     ViewInstanceEntity viewInstanceEntity = new ViewInstanceEntity(viewEntity, instanceConfig);
 
+    ResourceTypeEntity resourceTypeEntity = new ResourceTypeEntity();
+    resourceTypeEntity.setId(10);
+    resourceTypeEntity.setName(viewEntity.getName());
+
+    viewEntity.setResourceType(resourceTypeEntity);
+
+    ResourceEntity resourceEntity = new ResourceEntity();
+    resourceEntity.setId(20L);
+    resourceEntity.setResourceType(resourceTypeEntity);
+    viewInstanceEntity.setResource(resourceEntity);
+
     registry.addDefinition(viewEntity);
     registry.addInstanceDefinition(viewEntity, viewInstanceEntity);
 
@@ -459,8 +509,10 @@ public class ViewRegistryTest {
 
     ViewDAO viewDAO = createNiceMock(ViewDAO.class);
     ViewInstanceDAO viewInstanceDAO = createNiceMock(ViewInstanceDAO.class);
+    ResourceDAO resourceDAO = createNiceMock(ResourceDAO.class);
+    ResourceTypeDAO resourceTypeDAO = createNiceMock(ResourceTypeDAO.class);
 
-    ViewRegistry.init(viewDAO, viewInstanceDAO);
+    ViewRegistry.init(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
 
@@ -476,7 +528,7 @@ public class ViewRegistryTest {
     expect(viewInstanceDAO.merge(viewInstanceEntity)).andReturn(null);
     expect(viewInstanceDAO.findByName("MY_VIEW{1.0.0}", viewInstanceEntity.getInstanceName())).andReturn(viewInstanceEntity);
 
-    replay(viewDAO, viewInstanceDAO);
+    replay(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     registry.addDefinition(viewEntity);
     registry.installViewInstance(viewInstanceEntity);
@@ -487,7 +539,7 @@ public class ViewRegistryTest {
 
     Assert.assertEquals(viewInstanceEntity, viewInstanceDefinitions.iterator().next());
 
-    verify(viewDAO, viewInstanceDAO);
+    verify(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
   }
 
   @Test
@@ -495,8 +547,10 @@ public class ViewRegistryTest {
 
     ViewDAO viewDAO = createNiceMock(ViewDAO.class);
     ViewInstanceDAO viewInstanceDAO = createNiceMock(ViewInstanceDAO.class);
+    ResourceDAO resourceDAO = createNiceMock(ResourceDAO.class);
+    ResourceTypeDAO resourceTypeDAO = createNiceMock(ResourceTypeDAO.class);
 
-    ViewRegistry.init(viewDAO, viewInstanceDAO);
+    ViewRegistry.init(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
 
@@ -509,7 +563,7 @@ public class ViewRegistryTest {
     ViewEntity viewEntity = getViewEntity(config, ambariConfig, getClass().getClassLoader(), "");
     ViewInstanceEntity viewInstanceEntity = getViewInstanceEntity(viewEntity, config.getInstances().get(0));
 
-    replay(viewDAO, viewInstanceDAO);
+    replay(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     registry.addDefinition(viewEntity);
     try {
@@ -518,7 +572,7 @@ public class ViewRegistryTest {
     } catch (IllegalStateException e) {
       // expected
     }
-    verify(viewDAO, viewInstanceDAO);
+    verify(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
   }
 
   @Test
@@ -526,8 +580,10 @@ public class ViewRegistryTest {
 
     ViewDAO viewDAO = createNiceMock(ViewDAO.class);
     ViewInstanceDAO viewInstanceDAO = createNiceMock(ViewInstanceDAO.class);
+    ResourceDAO resourceDAO = createNiceMock(ResourceDAO.class);
+    ResourceTypeDAO resourceTypeDAO = createNiceMock(ResourceTypeDAO.class);
 
-    ViewRegistry.init(viewDAO, viewInstanceDAO);
+    ViewRegistry.init(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
 
@@ -541,7 +597,7 @@ public class ViewRegistryTest {
     ViewInstanceEntity viewInstanceEntity = getViewInstanceEntity(viewEntity, config.getInstances().get(0));
     viewInstanceEntity.setViewName("BOGUS_VIEW");
 
-    replay(viewDAO, viewInstanceDAO);
+    replay(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     registry.addDefinition(viewEntity);
     try {
@@ -550,7 +606,7 @@ public class ViewRegistryTest {
     } catch (IllegalArgumentException e) {
       // expected
     }
-    verify(viewDAO, viewInstanceDAO);
+    verify(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
   }
 
   @Test
@@ -558,8 +614,10 @@ public class ViewRegistryTest {
 
     ViewDAO viewDAO = createNiceMock(ViewDAO.class);
     ViewInstanceDAO viewInstanceDAO = createNiceMock(ViewInstanceDAO.class);
+    ResourceDAO resourceDAO = createNiceMock(ResourceDAO.class);
+    ResourceTypeDAO resourceTypeDAO = createNiceMock(ResourceTypeDAO.class);
 
-    ViewRegistry.init(viewDAO, viewInstanceDAO);
+    ViewRegistry.init(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
 
@@ -577,7 +635,7 @@ public class ViewRegistryTest {
     expect(viewInstanceDAO.merge(viewInstanceEntity)).andReturn(viewInstanceEntity);
     expect(viewInstanceDAO.findByName("MY_VIEW{1.0.0}", viewInstanceEntity.getInstanceName())).andReturn(viewInstanceEntity);
 
-    replay(viewDAO, viewInstanceDAO);
+    replay(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     registry.addDefinition(viewEntity);
     registry.installViewInstance(viewInstanceEntity);
@@ -590,7 +648,7 @@ public class ViewRegistryTest {
 
     Assert.assertEquals(viewInstanceEntity, viewInstanceDefinitions.iterator().next());
 
-    verify(viewDAO, viewInstanceDAO);
+    verify(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
   }
 
   @Test
@@ -598,8 +656,10 @@ public class ViewRegistryTest {
 
     ViewDAO viewDAO = createNiceMock(ViewDAO.class);
     ViewInstanceDAO viewInstanceDAO = createNiceMock(ViewInstanceDAO.class);
+    ResourceDAO resourceDAO = createNiceMock(ResourceDAO.class);
+    ResourceTypeDAO resourceTypeDAO = createNiceMock(ResourceTypeDAO.class);
 
-    ViewRegistry.init(viewDAO, viewInstanceDAO);
+    ViewRegistry.init(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
 
@@ -617,7 +677,7 @@ public class ViewRegistryTest {
     expect(viewInstanceDAO.merge(viewInstanceEntity)).andReturn(null);
     expect(viewInstanceDAO.findByName("MY_VIEW{1.0.0}", viewInstanceEntity.getInstanceName())).andReturn(viewInstanceEntity);
 
-    replay(viewDAO, viewInstanceDAO);
+    replay(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     registry.addDefinition(viewEntity);
     registry.installViewInstance(viewInstanceEntity);
@@ -628,7 +688,7 @@ public class ViewRegistryTest {
     } catch (IllegalStateException e) {
       // expected
     }
-    verify(viewDAO, viewInstanceDAO);
+    verify(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
   }
 
   @Test
@@ -636,8 +696,10 @@ public class ViewRegistryTest {
 
     ViewDAO viewDAO = createNiceMock(ViewDAO.class);
     ViewInstanceDAO viewInstanceDAO = createNiceMock(ViewInstanceDAO.class);
+    ResourceDAO resourceDAO = createNiceMock(ResourceDAO.class);
+    ResourceTypeDAO resourceTypeDAO = createNiceMock(ResourceTypeDAO.class);
 
-    ViewRegistry.init(viewDAO, viewInstanceDAO);
+    ViewRegistry.init(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     ViewRegistry registry = ViewRegistry.getInstance();
 
@@ -649,22 +711,25 @@ public class ViewRegistryTest {
 
     viewInstanceDAO.removeData(dataEntity);
     expect(viewInstanceDAO.merge(viewInstanceEntity)).andReturn(viewInstanceEntity);
-    replay(viewDAO, viewInstanceDAO);
+    replay(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
 
     registry.removeInstanceData(viewInstanceEntity, "foo");
 
     Assert.assertNull(viewInstanceEntity.getInstanceData("foo"));
-    verify(viewDAO, viewInstanceDAO);
+    verify(viewDAO, viewInstanceDAO, resourceDAO, resourceTypeDAO);
   }
 
   @Before
   public void before() throws Exception {
-    ViewRegistry.getInstance().clear();
-    ViewRegistry.setViewDAO(null);
+    clear();
   }
 
   @AfterClass
   public static void afterClass() {
+    clear();
+  }
+
+  public static void clear() {
     ViewRegistry.getInstance().clear();
     ViewRegistry.setViewDAO(null);
   }