/** edit the enabled disabled */
  @SuppressWarnings("unchecked")
  public void memberMenuEnabledDisabled() {

    GuiResponseJs guiResponseJs = GuiResponseJs.retrieveGuiResponseJs();

    // lets see which subject we are dealing with:
    HttpServletRequest httpServletRequest = GrouperUiFilter.retrieveHttpServletRequest();
    String menuIdOfMenuTarget = httpServletRequest.getParameter("menuIdOfMenuTarget");
    if (StringUtils.isBlank(menuIdOfMenuTarget)) {
      throw new RuntimeException("Missing id of menu target");
    }
    if (!menuIdOfMenuTarget.startsWith("memberMenuButton_")) {
      throw new RuntimeException("Invalid id of menu target: '" + menuIdOfMenuTarget + "'");
    }
    String memberId = GrouperUtil.prefixOrSuffix(menuIdOfMenuTarget, "memberMenuButton_", false);

    final Subject loggedInSubject = GrouperUiFilter.retrieveSubjectLoggedIn();

    GrouperSession grouperSession = null;
    Group group = null;
    try {

      grouperSession = GrouperSession.start(loggedInSubject);

      Member member = MemberFinder.findByUuid(grouperSession, memberId, true);

      group = new SimpleMembershipUpdate().retrieveGroup(grouperSession);

      Membership membership =
          group.getImmediateMembership(Group.getDefaultList(), member, false, true);

      SimpleMembershipUpdateContainer simpleMembershipUpdateContainer =
          SimpleMembershipUpdateContainer.retrieveFromSession();

      GuiMember guiMember = new GuiMember(member);
      simpleMembershipUpdateContainer.setEnabledDisabledMember(guiMember);

      guiMember.setMembership(membership);

      guiResponseJs.addAction(
          GuiScreenAction.newDialogFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateEnabledDisabled.jsp"));

    } catch (ControllerDone cd) {
      throw cd;
    } catch (NoSessionException nse) {
      throw nse;
    } catch (Exception se) {
      throw new RuntimeException(
          "Error listing member details: " + menuIdOfMenuTarget + ", " + se.getMessage(), se);
    } finally {
      GrouperSession.stopQuietly(grouperSession);
    }
  }
 /**
  * Creates a group if it does not exist, removes all its members otherwise .
  *
  * @param definition The definition of the group.
  * @see
  *     org.esco.dynamicgroups.dao.grouper.IGroupsDAOService#resetGroupMembers(DynamicGroupDefinition)
  */
 public void resetGroupMembers(final DynamicGroupDefinition definition) {
   GrouperSession session = null;
   try {
     session = GrouperSession.start(SubjectFinder.findRootSubject(), false);
     GrouperSession.callbackGrouperSession(
         session, new ResetGroupMembersCallback(this, definition.getGroupUUID()));
   } catch (SessionException e) {
     LOGGER.error(e, e);
   } finally {
     GrouperSession.stopQuietly(session);
   }
 }
  /**
   * Convenience method
   *
   * @param privileges
   * @param s
   * @param group
   * @return
   */
  protected boolean hasAtleastOneOf(String[] privileges, GrouperSession s, Group group) {
    if (privileges == null || privileges.length == 0) return true;

    boolean result = false;
    for (int i = 0; i < privileges.length; i++) {
      if (privileges[i].equals("admin") && group.hasAdmin(s.getSubject())) return true;
      if (privileges[i].equals("update") && group.hasUpdate(s.getSubject())) return true;
      if (privileges[i].equals("read") && group.hasRead(s.getSubject())) return true;
      if (privileges[i].equals("view") && group.hasView(s.getSubject())) return true;
      if (privileges[i].equals("optin") && group.hasOptin(s.getSubject())) return true;
      if (privileges[i].equals("optout") && group.hasOptout(s.getSubject())) return true;
    }
    return result;
  }
  public void testAttributeDefSave() {

    // cant create without privs
    GrouperSession.stopQuietly(this.grouperSession);
    this.grouperSession = GrouperSession.start(SubjectTestHelper.SUBJ0);
    try {
      new AttributeDefSave(this.grouperSession).assignName("top:b").save();
      fail("shouldnt get here");
    } catch (Exception e) {
      // good
    }

    // grant privs
    GrouperSession.stopQuietly(this.grouperSession);
    this.grouperSession = GrouperSession.startRootSession();
    this.top.grantPriv(SubjectTestHelper.SUBJ0, NamingPrivilege.CREATE);
    AttributeDefSave attributeDefSave =
        new AttributeDefSave(this.grouperSession).assignName("top:b");
    AttributeDef attributeDef = attributeDefSave.save();
    assertEquals("top:b", attributeDef.getName());
    assertNull(attributeDef.getDescription());
    assertFalse(attributeDef.isMultiValued());
    assertEquals(SaveResultType.INSERT, attributeDefSave.getSaveResultType());

    // update
    attributeDefSave =
        new AttributeDefSave(this.grouperSession)
            .assignName("top:b")
            .assignDescription("whatever")
            .assignValueType(AttributeDefValueType.string)
            .assignMultiValued(true);
    attributeDef = attributeDefSave.save();
    assertEquals(SaveResultType.UPDATE, attributeDefSave.getSaveResultType());
    assertEquals("whatever", attributeDef.getDescription());
    assertTrue(attributeDef.isMultiValued());

    // no change
    attributeDefSave =
        new AttributeDefSave(this.grouperSession)
            .assignName("top:b")
            .assignDescription("whatever")
            .assignValueType(AttributeDefValueType.string)
            .assignMultiValued(true);
    attributeDef = attributeDefSave.save();
    assertEquals(SaveResultType.NO_CHANGE, attributeDefSave.getSaveResultType());
    assertEquals("whatever", attributeDef.getDescription());
    assertTrue(attributeDef.isMultiValued());
  }
  /**
   * remove objects not allowed to see privileges on
   *
   * @param groupsAndStems
   */
  public static void removeObjectsNotAllowedToSeePrivs(Set<?> groupsAndStems) {

    if (groupsAndStems == null) {
      return;
    }

    // subject who is making the query
    final Subject grouperSessionSubject = GrouperSession.staticGrouperSession().getSubject();

    Iterator<?> iterator = groupsAndStems.iterator();

    while (iterator.hasNext()) {
      Object groupOrStem = iterator.next();

      if (groupOrStem instanceof Group) {

        Group group = (Group) groupOrStem;
        if (!group.hasAdmin(grouperSessionSubject)) {
          iterator.remove();
        }
      } else if (groupOrStem instanceof Stem) {

        Stem stem = (Stem) groupOrStem;
        if (!stem.hasStem(grouperSessionSubject)) {
          iterator.remove();
        }

      } else {
        // this should never happen
        throw new RuntimeException(
            "Not expecting object of type: " + groupOrStem.getClass() + ", " + groupOrStem);
      }
    }
  }
  /**
   * retrieve if delegatable
   *
   * @param action
   * @param attributeDefName
   * @return if delegatable or grant
   */
  private AttributeAssignDelegatable retrieveDelegatable(
      String action, AttributeDefName attributeDefName) {

    if (AttributeDefType.perm != attributeDefName.getAttributeDef().getAttributeDefType()) {
      throw new RuntimeException(
          "Can only delegate a permission: "
              + attributeDefName.getAttributeDef().getAttributeDefType());
    }

    Set<PermissionEntry> permissionEntries =
        GrouperDAOFactory.getFactory()
            .getPermissionEntry()
            .findByMemberIdAndAttributeDefNameId(
                GrouperSession.staticGrouperSession().getMemberUuid(), attributeDefName.getId());

    boolean isGrant = false;
    boolean isDelegate = false;
    action = StringUtils.defaultString(action, AttributeDef.ACTION_DEFAULT);
    for (PermissionEntry permissionEntry : permissionEntries) {
      if (permissionEntry.isEnabled() && StringUtils.equals(action, permissionEntry.getAction())) {
        AttributeAssignDelegatable localDelegatable =
            permissionEntry.getAttributeAssignDelegatable();
        isGrant = isGrant || (localDelegatable == AttributeAssignDelegatable.GRANT);
        isDelegate = isDelegate || localDelegatable.delegatable();
      }
    }
    if (isGrant) {
      return AttributeAssignDelegatable.GRANT;
    }
    if (isDelegate) {
      return AttributeAssignDelegatable.TRUE;
    }
    return AttributeAssignDelegatable.FALSE;
  }
  /**
   * handle a click or select from the member menu
   *
   * @param httpServletRequest
   * @param httpServletResponse
   */
  @SuppressWarnings("unused")
  public void memberMenu(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

    GuiResponseJs guiResponseJs = GuiResponseJs.retrieveGuiResponseJs();

    final Subject loggedInSubject = GrouperUiFilter.retrieveSubjectLoggedIn();

    GrouperSession grouperSession = null;

    Group group = null;

    try {

      grouperSession = GrouperSession.start(loggedInSubject);

      // make sure we are on the right group
      group = new SimpleMembershipUpdate().retrieveGroup(grouperSession);

    } catch (NoSessionException se) {
      throw se;
    } catch (ControllerDone cd) {
      throw cd;
    } catch (Exception se) {
      throw new RuntimeException("Error member menu: " + group + ", " + se.getMessage(), se);
    } finally {
      GrouperSession.stopQuietly(grouperSession);
    }

    String menuItemId = httpServletRequest.getParameter("menuItemId");
    String menuHtmlId = httpServletRequest.getParameter("menuHtmlId");
    // String menuRadioGroup = httpServletRequest.getParameter("menuRadioGroup");
    // String menuCheckboxChecked  = httpServletRequest.getParameter("menuCheckboxChecked");

    menuHtmlId = httpServletRequest.getParameter("menuIdOfMenuTarget");
    if (StringUtils.equals(menuItemId, "memberDetails")) {
      //        guiResponseJs.addAction(GuiScreenAction.newAlert("Menu action: menuItemId: " +
      // menuItemId
      //            + ", menuHtmlId: " + menuHtmlId));
      this.memberMenuSubjectDetails();
    } else if (StringUtils.equals(menuItemId, "enabledDisabled")) {
      this.memberMenuEnabledDisabled();
    } else {
      throw new RuntimeException("Unexpected menu id: '" + menuItemId + "'");
    }
  }
  public void testGroupType() {

    GroupType adminType = GroupType.createType(GrouperSession.staticGrouperSession(), "adminType");
    groupA.addType(adminType);

    correctAttributesA.setAttribute("groupType", adminType, GroupTypeFinder.find("base", true));

    runResolveTest("testAttributesOnly", groupA, correctAttributesA);
  }
  /**
   * see if a group or parent or ancestor folder has an attribute. this can run securely.
   *
   * @param attributeFlagName
   * @param checkSecurity
   * @return true if group or stem has attribute
   */
  public boolean hasAttributeOrAncestorHasAttribute(
      final String attributeFlagName, final boolean checkSecurity) {

    final AttributeAssignable owner = this.getAttributeAssignable();

    if (checkSecurity) {
      Subject subjectMakingCall = GrouperSession.staticGrouperSession().getSubject();
      return hasAttributeOrAncestorHasAttributeHelper(
          owner, null, attributeFlagName, subjectMakingCall);
    }
    return (Boolean)
        GrouperSession.internal_callbackRootGrouperSession(
            new GrouperSessionHandler() {

              public Object callback(GrouperSession grouperSession) throws GrouperSessionException {
                return hasAttributeOrAncestorHasAttributeHelper(
                    owner, null, attributeFlagName, grouperSession.getSubject());
              }
            });
  }
  public void setUp() {
    super.setUp();
    try {
      this.s = GrouperSession.start(SubjectFinder.findRootSubject());
      this.root = StemFinder.findRootStem(this.s);

      this.originalRootSize = new ChildStemFilter(this.root).getResults(this.s).size();

      this.top = this.root.addChildStem("top", "top");
      this.child = this.top.addChildStem("child", "child");
    } catch (Exception e) {
      throw new GrouperException("test setUp() error: " + e.getMessage(), e);
    }
  }
  public void setUp() {

    super.setUp();

    // add etc:attribute:courses:courseType attribute
    Stem etcStem =
        StemFinder.findByName(GrouperSession.staticGrouperSession(), "etc:attribute", true);
    Stem coursesStem = etcStem.addChildStem("courses", "Courses");
    AttributeDef attributeDef =
        coursesStem.addChildAttributeDef("courseType", AttributeDefType.attr);
    attributeDef.setAssignToGroup(true);
    attributeDef.setMultiValued(true);
    attributeDef.setValueType(AttributeDefValueType.string);
    attributeDef.store();
    coursesStem.addChildAttributeDefName(attributeDef, "courseType", "courseType");
  }
  public Set getResults(GrouperSession s) throws QueryException {
    // note, no need for GrouperSession inverse of control
    GrouperSession.validate(s);
    Set results;

    if (ns.isRootStem()) {
      results =
          PrivilegeHelper.canViewGroups(
              s, GrouperDAOFactory.getFactory().getGroup().findAllByCreatedAfter(this.d));
    } else {
      results =
          PrivilegeHelper.canViewGroups(
              s,
              GrouperDAOFactory.getFactory()
                  .getGroup()
                  .findAllByCreatedAfter(this.d, getStringForScope(ns)));
    }
    return results;
  } // public Set getResults(s)
  /* (non-Javadoc)
   * @see edu.internet2.middleware.grouper.ui.RepositoryBrowser#init(edu.internet2.middleware.grouper.GrouperSession, java.util.ResourceBundle)
   */
  public void init(GrouperSession s, ResourceBundle bundle, ResourceBundle mediaBundle) {
    this.mediaBundle = mediaBundle;
    navBundle = bundle;
    this.s = s;
    this.subject = s.getSubject();

    isFlatCapable = "true".equals(getProperty("flat-capable"));
    rootNode = getProperty("root-node");
    if ("".equals(rootNode)) {
      try {
        rootNode = mediaBundle.getString("default.browse.stem");
      } catch (MissingResourceException mre) {
        // thats ok, just ignore
      }
      if (rootNode.startsWith("@")) rootNode = "";
    }
    hidePreRootNode = "true".equals(getProperty("hide-pre-root-node"));
    flatType = getProperty("flat-type");
    flatPrivs = getProperty("flat-privs").split(" ");
    search = getProperty("search");
    initialStems = getProperty("initial-stems");
  }
  /**
   * handle a click or select from the advanced menu
   *
   * @param httpServletRequest
   * @param httpServletResponse
   */
  public void advancedMenu(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
    GuiResponseJs guiResponseJs = GuiResponseJs.retrieveGuiResponseJs();

    final Subject loggedInSubject = GrouperUiFilter.retrieveSubjectLoggedIn();

    GrouperSession grouperSession = null;

    Group group = null;

    try {

      grouperSession = GrouperSession.start(loggedInSubject);

      // make sure we are on the right group
      group = new SimpleMembershipUpdate().retrieveGroup(grouperSession);

    } catch (NoSessionException se) {
      throw se;
    } catch (ControllerDone cd) {
      throw cd;
    } catch (Exception se) {
      throw new RuntimeException("Error advanced menu: " + group + ", " + se.getMessage(), se);
    } finally {
      GrouperSession.stopQuietly(grouperSession);
    }

    String menuItemId = httpServletRequest.getParameter("menuItemId");
    String menuEvent = httpServletRequest.getParameter("menuEvent");
    boolean isOnClick = StringUtils.equals("onClick", menuEvent);
    // String menuHtmlId = httpServletRequest.getParameter("menuHtmlId");
    // String menuRadioGroup = httpServletRequest.getParameter("menuRadioGroup");
    String menuCheckboxChecked = httpServletRequest.getParameter("menuCheckboxChecked");

    //    guiResponseJs.addAction(GuiScreenAction.newAlert("Menu action: menuItemId: " + menuItemId
    //        + ", menuHtmlId: " + menuHtmlId
    //        + ", menuRadioGroup: "
    //        + menuRadioGroup + ", menuCheckboxChecked: " + menuCheckboxChecked));

    if (StringUtils.equals(menuItemId, "inviteLink")) {
      guiResponseJs.addAction(
          GuiScreenAction.newScript(
              "window.location = 'grouper.html?operation=InviteExternalSubjects.inviteExternalSubject&groupId="
                  + group.getUuid()
                  + "'"));
    } else if (StringUtils.equals(menuItemId, "showGroupDetails")) {
      if (!isOnClick) {
        if (GrouperUtil.booleanValue(menuCheckboxChecked)) {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToShow("simpleMembershipUpdateGroupDetails"));
        } else {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToHide("simpleMembershipUpdateGroupDetails"));
        }
      }
    } else if (StringUtils.equals(menuItemId, "multiDelete")) {
      if (!isOnClick) {
        if (GrouperUtil.booleanValue(menuCheckboxChecked)) {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToShow("simpleMembershipUpdateDeleteMultiple"));
        } else {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToHide("simpleMembershipUpdateDeleteMultiple"));
        }
      }
    } else if (StringUtils.equals(menuItemId, "showMemberFilter")) {
      if (!isOnClick) {
        if (GrouperUtil.booleanValue(menuCheckboxChecked)) {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToShow("simpleMembershipUpdateMemberFilter"));
        } else {
          guiResponseJs.addAction(
              GuiScreenAction.newHideShowNameToHide("simpleMembershipUpdateMemberFilter"));
        }
      }
    } else if (StringUtils.equals(menuItemId, "exportSubjectIds")) {
      guiResponseJs.addAction(
          GuiScreenAction.newAlertFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateExportSubjectIds.jsp"));
    } else if (StringUtils.equals(menuItemId, "exportAll")) {
      guiResponseJs.addAction(
          GuiScreenAction.newAlertFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateExportAll.jsp"));

    } else if (StringUtils.equals(menuItemId, "import")) {
      guiResponseJs.addAction(
          GuiScreenAction.newDialogFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateImport.jsp"));
    } else {
      throw new RuntimeException("Unexpected menu id: '" + menuItemId + "'");
    }
  }
  /**
   * @param action is the action on the assignment (null means default action)
   * @param attributeDefName
   * @param assign true to assign, false to unassign
   * @param attributeAssignDelegateOptions if there are more options, null if not
   * @return the result including if added or already there
   */
  public AttributeAssignResult delegateAttribute(
      final String action,
      final AttributeDefName attributeDefName,
      final boolean assign,
      final AttributeAssignDelegateOptions attributeAssignDelegateOptions) {

    AttributeDef attributeDef = attributeDefName.getAttributeDef();

    if (attributeDef.isMultiAssignable()) {
      throw new RuntimeException(
          "This attribute must not be multi-assignable to call "
              + "this method, use the multi-assign methods: "
              + attributeDefName.getName());
    }

    this.assertCanDelegateAttributeDefName(action, attributeDefName);

    if (attributeAssignDelegateOptions != null
        && attributeAssignDelegateOptions.isAssignAttributeAssignDelegatable()) {
      if (attributeAssignDelegateOptions.getAttributeAssignDelegatable()
              == AttributeAssignDelegatable.GRANT
          || attributeAssignDelegateOptions.getAttributeAssignDelegatable()
              == AttributeAssignDelegatable.TRUE) {
        this.assertCanGrantAttributeDefName(action, attributeDefName);
      }
    }

    AttributeAssignResult attributeAssignResult =
        (AttributeAssignResult)
            GrouperSession.callbackGrouperSession(
                GrouperSession.staticGrouperSession().internal_getRootSession(),
                new GrouperSessionHandler() {

                  public Object callback(GrouperSession grouperSession)
                      throws GrouperSessionException {

                    if (assign) {

                      // do the same thing that an assign would do
                      // do this as root since the user who can delegate might not be able to
                      // assign...
                      AttributeAssignResult attributeAssignResult2 =
                          AttributeAssignBaseDelegate.this.internal_assignAttributeHelper(
                              action, attributeDefName, false, null, null);

                      if (attributeAssignDelegateOptions != null) {

                        AttributeAssign attributeAssign =
                            attributeAssignResult2.getAttributeAssign();
                        if (attributeAssignDelegateOptions.isAssignAttributeAssignDelegatable()) {
                          attributeAssign.setAttributeAssignDelegatable(
                              attributeAssignDelegateOptions.getAttributeAssignDelegatable());
                        }
                        if (attributeAssignDelegateOptions.isAssignDisabledDate()) {
                          attributeAssign.setDisabledTime(
                              attributeAssignDelegateOptions.getDisabledTime());
                        }
                        if (attributeAssignDelegateOptions.isAssignEnabledDate()) {
                          attributeAssign.setDisabledTime(
                              attributeAssignDelegateOptions.getEnabledTime());
                        }
                        attributeAssign.saveOrUpdate(true);
                      }
                      return attributeAssignResult2;
                    }

                    return AttributeAssignBaseDelegate.this.removeAttributeHelper(
                        action, attributeDefName, false);
                  }
                });

    return attributeAssignResult;
  }
  /** show subject details */
  @SuppressWarnings("unchecked")
  public void memberMenuSubjectDetails() {

    GuiResponseJs guiResponseJs = GuiResponseJs.retrieveGuiResponseJs();

    // lets see which subject we are dealing with:
    HttpServletRequest httpServletRequest = GrouperUiFilter.retrieveHttpServletRequest();
    String menuIdOfMenuTarget = httpServletRequest.getParameter("menuIdOfMenuTarget");
    if (StringUtils.isBlank(menuIdOfMenuTarget)) {
      throw new RuntimeException("Missing id of menu target");
    }
    if (!menuIdOfMenuTarget.startsWith("memberMenuButton_")) {
      throw new RuntimeException("Invalid id of menu target: '" + menuIdOfMenuTarget + "'");
    }
    String memberId = GrouperUtil.prefixOrSuffix(menuIdOfMenuTarget, "memberMenuButton_", false);

    final Subject loggedInSubject = GrouperUiFilter.retrieveSubjectLoggedIn();

    GrouperSession grouperSession = null;

    try {

      grouperSession = GrouperSession.start(loggedInSubject);

      Member member = MemberFinder.findByUuid(grouperSession, memberId, true);
      Subject subject = member.getSubject();
      String order = null;

      try {
        order =
            GrouperUiConfig.retrieveConfig()
                .propertyValueString("subject.attributes.order." + subject.getSource().getId());
      } catch (MissingResourceException mre) {
        // thats ok, go with default
      }

      if (StringUtils.isBlank(order)) {
        Set<String> attributeNames = new LinkedHashSet<String>();
        attributeNames.add("screenLabel");
        attributeNames.addAll(GrouperUtil.nonNull(subject.getAttributes()).keySet());

        // lets add subjectId, typeName, sourceId, sourceName, memberId
        attributeNames.add("subjectId");
        attributeNames.add("name");
        attributeNames.add("description");
        attributeNames.add("typeName");
        attributeNames.add("sourceId");
        attributeNames.add("sourceName");

        order = GrouperUtil.join(attributeNames.iterator(), ',');
      }

      String[] attrNames = GrouperUtil.splitTrim(order, ",");

      SimpleMembershipUpdateContainer simpleMembershipUpdateContainer =
          SimpleMembershipUpdateContainer.retrieveFromSession();
      simpleMembershipUpdateContainer.setSubjectForDetails(subject);
      simpleMembershipUpdateContainer.getSubjectDetails().clear();

      // lookup each attribute
      for (String attrName : attrNames) {

        // sometimes group have blank attributes???
        if (StringUtils.isBlank(attrName)) {
          continue;
        }
        String attributeValue = GuiSubject.attributeValue(subject, attrName);
        simpleMembershipUpdateContainer.getSubjectDetails().put(attrName, attributeValue);
      }
      guiResponseJs.addAction(
          GuiScreenAction.newAlertFromJsp(
              "/WEB-INF/grouperUi/templates/simpleMembershipUpdate/simpleMembershipUpdateSubjectDetails.jsp"));

    } catch (ControllerDone cd) {
      throw cd;
    } catch (NoSessionException nse) {
      throw nse;
    } catch (Exception se) {
      throw new RuntimeException(
          "Error listing member details: " + menuIdOfMenuTarget + ", " + se.getMessage(), se);
    } finally {
      GrouperSession.stopQuietly(grouperSession);
    }
  }
  /**
   * make the structure of the advanced menu
   *
   * @param httpServletRequest
   * @param httpServletResponse
   */
  public void advancedMenuStructure(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

    // get the text to add to html if showing details
    GuiHideShow showGroupDetails =
        GuiHideShow.retrieveHideShow("simpleMembershipUpdateGroupDetails", true);

    // get the text to add to html if showing multi delete
    GuiHideShow showMultiDelete =
        GuiHideShow.retrieveHideShow("simpleMembershipUpdateDeleteMultiple", true);

    // get the text to add to html if showing member filter
    GuiHideShow showMemberFilter =
        GuiHideShow.retrieveHideShow("simpleMembershipUpdateMemberFilter", true);

    SimpleMembershipUpdateContainer simpleMembershipUpdateContainer =
        SimpleMembershipUpdateContainer.retrieveFromSession();

    DhtmlxMenu dhtmlxMenu = new DhtmlxMenu();

    final Subject loggedInSubject = GrouperUiFilter.retrieveSubjectLoggedIn();

    Group group = null;
    GrouperSession grouperSession = null;
    boolean canInviteOthers = false;
    try {

      grouperSession = GrouperSession.start(loggedInSubject);

      group = new SimpleMembershipUpdate().retrieveGroup(grouperSession);

      UIGroupPrivilegeResolver resolver =
          UIGroupPrivilegeResolverFactory.getInstance(
              grouperSession,
              GrouperUiFilter.retrieveSessionMediaResourceBundle(),
              group,
              grouperSession.getSubject());
      canInviteOthers = resolver.canInviteExternalPeople();
    } finally {
      GrouperSession.stopQuietly(grouperSession);
    }

    {
      DhtmlxMenuItem multiDeleteMenuItem = new DhtmlxMenuItem();
      multiDeleteMenuItem.setId("multiDelete");
      multiDeleteMenuItem.setType("checkbox");
      if (showMultiDelete.isShowing()) {
        multiDeleteMenuItem.setChecked(showMultiDelete.isShowing());
      }
      multiDeleteMenuItem.setText(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuDeleteMultiple());
      multiDeleteMenuItem.setTooltip(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuDeleteMultipleTooltip());
      dhtmlxMenu.addDhtmlxItem(multiDeleteMenuItem);
    }

    {
      // see if we can invite
      if (canInviteOthers
          && GrouperUiConfig.retrieveConfig()
              .propertyValueBoolean("inviteExternalPeople.link-from-lite-ui", false)) {
        DhtmlxMenuItem memberInviteMenuItem = new DhtmlxMenuItem();
        memberInviteMenuItem.setId("inviteLink");
        memberInviteMenuItem.setText(TagUtils.navResourceString("ui-lite.invite-menu"));
        memberInviteMenuItem.setTooltip(TagUtils.navResourceString("ui-lite.invite-menuTooltip"));
        // memberInviteMenuItem.setHref("grouper.html?operation=InviteExternalSubjects.inviteExternalSubject&groupId=" + group.getUuid());
        // memberInviteMenuItem.setHref("http://localhost:8091/grouper/grouperUi/appHtml/grouper.html?operation=InviteExternalSubjects.inviteExternalSubject&groupId=0e0262d9be924774914052c12f0e7fd2");
        dhtmlxMenu.addDhtmlxItem(memberInviteMenuItem);
      }
    }

    {
      DhtmlxMenuItem groupDetailsMenuItem = new DhtmlxMenuItem();
      groupDetailsMenuItem.setId("showGroupDetails");
      groupDetailsMenuItem.setType("checkbox");
      if (showGroupDetails.isShowing()) {
        groupDetailsMenuItem.setChecked(showGroupDetails.isShowing());
      }
      groupDetailsMenuItem.setText(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuShowGroupDetails());
      groupDetailsMenuItem.setTooltip(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuShowGroupDetailsTooltip());
      dhtmlxMenu.addDhtmlxItem(groupDetailsMenuItem);
    }

    {
      DhtmlxMenuItem memberFilterMenuItem = new DhtmlxMenuItem();
      memberFilterMenuItem.setId("showMemberFilter");
      memberFilterMenuItem.setType("checkbox");
      if (showMemberFilter.isShowing()) {
        memberFilterMenuItem.setChecked(showMemberFilter.isShowing());
      }
      memberFilterMenuItem.setText(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuShowMemberFilter());
      memberFilterMenuItem.setTooltip(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuShowMemberFilterTooltip());
      dhtmlxMenu.addDhtmlxItem(memberFilterMenuItem);
    }

    DhtmlxMenuItem importExportMenuItem = new DhtmlxMenuItem();
    importExportMenuItem.setId("importExport");
    importExportMenuItem.setText(
        simpleMembershipUpdateContainer.getText().getAdvancedMenuImportExport());
    importExportMenuItem.setTooltip(
        simpleMembershipUpdateContainer.getText().getAdvancedMenuImportExportTooltip());
    dhtmlxMenu.addDhtmlxItem(importExportMenuItem);

    DhtmlxMenuItem exportMenuItem = new DhtmlxMenuItem();
    exportMenuItem.setId("export");
    exportMenuItem.setText(simpleMembershipUpdateContainer.getText().getAdvancedMenuExport());
    exportMenuItem.setTooltip(
        simpleMembershipUpdateContainer.getText().getAdvancedMenuExportTooltip());
    importExportMenuItem.addDhtmlxItem(exportMenuItem);

    {
      DhtmlxMenuItem exportSubjectIdsMenuItem = new DhtmlxMenuItem();
      exportSubjectIdsMenuItem.setId("exportSubjectIds");
      exportSubjectIdsMenuItem.setText(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuExportSubjectIds());
      exportSubjectIdsMenuItem.setTooltip(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuExportSubjectIdsTooltip());
      exportMenuItem.addDhtmlxItem(exportSubjectIdsMenuItem);
    }

    {
      DhtmlxMenuItem exportAllMenuItem = new DhtmlxMenuItem();
      exportAllMenuItem.setId("exportAll");
      exportAllMenuItem.setText(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuExportAll());
      exportAllMenuItem.setTooltip(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuExportAllTooltip());
      exportMenuItem.addDhtmlxItem(exportAllMenuItem);
    }

    {
      DhtmlxMenuItem importMenuItem = new DhtmlxMenuItem();
      importMenuItem.setId("import");
      importMenuItem.setText(simpleMembershipUpdateContainer.getText().getAdvancedMenuImport());
      importMenuItem.setTooltip(
          simpleMembershipUpdateContainer.getText().getAdvancedMenuImportTooltip());
      importExportMenuItem.addDhtmlxItem(importMenuItem);
    }

    GrouperUiUtils.printToScreen(
        "<?xml version=\"1.0\"?>\n" + dhtmlxMenu.toXml(), HttpContentType.TEXT_XML, false, false);
    throw new ControllerDone();
  }
  /**
   * @see
   *     edu.internet2.middleware.grouper.changeLog.ChangeLogConsumerBase#processChangeLogEntries(java.util.List,
   *     edu.internet2.middleware.grouper.changeLog.ChangeLogProcessorMetadata)
   */
  @Override
  public long processChangeLogEntries(
      List<ChangeLogEntry> changeLogEntryList,
      ChangeLogProcessorMetadata changeLogProcessorMetadata) {

    long currentId = -1;

    boolean startedGrouperSession = false;
    GrouperSession grouperSession = GrouperSession.staticGrouperSession(false);
    if (grouperSession == null) {
      grouperSession = GrouperSession.startRootSession();
      startedGrouperSession = true;
    } else {
      grouperSession = grouperSession.internal_getRootSession();
    }

    // try catch so we can track that we made some progress
    try {
      for (ChangeLogEntry changeLogEntry : changeLogEntryList) {
        currentId = changeLogEntry.getSequenceNumber();

        // if this is a group add action and category
        if (changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.GROUP_ADD)) {

          String groupName = changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_ADD.name);
          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String groupExtension = GrouperUtil.extensionFromName(groupName);
            // get the group in grouper
            String groupDescription =
                changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_ADD.description);
            // shouldnt be the case but check anyways
            if (!GrouperDuoCommands.retrieveGroups().containsKey(groupExtension)) {
              GrouperDuoCommands.createDuoGroup(groupExtension, groupDescription, true);
            }
          }
        } else if (changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.GROUP_DELETE)) {
          String groupName =
              changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_DELETE.name);
          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String groupExtension = GrouperUtil.extensionFromName(groupName);
            // shouldnt be the case but check anyways
            GrouperDuoGroup grouperDuoGroup =
                GrouperDuoCommands.retrieveGroups().get(groupExtension);
            if (grouperDuoGroup != null) {
              GrouperDuoCommands.deleteDuoGroup(grouperDuoGroup.getId(), true);
            }
          }
        }
        if (changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.GROUP_UPDATE)) {
          String groupName =
              changeLogEntry.retrieveValueForLabel(ChangeLogLabels.GROUP_UPDATE.name);
          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String groupExtension = GrouperUtil.extensionFromName(groupName);
            // get the group in grouper

            Group group = GroupFinder.findByName(grouperSession, groupName, false);

            if (group != null) {

              // shouldnt be the case but check anyways
              Map<String, GrouperDuoGroup> groupNameToDuoGroupMap =
                  GrouperDuoCommands.retrieveGroups();
              GrouperDuoGroup grouperDuoGroup = groupNameToDuoGroupMap.get(groupExtension);
              if (grouperDuoGroup != null) {
                GrouperDuoCommands.updateDuoGroup(
                    grouperDuoGroup.getId(), group.getDescription(), true);
              }
            }
          }
        }

        boolean isMembershipAdd =
            changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.MEMBERSHIP_ADD);
        boolean isMembershipDelete =
            changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.MEMBERSHIP_DELETE);
        boolean isMembershipUpdate =
            changeLogEntry.equalsCategoryAndAction(ChangeLogTypeBuiltin.MEMBERSHIP_UPDATE);
        if (isMembershipAdd || isMembershipDelete || isMembershipUpdate) {
          String groupName =
              changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_ADD.groupName);

          if (GrouperDuoUtils.validDuoGroupName(groupName)) {
            String sourceId =
                changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_ADD.sourceId);

            boolean inCorrectSubjectSource =
                GrouperDuoUtils.configSourcesForSubjects().contains(sourceId);

            if (inCorrectSubjectSource) {
              String groupExtension = GrouperUtil.extensionFromName(groupName);
              Group group = GroupFinder.findByName(grouperSession, groupName, false);
              Map<String, GrouperDuoGroup> groupNameToDuoGroupMap =
                  GrouperDuoCommands.retrieveGroups();
              GrouperDuoGroup grouperDuoGroup = groupNameToDuoGroupMap.get(groupExtension);
              String subjectId =
                  changeLogEntry.retrieveValueForLabel(ChangeLogLabels.MEMBERSHIP_ADD.subjectId);

              String subjectAttributeForDuoUsername =
                  GrouperDuoUtils.configSubjectAttributeForDuoUsername();

              String username = null;
              Subject subject = SubjectFinder.findByIdAndSource(subjectId, sourceId, false);

              if (StringUtils.equals("id", subjectAttributeForDuoUsername)) {
                username = subjectId;
              } else {

                if (subject != null) {
                  String attributeValue = subject.getAttributeValue(subjectAttributeForDuoUsername);
                  if (!StringUtils.isBlank(attributeValue)) {
                    username = attributeValue;
                  }
                }
              }

              String duoGroupId = grouperDuoGroup != null ? grouperDuoGroup.getId() : null;
              String duoUserId =
                  !StringUtils.isBlank(username)
                      ? GrouperDuoCommands.retrieveUserIdFromUsername(username)
                      : null;

              // cant do anything if missing these things
              if (!StringUtils.isBlank(duoGroupId) && !StringUtils.isBlank(duoUserId)) {

                boolean userInDuoGroup =
                    GrouperDuoCommands.userInGroup(duoUserId, duoGroupId, true);

                boolean addUserToGroup = isMembershipAdd;

                // if update it could have unexpired
                if (isMembershipUpdate
                    && group != null
                    && subject != null
                    && group.hasMember(subject)) {
                  addUserToGroup = true;
                }

                // see if any update is needed
                if (addUserToGroup != userInDuoGroup) {
                  if (addUserToGroup) {
                    GrouperDuoCommands.assignUserToGroup(duoUserId, duoGroupId, true);
                  } else {
                    GrouperDuoCommands.removeUserFromGroup(duoUserId, duoGroupId, true);
                  }
                }
              }
            }
          }
        }

        // we successfully processed this record
      }
    } catch (Exception e) {
      changeLogProcessorMetadata.registerProblem(e, "Error processing record", currentId);
      // we made it to this -1
      return currentId - 1;
    } finally {
      if (startedGrouperSession) {
        GrouperSession.stopQuietly(grouperSession);
      }
    }
    if (currentId == -1) {
      throw new RuntimeException("Couldnt process any records");
    }

    return currentId;
  }
示例#19
0
 public void setUp() {
   super.setUp();
   this.grouperSession = GrouperSession.start(SubjectFinder.findRootSubject());
   this.root = StemFinder.findRootStem(this.grouperSession);
   this.top = this.root.addChildStem("top", "top display name");
 }
示例#20
0
  /**
   * 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;
  }