/**
  * Gets a policy by its id. Also verifies that the policy really does belong to the entity
  * indicated.
  *
  * @param type
  * @param organizationId
  * @param entityId
  * @param entityVersion
  * @param policyId
  * @return a policy bean
  * @throws PolicyNotFoundException
  */
 protected PolicyBean doGetPolicy(
     PolicyType type, String organizationId, String entityId, String entityVersion, long policyId)
     throws PolicyNotFoundException {
   try {
     PolicyBean policy = storage.get(policyId, PolicyBean.class);
     if (policy.getType() != type) {
       throw ExceptionFactory.policyNotFoundException(policyId);
     }
     if (!policy.getOrganizationId().equals(organizationId)) {
       throw ExceptionFactory.policyNotFoundException(policyId);
     }
     if (!policy.getEntityId().equals(entityId)) {
       throw ExceptionFactory.policyNotFoundException(policyId);
     }
     if (!policy.getEntityVersion().equals(entityVersion)) {
       throw ExceptionFactory.policyNotFoundException(policyId);
     }
     PolicyTemplateUtil.generatePolicyDescription(policy);
     return policy;
   } catch (DoesNotExistException e) {
     throw ExceptionFactory.policyNotFoundException(policyId);
   } catch (StorageException e) {
     throw new SystemErrorException(e);
   } catch (Exception e) {
     throw new SystemErrorException(e);
   }
 }
  /**
   * Creates a policy for the given entity (supports creating policies for applications, services,
   * and plans).
   *
   * @param organizationId
   * @param entityId
   * @param entityVersion
   * @param bean
   * @return the stored policy bean (with updated information)
   * @throws NotAuthorizedException
   */
  protected PolicyBean doCreatePolicy(
      String organizationId,
      String entityId,
      String entityVersion,
      PolicyBean bean,
      PolicyType type)
      throws PolicyDefinitionNotFoundException {
    if (bean.getDefinition() == null) {
      ExceptionFactory.policyDefNotFoundException("null"); // $NON-NLS-1$
    }
    try {
      PolicyDefinitionBean def =
          storage.get(bean.getDefinition().getId(), PolicyDefinitionBean.class);
      bean.setDefinition(def);
    } catch (DoesNotExistException e) {
      ExceptionFactory.policyDefNotFoundException(bean.getDefinition().getId());
    } catch (StorageException e) {
      throw new SystemErrorException(e);
    }

    try {
      bean.setId(null);
      bean.setCreatedBy(securityContext.getCurrentUser());
      bean.setCreatedOn(new Date());
      bean.setModifiedBy(securityContext.getCurrentUser());
      bean.setModifiedOn(new Date());
      bean.setOrganizationId(organizationId);
      bean.setEntityId(entityId);
      bean.setEntityVersion(entityVersion);
      bean.setType(type);
      storage.create(bean);

      PolicyTemplateUtil.generatePolicyDescription(bean);
      return bean;
    } catch (Exception e) {
      throw new SystemErrorException(e);
    }
  }