public PolicyBean createPolicy(String organizationId, String entityId, String entityVersion,
        NewPolicyBean bean, PolicyType type) throws PolicyDefinitionNotFoundException {

        return tryAction(() -> {
            if (bean.getDefinitionId() == null) {
                throw ExceptionFactory.policyDefNotFoundException("null"); //$NON-NLS-1$
            }
            PolicyDefinitionBean def = storage.getPolicyDefinition(bean.getDefinitionId());

            if (def == null) {
                throw ExceptionFactory.policyDefNotFoundException(bean.getDefinitionId());
            }

            int newIdx = query.getMaxPolicyOrderIndex(organizationId, entityId, entityVersion, type) + 1;

            PolicyBean policy = new PolicyBean();
            policy.setId(null);
            policy.setDefinition(def);
            policy.setName(def.getName());
            policy.setConfiguration(bean.getConfiguration());
            policy.setCreatedBy(securityContext.getCurrentUser());
            policy.setCreatedOn(new Date());
            policy.setModifiedBy(securityContext.getCurrentUser());
            policy.setModifiedOn(new Date());
            policy.setOrganizationId(organizationId);
            policy.setEntityId(entityId);
            policy.setEntityVersion(entityVersion);
            policy.setType(type);
            policy.setOrderIndex(newIdx);

            if (type == PolicyType.Client) {
                ClientVersionBean cvb = storage.getClientVersion(organizationId, entityId, entityVersion);
                cvb.setModifiedBy(securityContext.getCurrentUser());
                cvb.setModifiedOn(new Date());
                storage.updateClientVersion(cvb);
            } else if (type == PolicyType.Api) {
                ApiVersionBean avb = storage.getApiVersion(organizationId, entityId, entityVersion);
                avb.setModifiedBy(securityContext.getCurrentUser());
                avb.setModifiedOn(new Date());
                storage.updateApiVersion(avb);
            } else if (type == PolicyType.Plan) {
                PlanVersionBean pvb = storage.getPlanVersion(organizationId, entityId, entityVersion);
                pvb.setModifiedBy(securityContext.getCurrentUser());
                pvb.setModifiedOn(new Date());
                storage.updatePlanVersion(pvb);
            }

            storage.createPolicy(policy);
            storage.createAuditEntry(AuditUtils.policyAdded(policy, type, securityContext));

            PolicyTemplateUtil.generatePolicyDescription(policy);

            LOGGER.debug(String.format("Created client policy: %s", policy)); //$NON-NLS-1$
            return policy;
        });
    }
Creates a policy for the given entity (supports creating policies for clients,
APIs, and plans).

@param organizationId
@param entityId
@param entityVersion
@param bean
@return the stored policy bean (with updated information)
manager/api/rest-impl/src/main/java/io/apiman/manager/api/service/PolicyService.java