/**
  * Retrieve actual data which was saved - called by Filter. Chose to keep all logic here for
  * saving and retrieving data TODO find away of purging stuff *when* it is reasonable to do so
  *
  * @param request
  * @param id
  * @return Map containing details of previous pages visited
  * @throws IllegalStateException
  */
 public static Map[] getCallerPageData(HttpServletRequest request, String id) {
   Map callerPageHistory = (Map) request.getSession().getAttribute("callerPageHistory");
   if (callerPageHistory == null || !callerPageHistory.containsKey(id)) {
     CallerPageException e = new CallerPageException("No caller page data for ID=" + id);
     throw (CallerPageException) NavExceptionHelper.fillInStacktrace(e);
   }
   return (Map[]) callerPageHistory.get(id);
 }
  /**
   * Makes HttpSession and GrouperSession available to subclasses Also handles pageSize parameter
   * and times how long is spent in an action
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    GrouperSession grouperSession =
        (GrouperSession)
            request.getSession().getAttribute("edu.intenet2.middleware.grouper.ui.GrouperSession");
    // if(grouperSession == null && !"/populateIndex.do".equals(request.getServletPath())) return
    // mapping.findForward("Index");

    ModuleConfig modConfig = (ModuleConfig) request.getAttribute("org.apache.struts.action.MODULE");
    String modulePrefix = modConfig.getPrefix();
    if (modulePrefix == null) modulePrefix = "";
    request.setAttribute("modulePrefix", modulePrefix);
    HttpSession session = request.getSession();
    String pageSize = request.getParameter("pageSize");
    if (pageSize != null && pageSize.length() > 0) {
      session.setAttribute("default.pagesize", pageSize);
    }

    DynaActionForm dummyForm = (DynaActionForm) form;
    if (dummyForm != null) {
      try {
        dummyForm.set("pageSize", "" + getPageSize(session));
      } catch (Exception e) {
        // Ok so form doesn't care about pageSize
        // let's just ignore it
      }
    }
    isWheelGroupMember(session);
    String wheelGroupAction = request.getParameter("wheelGroupAction");
    if (!isEmpty(wheelGroupAction)) doWheelGroupStuff(wheelGroupAction, session);
    UIThreadLocal.replace(
        "isActiveWheelGroupMember", new Boolean(isActiveWheelGroupMember(session)));

    if (grouperSession != null) {
      if (isWheelGroupMember(session)) {
        grouperSession.setConsiderIfWheelMember(isActiveWheelGroupMember(session));
      } else {
        // we'll set this back to the default
        grouperSession.setConsiderIfWheelMember(true);
      }
    }

    if (form != null) request.setAttribute("grouperForm", form);
    Object sessionMessage = session.getAttribute("sessionMessage");
    if (isEmpty(request.getAttribute("message")) && !isEmpty(sessionMessage)) {
      request.setAttribute("message", sessionMessage);
      session.removeAttribute("sessionMessage");
    }
    request.setAttribute("linkBrowseMode", getLinkBrowseMode(session));
    Date before = new Date();
    ActionForward forward = null;
    try {
      if (isEmpty(wheelGroupAction)) {

        forward =
            grouperTransactionExecute(mapping, form, request, response, session, grouperSession);

      } else
        forward =
            new ActionForward(
                GrouperUiFilter.retrieveSessionMediaResourceBundle().getString("admin.browse.path"),
                true);
    } catch (GrouperDAOException e) {
      Throwable cause = e.getCause();

      Throwable causeCause = cause == null ? null : cause.getCause();

      Throwable causeCauseCause = causeCause == null ? null : causeCause.getCause();

      HookVeto hookVeto = (cause instanceof HookVeto) ? (HookVeto) cause : null;

      hookVeto =
          ((hookVeto == null) && (causeCause instanceof HookVeto))
              ? (HookVeto) causeCause
              : hookVeto;

      hookVeto =
          ((hookVeto == null) && (causeCauseCause instanceof HookVeto))
              ? (HookVeto) causeCauseCause
              : hookVeto;

      if (hookVeto != null) {
        Message.addVetoMessageToScreen(request, hookVeto);
      } else if (!(cause instanceof UnrecoverableErrorException)) {
        LOG.error(NavExceptionHelper.toLog(cause));
        cause = new UnrecoverableErrorException(cause);
      }
      if (cause instanceof UnrecoverableErrorException) {
        NavExceptionHelper neh = getExceptionHelper(session);
        String msg = neh.getMessage((UnrecoverableErrorException) cause);
        request.setAttribute("seriousError", msg);
      }
      forward = mapping.findForward("ErrorPage");
    }
    Date after = new Date();
    long diff = after.getTime() - before.getTime();
    String url = request.getServletPath();
    Long ms = (Long) request.getAttribute("timingsMS");
    long mss = 0;
    if (ms != null) mss = ms.longValue();
    if (diff > 25) {
      request.setAttribute("timingsClass", this.getClass().getName());
      request.setAttribute("timingsMS", new Long(diff + mss));
    }
    if (forward != null && forward.getRedirect() && !isEmpty(request.getAttribute("message"))) {
      try {
        session.setAttribute("sessionMessage", request.getAttribute("message"));
      } catch (IllegalStateException e) {
      }
    }

    if (Boolean.TRUE.equals(request.getAttribute("loggedOut"))) {
      return forward;
    }
    try {
      GrouperHelper.fixSessionFields((Map) session.getAttribute("fieldList"));
    } catch (SchemaException e) {
      LOG.error(e);
    }
    String advSearch = request.getParameter("advancedSearch");
    try {
      session.getAttribute("");
    } catch (Exception e) {
      return forward;
    }
    if (!isEmpty(advSearch)) {
      setAdvancedSearchMode("true".equals(advSearch), session);
    }
    request.setAttribute("isAdvancedSearch", getAdvancedSearchMode(session));
    return forward;
  }
  public ActionForward grouperExecute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      GrouperSession grouperSession)
      throws Exception {
    Class sortOverrideClass = Group.class;
    NavExceptionHelper neh = getExceptionHelper(session);
    DynaActionForm subjectForm = (DynaActionForm) form;
    if ("true".equals(request.getParameter("changeMode")))
      PopulateSearchSubjectsAction.initMode(session);
    session.setAttribute("subtitle", "subject.action.show-summary");
    if (isEmpty(subjectForm.get("callerPageId"))) {
      if (isEmpty(subjectForm.get("subjectId"))) {
        LOG.info("Restoring lastSubjectSummaryForm");
        restoreDynaFormBean(session, subjectForm, "lastSubjectSummaryForm");
      } else {
        LOG.info("Saving lastSubjectSummaryForm");
        saveDynaFormBean(session, subjectForm, "lastSubjectSummaryForm");
        saveAsCallerPage(request, subjectForm);
      }
    }
    saveAsCallerPage(request, subjectForm);

    String listField = (String) subjectForm.get("listField");
    String membershipField = "members";

    if (!isEmpty(listField)) {
      membershipField = listField;
    }
    Field mField = null;
    try {
      mField = FieldFinder.find(membershipField, true);
    } catch (SchemaException e) {
      LOG.error("Could not find Field: " + membershipField, e);
      if ("members".equals(membershipField)) {
        LOG.fatal("Built in field: members, missing");
        throw new UnrecoverableErrorException(e);
      } else {
        mField = FieldFinder.find("members", true);
        request.setAttribute(
            "message", new Message("error.subject-summary.missing-field", listField, true));
      }
    }

    subjectForm.set("contextSubject", "true");
    String subjectId = (String) subjectForm.get("subjectId");
    String subjectType = (String) subjectForm.get("subjectType");
    String subjectSource = (String) subjectForm.get("sourceId");
    if (isEmpty(subjectId) || isEmpty(subjectType) || isEmpty(subjectSource)) {
      String msg =
          neh.missingParameters(
              subjectId, "subjectId", subjectType, "subjectType", subjectSource, "sourceId");
      LOG.error(msg);
      if (doRedirectToCaller(subjectForm)) {
        session.setAttribute(
            "sessionMessage", new Message("error.subject-summary.missing-parameter", true));
        return redirectToCaller(subjectForm);
      }
      throw new UnrecoverableErrorException("error.subject-summary.missing-parameter");
    }
    Subject subject = null;
    try {
      subject = SubjectFinder.findById(subjectId, subjectType, subjectSource, true);
    } catch (Exception e) {
      LOG.error(e);
      if (e instanceof SubjectNotFoundException) {
        subject = new UnresolvableSubject(subjectId, subjectType, subjectSource);
        addMessage(
            new Message(
                "error.subject.unresolvable", new String[] {subjectId, subjectSource}, true),
            request);
      } else {

        String contextError = "error.subject-summary.subject.exception";
        session.setAttribute("sessionMessage", new Message(neh.key(e), contextError, true));
        if (doRedirectToCaller(subjectForm)) return redirectToCaller(subjectForm);
        throw new UnrecoverableErrorException(contextError, e);
      }
    }
    Map subjectMap = GrouperHelper.subject2Map(subject);
    request.setAttribute("subject", subjectMap);

    String order = null;
    try {
      order =
          GrouperUiFilter.retrieveSessionMediaResourceBundle()
              .getString("subject.attributes.order." + subject.getSource().getId());
      request.setAttribute("subjectAttributeNames", order.split(","));
    } catch (Exception e) {
      // No order specified, so go with all, in whatever order they come
      List extendedAttr = new ArrayList(GrouperUtil.nonNull(subject.getAttributes()).keySet());
      extendedAttr.add("subjectType");
      extendedAttr.add("id");
      request.setAttribute("subjectAttributeNames", extendedAttr);
    }
    String membershipListScope = (String) subjectForm.get("membershipListScope");

    if ("any-access".equals(membershipListScope)) {
      if ("false".equals(request.getParameter("advancedSearch"))) {
        membershipListScope = null;
      } else {
        request.setAttribute("fromSubjectSummary", Boolean.TRUE);

        session.setAttribute("groupSearchSubject", subject);
        session.setAttribute("groupSearchSubjectMap", subjectMap);
        return mapping.findForward(FORWARD_GroupSearch);
      }
    }
    if (":all:imm:eff:access:naming:".indexOf(":" + membershipListScope + ":") == -1) {
      membershipListScope = (String) session.getAttribute("subjectMembershipListScope");
    }
    if (membershipListScope == null) membershipListScope = "imm";
    session.setAttribute("subjectMembershipListScope", membershipListScope);
    subjectForm.set("membershipListScope", membershipListScope);

    String accessPriv = (String) subjectForm.get("accessPriv");
    if (isEmpty(accessPriv)) accessPriv = (String) session.getAttribute("subjectSummaryAccessPriv");
    if (isEmpty(accessPriv)) accessPriv = "read";
    session.setAttribute("subjectSummaryAccessPriv", accessPriv);
    subjectForm.set("accessPriv", accessPriv);

    String namingPriv = (String) subjectForm.get("namingPriv");
    if (isEmpty(namingPriv)) namingPriv = (String) session.getAttribute("subjectSummaryNamingPriv");
    if (isEmpty(namingPriv)) namingPriv = "create";
    session.setAttribute("subjectSummaryNamingPriv", namingPriv);
    subjectForm.set("namingPriv", namingPriv);
    // Retrieve the membership according to scope selected by user
    Member member = null;
    try {
      member = MemberFinder.findBySubject(grouperSession, subject, true);
      if (member == null) {
        throw new MemberNotFoundException("Unresolvable subject is also not a Member");
      }
    } catch (Exception e) {
      LOG.error(e);
      if (doRedirectToCaller(subjectForm)) {
        session.setAttribute(
            "sessionMessage", new Message("error.subject-summary.member.exception", true));
        return redirectToCaller(subjectForm);
      }
      throw new UnrecoverableErrorException("error.subject-summary.member.exception", e);
    }
    Set subjectScopes = null;
    List subjectScopeMaps = null;
    Map listViews = new HashMap();
    listViews.put("titleKey", "subject.summary.memberships");
    listViews.put("noResultsKey", "subject.list-membership.none");
    listViews.put("view", "whereSubjectsAreMembers");
    // listViews.put("itemView","whereIsMemberLink");
    listViews.put("itemView", "subjectSummary");
    listViews.put("headerView", "genericListHeader");
    listViews.put("footerView", "genericListFooter");

    if ("imm".equals(membershipListScope)) {
      subjectScopes = member.getImmediateMemberships(mField);
      listViews.put("noResultsKey", "subject.list-membership.imm.none");
    } else if ("eff".equals(membershipListScope)) {
      if (membershipField.equals("members")) {
        subjectScopes = member.getMemberships();
        subjectScopes.removeAll(member.getImmediateMemberships());

      } else {
        subjectScopes = member.getEffectiveMemberships(mField);
        listViews.put("noResultsKey", "subject.list-membership.all.none");
      }
      if ("members".equals(membershipField)) {
        listViews.put("noResultsKey", "subject.list-membership.eff.none");
      } else {
        listViews.put("noResultsKey", "subject.list-membership.custom.eff.none");
      }

    } else if ("all".equals(membershipListScope)) {
      subjectScopes = member.getMemberships(mField);
      listViews.put("noResultsKey", "subject.list-membership.all.none");
    } else if ("access".equals(membershipListScope)) {

      subjectScopes = GrouperHelper.getGroupsOrStemsWhereMemberHasPriv(member, accessPriv);

      // filter out groups where the subject can't see privs
      removeObjectsNotAllowedToSeePrivs(subjectScopes);

      subjectScopeMaps =
          GrouperHelper.subjects2SubjectPrivilegeMaps(
              grouperSession, subjectScopes, subject, accessPriv);
      listViews.put("titleKey", "subject.summary.access-privs");
      listViews.put("noResultsKey", "subject.list-access.none");
      listViews.put("view", "subjectSummaryPrivileges");
      listViews.put("itemView", "subjectSummaryPrivilege");
    } else {
      sortOverrideClass = Stem.class;
      subjectScopes = GrouperHelper.getGroupsOrStemsWhereMemberHasPriv(member, namingPriv);

      // filter out stems where the subject can't see privs
      removeObjectsNotAllowedToSeePrivs(subjectScopes);

      subjectScopeMaps =
          GrouperHelper.subjects2SubjectPrivilegeMaps(
              grouperSession, subjectScopes, subject, namingPriv);
      listViews.put("titleKey", "subject.summary.naming-privs");
      listViews.put("noResultsKey", "subject.list-naming.none");
      listViews.put("view", "subjectSummaryPrivileges");
      listViews.put("itemView", "subjectSummaryPrivilege");
    }
    request.setAttribute("scopeListData", listViews);
    if (subjectScopeMaps == null) {
      Map countMap = new HashMap();
      Map sources = new HashMap();
      List uniqueSubjectScopes =
          GrouperHelper.getOneMembershipPerSubjectOrGroup(
              subjectScopes, "subject", countMap, sources, 0);
      subjectScopeMaps = GrouperHelper.memberships2Maps(grouperSession, uniqueSubjectScopes);
      GrouperHelper.setMembershipCountPerSubjectOrGroup(subjectScopeMaps, "subject", countMap);
    }
    // This is a hack to force sorting by Group/Stem rather than Subject - which is generally what
    // happens with Memberships
    // DefaultComparatorImpl has been updated to read the TheadLocal
    UIThreadLocal.put("GrouperComparatorHelperOverrideClass", sortOverrideClass);
    subjectScopeMaps = sort(subjectScopeMaps, request, "subjectSummary", -1, null);
    UIThreadLocal.replace("GrouperComparatorHelperOverrideClass", null);
    String startStr = (String) subjectForm.get("start");
    if (startStr == null || "".equals(startStr)) startStr = "0";

    int start = Integer.parseInt(startStr);
    int pageSize = getPageSize(session);
    int end = start + pageSize;
    if (end > subjectScopeMaps.size()) end = subjectScopeMaps.size();
    CollectionPager pager =
        new CollectionPager(
            null, subjectScopeMaps, subjectScopeMaps.size(), null, start, null, pageSize);

    if (!isEmpty(listField)) pager.setParam("listField", listField);
    pager.setParam("subjectId", subjectId);
    pager.setParam("subjectType", subjectType);
    pager.setParam("sourceId", subjectSource);
    pager.setParam("returnTo", subjectForm.get("returnTo"));
    pager.setParam("returnToLinkKey", subjectForm.get("returnToLinkKey"));
    pager.setTarget(mapping.getPath());
    request.setAttribute("pager", pager);
    request.setAttribute("linkParams", pager.getParams().clone());
    request.setAttribute("listFieldParams", pager.getParams().clone());

    Map saveParams = new HashMap();
    saveParams.put("subjectId", subject.getId());
    saveParams.put("subjectType", subject.getType().getName());
    saveParams.put("sourceId", subject.getSource().getId());
    saveParams.put("callerPageId", request.getAttribute("thisPageId"));
    request.setAttribute("saveParams", saveParams);

    if (subjectType.equals("group")) {
      List lists = GrouperHelper.getReadableListFieldsForGroup(grouperSession, subjectId);
      if (!lists.isEmpty()) request.setAttribute("listFields", lists);
    }

    List memberOfListFields = GrouperHelper.getListFieldsForSubject(grouperSession, subject);
    if (memberOfListFields.size() > 0) {
      request.setAttribute("memberOfListFields", memberOfListFields);
    }

    Collection accessPrivs =
        GrouperHelper.getGroupPrivsWithLabels(GrouperUiFilter.retrieveSessionNavResourceBundle());
    Collection namingPrivs =
        GrouperHelper.getStemPrivsWithLabels(GrouperUiFilter.retrieveSessionNavResourceBundle());
    request.setAttribute("allAccessPrivs", accessPrivs);
    request.setAttribute("allNamingPrivs", namingPrivs);

    return mapping.findForward(FORWARD_SubjectSummary);
  }