/**
   * finds the entity indicated by the given ID or name
   *
   * <p>prefers ID based lookup in which case appId is optional, and if supplied will be enforced.
   * optionally the name can be supplied, for cases when paths should work across versions, in which
   * case names will be searched recursively (and the application is required).
   *
   * @throws 404 or 412 (unless input is null in which case output is null)
   */
  public EntityLocal getEntity(String application, String entity) {
    if (entity == null) return null;
    Application app = application != null ? getApplication(application) : null;
    EntityLocal e = (EntityLocal) mgmt.getEntityManager().getEntity(entity);

    if (e != null) {
      if (!Entitlements.isEntitled(mgmt.getEntitlementManager(), Entitlements.SEE_ENTITY, e)) {
        throw WebResourceUtils.notFound(
            "Cannot find entity '%s': no known ID and application not supplied for searching",
            entity);
      }

      if (app == null || app.equals(findTopLevelApplication(e))) return e;
      throw WebResourceUtils.preconditionFailed(
          "Application '%s' specified does not match application '%s' to which entity '%s' (%s) is associated",
          application, e.getApplication().getId(), entity, e);
    }
    if (application == null)
      throw WebResourceUtils.notFound(
          "Cannot find entity '%s': no known ID and application not supplied for searching",
          entity);

    assert app != null : "null app should not be returned from getApplication";
    e = searchForEntityNamed(app, entity);
    if (e != null) return e;
    throw WebResourceUtils.notFound(
        "Cannot find entity '%s' in application '%s' (%s)", entity, application, app);
  }
  /**
   * finds the policy indicated by the given ID or name.
   *
   * @see {@link getPolicy(String,String,String)}.
   *     <p>
   * @throws 404 or 412 (unless input is null in which case output is null)
   */
  public Policy getPolicy(Entity entity, String policy) {
    if (policy == null) return null;

    for (Policy p : entity.getPolicies()) {
      if (policy.equals(p.getId())) return p;
    }
    for (Policy p : entity.getPolicies()) {
      if (policy.equals(p.getName())) return p;
    }

    throw WebResourceUtils.notFound("Cannot find policy '%s' in entity '%s'", policy, entity);
  }