예제 #1
0
  /**
   * Look up the id of a group authorized for one of the given roles. If no group is currently
   * authorized to perform this role then a new group will be created and assigned the role.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return The id of the group associated with that particular role or -1
   */
  public static int getCollectionDefaultRead(Context context, int collectionID)
      throws SQLException, AuthorizeException {
    Collection collection = Collection.find(context, collectionID);

    Group[] itemGroups =
        AuthorizeManager.getAuthorizedGroups(context, collection, Constants.DEFAULT_ITEM_READ);
    Group[] bitstreamGroups =
        AuthorizeManager.getAuthorizedGroups(context, collection, Constants.DEFAULT_BITSTREAM_READ);

    int itemGroupID = -1;

    // If there are more than one groups assigned either of these privileges then this role based
    // method will not work.
    // The user will need to go to the authorization section to manually straighten this out.
    if (itemGroups.length != 1 || bitstreamGroups.length != 1) {
      // do nothing the itemGroupID is already set to -1
    } else {
      Group itemGroup = itemGroups[0];
      Group bitstreamGroup = bitstreamGroups[0];

      // If the same group is not assigned both of these privileges then this role based method will
      // not work. The user
      // will need to go to the authorization section to manually straighten this out.
      if (itemGroup.getID() != bitstreamGroup.getID()) {
        // do nothing the itemGroupID is already set to -1
      } else {
        itemGroupID = itemGroup.getID();
      }
    }

    return itemGroupID;
  }
예제 #2
0
파일: Group.java 프로젝트: seesmith/DSpace
  /**
   * add group to this group
   *
   * @param g
   */
  public void addMember(Group g) {
    loadData(); // make sure Group has data loaded

    // don't add if it's already a member
    // and don't add itself
    if (isMember(g) || getID() == g.getID()) {
      return;
    }

    groups.add(g);
    groupsChanged = true;

    myContext.addEvent(
        new Event(Event.ADD, Constants.GROUP, getID(), Constants.GROUP, g.getID(), g.getName()));
  }
예제 #3
0
  /**
   * Return a List of the policies for a group
   *
   * @param c current context
   * @param g group to retrieve policies for
   * @return List of <code>ResourcePolicy</code> objects
   */
  public static List<ResourcePolicy> getPoliciesForGroup(Context c, Group g) throws SQLException {
    TableRowIterator tri =
        DatabaseManager.queryTable(
            c,
            "resourcepolicy",
            "SELECT * FROM resourcepolicy WHERE epersongroup_id= ? ",
            g.getID());

    List<ResourcePolicy> policies = new ArrayList<ResourcePolicy>();

    try {
      while (tri.hasNext()) {
        TableRow row = tri.next();

        // first check the cache (FIXME: is this right?)
        ResourcePolicy cachepolicy =
            (ResourcePolicy) c.fromCache(ResourcePolicy.class, row.getIntColumn("policy_id"));

        if (cachepolicy != null) {
          policies.add(cachepolicy);
        } else {
          policies.add(new ResourcePolicy(c, row));
        }
      }
    } finally {
      if (tri != null) {
        tri.close();
      }
    }

    return policies;
  }
예제 #4
0
  /**
   * Change default privileges from the anonymous group to a new group that will be created and
   * appropriate privileges assigned. The id of this new group will be returned.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @return The group ID of the new group.
   */
  public static int createCollectionDefaultReadGroup(Context context, int collectionID)
      throws SQLException, AuthorizeException, UIException {
    int roleID = getCollectionDefaultRead(context, collectionID);

    if (roleID != 0) {
      throw new UIException(
          "Unable to create a new default read group because either the group already exists or multiple groups are assigned the default privileges.");
    }

    Collection collection = Collection.find(context, collectionID);
    Group role = Group.create(context);
    role.setName("COLLECTION_" + collection.getID() + "_DEFAULT_READ");

    // Remove existing privileges from the anonymous group.
    AuthorizeManager.removePoliciesActionFilter(context, collection, Constants.DEFAULT_ITEM_READ);
    AuthorizeManager.removePoliciesActionFilter(
        context, collection, Constants.DEFAULT_BITSTREAM_READ);

    // Grant our new role the default privileges.
    AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_ITEM_READ, role);
    AuthorizeManager.addPolicy(context, collection, Constants.DEFAULT_BITSTREAM_READ, role);

    // Commit the changes
    role.update();
    context.commit();

    return role.getID();
  }
예제 #5
0
파일: FeedServlet.java 프로젝트: ekate/fda5
  // returns recently changed items, checking for accessibility
  private Item[] getItems(Context context, DSpaceObject dso) throws IOException, SQLException {
    try {
      // new method of doing the browse:
      String idx = ConfigurationManager.getProperty("recent.submissions.sort-option");
      if (idx == null) {
        throw new IOException(
            "There is no configuration supplied for: recent.submissions.sort-option");
      }
      BrowseIndex bix = BrowseIndex.getItemBrowseIndex();
      if (bix == null) {
        throw new IOException("There is no browse index with the name: " + idx);
      }

      BrowserScope scope = new BrowserScope(context);
      scope.setBrowseIndex(bix);
      if (dso != null) {
        scope.setBrowseContainer(dso);
      }

      for (SortOption so : SortOption.getSortOptions()) {
        if (so.getName().equals(idx)) {
          scope.setSortBy(so.getNumber());
        }
      }
      scope.setOrder(SortOption.DESCENDING);
      scope.setResultsPerPage(itemCount);

      // gather & add items to the feed.
      BrowseEngine be = new BrowseEngine(context);
      BrowseInfo bi = be.browseMini(scope);
      Item[] results = bi.getItemResults(context);

      if (includeAll) {
        return results;
      } else {
        // Check to see if we can include this item
        // Group[] authorizedGroups = AuthorizeManager.getAuthorizedGroups(context, results[i],
        // Constants.READ);
        // boolean added = false;
        List<Item> items = new ArrayList<Item>();
        for (Item result : results) {
          checkAccess:
          for (Group group :
              AuthorizeManager.getAuthorizedGroups(context, result, Constants.READ)) {
            if ((group.getID() == Group.ANONYMOUS_ID)) {
              items.add(result);
              break checkAccess;
            }
          }
        }
        return items.toArray(new Item[items.size()]);
      }
    } catch (SortException se) {
      log.error("caught exception: ", se);
      throw new IOException(se.getMessage(), se);
    } catch (BrowseException e) {
      log.error("caught exception: ", e);
      throw new IOException(e.getMessage(), e);
    }
  }
예제 #6
0
  /**
   * Look up the id of a group authorized for one of the given roles. If no group is currently
   * authorized to perform this role then a new group will be created and assigned the role.
   *
   * @param context The current DSpace context.
   * @param collectionID The collection id.
   * @param roleName ADMIN, WF_STEP1, WF_STEP2, WF_STEP3, SUBMIT, DEFAULT_READ.
   * @return The id of the group associated with that particular role, or -1 if the role was not
   *     found.
   */
  public static int getCollectionRole(Context context, int collectionID, String roleName)
      throws SQLException, AuthorizeException, IOException, TransformerException, SAXException,
          WorkflowConfigurationException, ParserConfigurationException {
    Collection collection = Collection.find(context, collectionID);

    // Determine the group based upon wich role we are looking for.
    Group roleGroup = null;
    if (ROLE_ADMIN.equals(roleName)) {
      roleGroup = collection.getAdministrators();
      if (roleGroup == null) {
        roleGroup = collection.createAdministrators();
      }
    } else if (ROLE_SUBMIT.equals(roleName)) {
      roleGroup = collection.getSubmitters();
      if (roleGroup == null) roleGroup = collection.createSubmitters();
    } else {
      if (ConfigurationManager.getProperty("workflow", "workflow.framework")
          .equals("xmlworkflow")) { // Resolve our id to a role
        roleGroup = getXMLWorkflowRole(context, collectionID, roleName, collection, roleGroup);
      } else {
        roleGroup = getOriginalWorkflowRole(roleName, collection, roleGroup);
      }
    }

    // In case we needed to create a group, save our changes
    collection.update();
    context.commit();

    // If the role name was valid then role should be non null,
    if (roleGroup != null) return roleGroup.getID();

    return -1;
  }
  private void populateTableRowFromCollection(Collection collection, TableRow row) {
    int id = collection.getID();
    Bitstream logo = collection.getLogo();
    Item templateItem = collection.getTemplateItem();
    Group admins = collection.getAdministrators();
    Group[] workflowGroups = collection.getWorkflowGroups();

    if (logo == null) {
      row.setColumnNull("logo_bitstream_id");
    } else {
      row.setColumn("logo_bitstream_id", logo.getID());
    }

    if (templateItem == null) {
      row.setColumnNull("template_item_id");
    } else {
      row.setColumn("template_item_id", templateItem.getID());
    }

    if (admins == null) {
      row.setColumnNull("admin");
    } else {
      row.setColumn("admin", admins.getID());
    }

    for (int i = 1; i <= workflowGroups.length; i++) {
      Group g = workflowGroups[i - 1];
      if (g == null) {
        row.setColumnNull("workflow_step_" + i);
      } else {
        row.setColumn("workflow_step_" + i, g.getID());
      }
    }

    // Now loop over all allowed metadata fields and set the value into the
    // TableRow.
    for (CollectionMetadataField field : CollectionMetadataField.values()) {
      String value = collection.getMetadata(field.toString());
      if (value == null) {
        row.setColumnNull(field.toString());
      } else {
        row.setColumn(field.toString(), value);
      }
    }

    row.setColumn("uuid", collection.getIdentifier().getUUID().toString());
  }
예제 #8
0
파일: Group.java 프로젝트: seesmith/DSpace
  /**
   * Create a new group
   *
   * @param context DSpace context object
   */
  public static Group create(Context context) throws SQLException, AuthorizeException {
    // FIXME - authorization?
    if (!AuthorizeManager.isAdmin(context)) {
      throw new AuthorizeException("You must be an admin to create an EPerson Group");
    }

    // Create a table row
    TableRow row = DatabaseManager.create(context, "epersongroup");

    Group g = new Group(context, row);

    log.info(LogManager.getHeader(context, "create_group", "group_id=" + g.getID()));

    context.addEvent(new Event(Event.CREATE, Constants.GROUP, g.getID(), null));

    return g;
  }
예제 #9
0
파일: Group.java 프로젝트: seesmith/DSpace
  /** Update the group - writing out group object and EPerson list if necessary */
  public void update() throws SQLException, AuthorizeException {
    // FIXME: Check authorisation
    DatabaseManager.update(myContext, myRow);

    if (modifiedMetadata) {
      myContext.addEvent(new Event(Event.MODIFY_METADATA, Constants.GROUP, getID(), getDetails()));
      modifiedMetadata = false;
      clearDetails();
    }

    // Redo eperson mappings if they've changed
    if (epeopleChanged) {
      // Remove any existing mappings
      DatabaseManager.updateQuery(
          myContext, "delete from epersongroup2eperson where eperson_group_id= ? ", getID());

      // Add new mappings
      Iterator<EPerson> i = epeople.iterator();

      while (i.hasNext()) {
        EPerson e = i.next();

        TableRow mappingRow = DatabaseManager.row("epersongroup2eperson");
        mappingRow.setColumn("eperson_id", e.getID());
        mappingRow.setColumn("eperson_group_id", getID());
        DatabaseManager.insert(myContext, mappingRow);
      }

      epeopleChanged = false;
    }

    // Redo Group mappings if they've changed
    if (groupsChanged) {
      // Remove any existing mappings
      DatabaseManager.updateQuery(
          myContext, "delete from group2group where parent_id= ? ", getID());

      // Add new mappings
      Iterator<Group> i = groups.iterator();

      while (i.hasNext()) {
        Group g = i.next();

        TableRow mappingRow = DatabaseManager.row("group2group");
        mappingRow.setColumn("parent_id", getID());
        mappingRow.setColumn("child_id", g.getID());
        DatabaseManager.insert(myContext, mappingRow);
      }

      // groups changed, now change group cache
      rethinkGroupCache();

      groupsChanged = false;
    }

    log.info(LogManager.getHeader(myContext, "update_group", "group_id=" + getID()));
  }
예제 #10
0
 /**
  * Removes all policies from a group for a particular object that belong to a Group. FIXME doesn't
  * check authorization
  *
  * @param c current context
  * @param o the object
  * @param g the group
  * @throws SQLException if there's a database problem
  */
 public static void removeGroupPolicies(Context c, DSpaceObject o, Group g) throws SQLException {
   DatabaseManager.updateQuery(
       c,
       "DELETE FROM resourcepolicy WHERE "
           + "resource_type_id= ? AND resource_id= ? AND epersongroup_id= ? ",
       o.getType(),
       o.getID(),
       g.getID());
 }
예제 #11
0
파일: Group.java 프로젝트: seesmith/DSpace
  /**
   * remove group from this group
   *
   * @param g
   */
  public void removeMember(Group g) {
    loadData(); // make sure Group has data loaded

    if (groups.remove(g)) {
      groupsChanged = true;
      myContext.addEvent(
          new Event(
              Event.REMOVE, Constants.GROUP, getID(), Constants.GROUP, g.getID(), g.getName()));
    }
  }
예제 #12
0
 /**
  * Return <code>true</code> if <code>other</code> is the same Group as this object, <code>false
  * </code> otherwise
  *
  * @param obj object to compare to
  * @return <code>true</code> if object passed in represents the same group as this object
  */
 @Override
 public boolean equals(Object obj) {
   if (obj == null) {
     return false;
   }
   Class<?> objClass = HibernateProxyHelper.getClassWithoutInitializingProxy(obj);
   if (getClass() != objClass) {
     return false;
   }
   final Group other = (Group) obj;
   return this.getID().equals(other.getID());
 }
예제 #13
0
  public void addListGroups(String groupID, List form, int errorFlag, Collection owningCollection)
      throws WingException, SQLException {

    if (isAdvancedFormEnabled) {
      // currently set group
      form.addLabel(T_groups);
      Select groupSelect = form.addItem().addSelect("group_id");
      groupSelect.setMultiple(false);

      java.util.List<Group> loadedGroups = null;

      // retrieve groups
      String name = ConfigurationManager.getProperty("webui.submission.restrictstep.groups");
      if (name != null) {
        Group uiGroup = groupService.findByName(context, name);
        if (uiGroup != null) loadedGroups = uiGroup.getMemberGroups();
      }
      if (loadedGroups == null || loadedGroups.size() == 0) {
        loadedGroups = groupService.findAll(context, GroupService.NAME);
      }

      // if no group selected for default set anonymous
      if (groupID == null || groupID.equals("")) groupID = "0";
      // when we're just loading the main step, also default to anonymous
      if (errorFlag == AccessStep.STATUS_COMPLETE) {
        groupID = "0";
      }
      for (Group group : loadedGroups) {
        boolean selectGroup = group.getID().toString().equals(groupID);
        groupSelect.addOption(selectGroup, group.getID().toString(), group.getName());
      }

      if (errorFlag == AccessStep.STATUS_DUPLICATED_POLICY
          || errorFlag == AccessStep.EDIT_POLICY_STATUS_DUPLICATED_POLICY
          || errorFlag == UploadWithEmbargoStep.STATUS_EDIT_POLICIES_DUPLICATED_POLICY
          || errorFlag == UploadWithEmbargoStep.STATUS_EDIT_POLICY_DUPLICATED_POLICY) {
        groupSelect.addError(T_error_duplicated_policy);
      }
    }
  }
예제 #14
0
파일: Group.java 프로젝트: seesmith/DSpace
 /**
  * Return <code>true</code> if <code>other</code> is the same Group as this object, <code>false
  * </code> otherwise
  *
  * @param obj object to compare to
  * @return <code>true</code> if object passed in represents the same group as this object
  */
 @Override
 public boolean equals(Object obj) {
   if (obj == null) {
     return false;
   }
   if (getClass() != obj.getClass()) {
     return false;
   }
   final Group other = (Group) obj;
   if (this.getID() != other.getID()) {
     return false;
   }
   return true;
 }
  @Override
  public List<EPerson> getEPeople(Group group) {
    try {
      // get epeople objects
      TableRowIterator tri =
          DatabaseManager.queryTable(
              context,
              "eperson",
              "SELECT e.eperson_id "
                  + "FROM eperson e, epersongroup2eperson eg2e "
                  + "WHERE eg2e.eperson_id = e.eperson_id "
                  + "AND eg2e.eperson_group_id = ?",
              group.getID());

      return returnAsList(tri);
    } catch (SQLException sqle) {
      throw new RuntimeException(":(", sqle);
    }
  }
예제 #16
0
  /**
   * Look up the id of a group authorized for one of the given roles. If no group is currently
   * authorized to perform this role then a new group will be created and assigned the role.
   *
   * @param context The current DSpace context.
   * @param communityID The collection id.
   * @param roleName ADMIN.
   * @return The id of the group associated with that particular role, or -1 if the role was not
   *     found.
   */
  public static int getCommunityRole(Context context, int communityID, String roleName)
      throws SQLException, AuthorizeException, IOException {
    Community community = Community.find(context, communityID);

    // Determine the group based upon which role we are looking for.
    Group role = null;
    if (ROLE_ADMIN.equals(roleName)) {
      role = community.getAdministrators();
      if (role == null) {
        role = community.createAdministrators();
      }
    }

    // In case we needed to create a group, save our changes
    community.update();
    context.commit();

    // If the role name was valid then role should be non null,
    if (role != null) {
      return role.getID();
    }

    return -1;
  }
  protected void notifyGroupOfTask(
      Context c, BasicWorkflowItem wi, Group mygroup, List<EPerson> epa)
      throws SQLException, IOException {
    // check to see if notification is turned off
    // and only do it once - delete key after notification has
    // been suppressed for the first time
    UUID myID = wi.getItem().getID();

    if (noEMail.containsKey(myID)) {
      // suppress email, and delete key
      noEMail.remove(myID);
    } else {
      try {
        // Get the item title
        String title = getItemTitle(wi);

        // Get the submitter's name
        String submitter = getSubmitterName(wi);

        // Get the collection
        Collection coll = wi.getCollection();

        String message = "";

        for (EPerson anEpa : epa) {
          Locale supportedLocale = I18nUtil.getEPersonLocale(anEpa);
          Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
          email.addArgument(title);
          email.addArgument(coll.getName());
          email.addArgument(submitter);

          ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale);
          switch (wi.getState()) {
            case WFSTATE_STEP1POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step1");

              break;

            case WFSTATE_STEP2POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step2");

              break;

            case WFSTATE_STEP3POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step3");

              break;
          }
          email.addArgument(message);
          email.addArgument(getMyDSpaceLink());
          email.addRecipient(anEpa.getEmail());
          email.send();
        }
      } catch (MessagingException e) {
        String gid = (mygroup != null) ? String.valueOf(mygroup.getID()) : "none";
        log.warn(
            LogManager.getHeader(
                c,
                "notifyGroupofTask",
                "cannot email user group_id="
                    + gid
                    + " workflow_item_id="
                    + wi.getID()
                    + ":  "
                    + e.getMessage()));
      }
    }
  }
예제 #18
0
  private static void notifyGroupOfTask(Context c, WorkflowItem wi, Group mygroup, EPerson[] epa)
      throws SQLException, IOException {
    // check to see if notification is turned off
    // and only do it once - delete key after notification has
    // been suppressed for the first time
    Integer myID = new Integer(wi.getItem().getID());

    if (noEMail.containsKey(myID)) {
      // suppress email, and delete key
      noEMail.remove(myID);
    } else {
      try {
        // Get the item title
        String title = getItemTitle(wi);

        // Get the submitter's name
        String submitter = getSubmitterName(wi);

        // Get the collection
        Collection coll = wi.getCollection();

        String message = "";

        for (int i = 0; i < epa.length; i++) {
          Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]);
          Email email =
              ConfigurationManager.getEmail(
                  I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
          email.addArgument(title);
          email.addArgument(coll.getMetadata("name"));
          email.addArgument(submitter);

          ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale);
          log.info("Locale des Resource Bundles: " + messages.getLocale().getDisplayName());
          switch (wi.getState()) {
            case WFSTATE_STEP1POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step1");

              break;

            case WFSTATE_STEP2POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step2");

              break;

            case WFSTATE_STEP3POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step3");

              break;
          }
          email.addArgument(message);
          email.addArgument(getMyDSpaceLink());
          email.addRecipient(epa[i].getEmail());
          email.send();
        }
      } catch (MessagingException e) {
        log.warn(
            LogManager.getHeader(
                c,
                "notifyGroupofTask",
                "cannot email user"
                    + " group_id"
                    + mygroup.getID()
                    + " workflow_item_id"
                    + wi.getID()));
      }
    }
  }
  public void addBody(Body body) throws WingException, SQLException {
    // Get all our parameters
    String baseURL = contextPath + "/admin/groups?administrative-continue=" + knot.getId();
    String query = parameters.getParameter("query", "");
    int page = parameters.getParameterAsInteger("page", 0);
    int highlightID = parameters.getParameterAsInteger("highlightID", -1);
    // FIXME: Bad!
    //        int resultCount = Group.searchResultCount(context, query);
    int resultCount = Group.search(context, query).length;
    Group[] groups = Group.search(context, query, page * PAGE_SIZE, PAGE_SIZE);

    // DIVISION: groups-main
    Division main =
        body.addInteractiveDivision(
            "groups-main",
            contextPath + "/admin/groups",
            Division.METHOD_POST,
            "primary administrative groups");
    main.setHead(T_main_head);

    // DIVISION: group-actions
    Division actions = main.addDivision("group-actions");
    actions.setHead(T_actions_head);

    // Browse Epeople
    List actionsList = actions.addList("actions");
    actionsList.addLabel(T_actions_create);
    actionsList.addItemXref(baseURL + "&submit_add", T_actions_create_link);
    actionsList.addLabel(T_actions_browse);
    actionsList.addItemXref(baseURL + "&query&submit_search", T_actions_browse_link);

    actionsList.addLabel(T_actions_search);
    org.dspace.app.xmlui.wing.element.Item actionItem = actionsList.addItem();
    Text queryField = actionItem.addText("query");
    if (query != null) queryField.setValue(query);
    queryField.setHelp(T_search_help);
    actionItem.addButton("submit_search").setValue(T_go);

    // DIVISION: group-search
    Division search = main.addDivision("group-search");
    search.setHead(T_search_head);

    if (resultCount > PAGE_SIZE) {
      // If there are enough results then paginate the results
      int firstIndex = page * PAGE_SIZE + 1;
      int lastIndex = page * PAGE_SIZE + groups.length;

      String nextURL = null, prevURL = null;
      if (page < (resultCount / PAGE_SIZE)) nextURL = baseURL + "&page=" + (page + 1);
      if (page > 0) prevURL = baseURL + "&page=" + (page - 1);

      search.setSimplePagination(resultCount, firstIndex, lastIndex, prevURL, nextURL);
    }

    Table table = search.addTable("groups-search-table", groups.length + 1, 1);
    Row header = table.addRow(Row.ROLE_HEADER);
    header.addCell().addContent(T_search_column1);
    header.addCell().addContent(T_search_column2);
    header.addCell().addContent(T_search_column3);
    header.addCell().addContent(T_search_column4);
    header.addCell().addContent(T_search_column5);

    for (Group group : groups) {
      Row row;
      if (group.getID() == highlightID) row = table.addRow(null, null, "highlight");
      else row = table.addRow();

      if (group.getID() > 1) {
        CheckBox select = row.addCell().addCheckBox("select_group");
        select.setLabel(new Integer(group.getID()).toString());
        select.addOption(new Integer(group.getID()).toString());
      } else {
        // Don't allow the user to remove the administrative (id:1) or
        // anonymous group (id:0)
        row.addCell();
      }

      row.addCell().addContent(group.getID());
      row.addCell().addXref(baseURL + "&submit_edit&groupID=" + group.getID(), group.getName());

      int memberCount = group.getMembers().length + group.getMemberGroups().length;
      row.addCell().addContent(memberCount == 0 ? "-" : String.valueOf(memberCount));

      Cell cell = row.addCell();
      if (FlowGroupUtils.getCollectionId(group.getName()) > -1) {
        Collection collection =
            Collection.find(context, FlowGroupUtils.getCollectionId(group.getName()));
        if (collection != null) {
          String collectionName = collection.getMetadata("name");

          if (collectionName == null) collectionName = "";
          else if (collectionName.length() > MAX_COLLECTION_NAME)
            collectionName = collectionName.substring(0, MAX_COLLECTION_NAME - 3) + "...";

          cell.addContent(collectionName + " ");

          Highlight highlight = cell.addHighlight("fade");

          highlight.addContent("[");
          highlight.addXref(
              contextPath + "/handle/" + collection.getExternalIdentifier().getCanonicalForm(),
              T_collection_link);
          highlight.addContent("]");
        }
      }
    }

    if (groups.length <= 0) {
      Cell cell = table.addRow().addCell(1, 5);
      cell.addHighlight("italic").addContent(T_no_results);
    } else {
      search.addPara().addButton("submit_delete").setValue(T_submit_delete);
    }

    search.addHidden("administrative-continue").setValue(knot.getId());
  }
예제 #20
0
 public void setGroupId(Group group) {
   myRow.setColumn("group_id", group.getID());
 }
예제 #21
0
  @RequestMapping(method = RequestMethod.POST)
  protected String processPost(
      @RequestAttribute Context context,
      ModelMap model,
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {

    Group group = null;
    group = checkGroup(context, request);

    if (group != null) {

      // is this user authorized to edit this group?
      AuthorizeManager.authorizeAction(context, group, Constants.ADD);

      boolean submit_edit = (request.getParameter("submit_edit") != null);
      boolean submit_group_update = (request.getParameter("submit_group_update") != null);
      boolean submit_group_delete = (request.getParameter("submit_group_delete") != null);
      boolean submit_confirm_delete = (request.getParameter("submit_confirm_delete") != null);
      boolean submit_cancel_delete = (request.getParameter("submit_cancel_delete") != null);

      // just chosen a group to edit - get group and pass it to
      // group-edit.jsp
      if (submit_edit && !submit_group_update && !submit_group_delete) {
        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        return "pages/admin/group-edit";
      } // update the members of the group
      else if (submit_group_update) {
        // first off, did we change the group name?
        String newName = request.getParameter("group_name");

        if (!newName.equals(group.getName())) {
          group.setName(newName);
          group.update();
        }

        int[] eperson_ids = Util.getIntParameters(request, "eperson_id");
        int[] group_ids = Util.getIntParameters(request, "group_ids");

        // now get members, and add new ones and remove missing ones
        EPerson[] members = group.getMembers();
        Group[] membergroups = group.getMemberGroups();

        if (eperson_ids != null) {
          // some epeople were listed, now make group's epeople match
          // given epeople
          Set memberSet = new HashSet();
          Set epersonIDSet = new HashSet();

          // add all members to a set
          for (int x = 0; x < members.length; x++) {
            Integer epersonID = Integer.valueOf(members[x].getID());
            memberSet.add(epersonID);
          }

          // now all eperson_ids are put in a set
          for (int x = 0; x < eperson_ids.length; x++) {
            epersonIDSet.add(Integer.valueOf(eperson_ids[x]));
          }

          // process eperson_ids, adding those to group not already
          // members
          Iterator i = epersonIDSet.iterator();

          while (i.hasNext()) {
            Integer currentID = (Integer) i.next();

            if (!memberSet.contains(currentID)) {
              group.addMember(EPerson.find(context, currentID.intValue()));
            }
          }

          // process members, removing any that aren't in eperson_ids
          for (int x = 0; x < members.length; x++) {
            EPerson e = members[x];

            if (!epersonIDSet.contains(Integer.valueOf(e.getID()))) {
              group.removeMember(e);
            }
          }
        } else {
          // no members found (ids == null), remove them all!

          for (int y = 0; y < members.length; y++) {
            group.removeMember(members[y]);
          }
        }

        if (group_ids != null) {
          // some groups were listed, now make group's member groups
          // match given group IDs
          Set memberSet = new HashSet();
          Set groupIDSet = new HashSet();

          // add all members to a set
          for (int x = 0; x < membergroups.length; x++) {
            Integer myID = Integer.valueOf(membergroups[x].getID());
            memberSet.add(myID);
          }

          // now all eperson_ids are put in a set
          for (int x = 0; x < group_ids.length; x++) {
            groupIDSet.add(Integer.valueOf(group_ids[x]));
          }

          // process group_ids, adding those to group not already
          // members
          Iterator i = groupIDSet.iterator();

          while (i.hasNext()) {
            Integer currentID = (Integer) i.next();

            if (!memberSet.contains(currentID)) {
              group.addMember(Group.find(context, currentID.intValue()));
            }
          }

          // process members, removing any that aren't in eperson_ids
          for (int x = 0; x < membergroups.length; x++) {
            Group g = membergroups[x];

            if (!groupIDSet.contains(Integer.valueOf(g.getID()))) {
              group.removeMember(g);
            }
          }

        } else {
          // no members found (ids == null), remove them all!
          for (int y = 0; y < membergroups.length; y++) {
            group.removeMember(membergroups[y]);
          }
        }

        group.update();

        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        context.commit();
        return "pages/admin/group-edit";
      } else if (submit_group_delete) {
        // direct to a confirmation step
        model.addAttribute("group", group);
        return "pages/admin/group-confirm-delete";
      } else if (submit_confirm_delete) {
        // phony authorize, only admins can do this
        AuthorizeManager.authorizeAction(context, group, Constants.WRITE);

        // delete group, return to group-list.jsp
        group.delete();

        return showMainPage(context, model, request, response);
      } else if (submit_cancel_delete) {
        // show group list
        return showMainPage(context, model, request, response);
      } else {
        // unknown action, show edit page
        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        return "pages/admin/group-edit";
      }
    } else {

      // want to add a group - create a blank one, and pass to
      // group_edit.jsp
      String button = UIUtil.getSubmitButton(request, "submit");

      if (button.equals("submit_add")) {
        group = Group.create(context);

        group.setName("new group" + group.getID());
        group.update();

        model.addAttribute("group", group);
        model.addAttribute("members", group.getMembers());
        model.addAttribute("membergroups", group.getMemberGroups());
        String utilsGrpName = Utils.addEntities(group.getName());
        model.addAttribute("utilsGrpName", utilsGrpName);

        context.commit();
        return "pages/admin/group-edit";

      } else {
        // show the main page (select groups)
        return showMainPage(context, model, request, response);
      }
    } // end
  } // end processGet
예제 #22
0
파일: Group.java 프로젝트: seesmith/DSpace
  /**
   * Get Set of all Integers all of the epeople members for a group
   *
   * @param c DSpace context
   * @param g Group object
   * @return Set of Integer epersonIDs
   * @throws SQLException
   */
  public static Set<Integer> allMemberIDs(Context c, Group g) throws SQLException {
    // two queries - first to get all groups which are a member of this group
    // second query gets all members of each group in the first query
    Set<Integer> epeopleIDs = new HashSet<Integer>();

    // Get all groups which are a member of this group
    TableRowIterator tri =
        DatabaseManager.queryTable(
            c, "group2groupcache", "SELECT * FROM group2groupcache WHERE parent_id= ? ", g.getID());

    Set<Integer> groupIDs = new HashSet<Integer>();

    try {
      while (tri.hasNext()) {
        TableRow row = tri.next();

        int childID = row.getIntColumn("child_id");

        groupIDs.add(Integer.valueOf(childID));
      }
    } finally {
      // close the TableRowIterator to free up resources
      if (tri != null) {
        tri.close();
      }
    }

    // now we have all the groups (including this one)
    // it is time to find all the EPeople who belong to those groups
    // and filter out all duplicates

    Object[] parameters = new Object[groupIDs.size() + 1];
    int idx = 0;
    Iterator<Integer> i = groupIDs.iterator();

    // don't forget to add the current group to this query!
    parameters[idx++] = Integer.valueOf(g.getID());

    StringBuilder epersonQuery = new StringBuilder();
    epersonQuery.append("SELECT * FROM epersongroup2eperson WHERE ");
    epersonQuery.append("eperson_group_id= ? ");

    if (i.hasNext()) {
      epersonQuery.append(" OR ");
    }

    while (i.hasNext()) {
      int groupID = (i.next()).intValue();
      parameters[idx++] = Integer.valueOf(groupID);

      epersonQuery.append("eperson_group_id= ? ");
      if (i.hasNext()) {
        epersonQuery.append(" OR ");
      }
    }

    // get all the EPerson IDs
    // Note: even through the query is dynamically built all data is separated
    // into the parameters array.
    tri =
        DatabaseManager.queryTable(c, "epersongroup2eperson", epersonQuery.toString(), parameters);

    try {
      while (tri.hasNext()) {
        TableRow row = tri.next();

        int epersonID = row.getIntColumn("eperson_id");

        epeopleIDs.add(Integer.valueOf(epersonID));
      }
    } finally {
      // close the TableRowIterator to free up resources
      if (tri != null) {
        tri.close();
      }
    }

    return epeopleIDs;
  }
예제 #23
0
파일: Group.java 프로젝트: seesmith/DSpace
  /**
   * get Set of Integers all of the group memberships for an eperson
   *
   * @param c
   * @param e
   * @return Set of Integer groupIDs
   * @throws SQLException
   */
  public static Set<Integer> allMemberGroupIDs(Context c, EPerson e) throws SQLException {
    Set<Integer> groupIDs = new HashSet<Integer>();

    if (e != null) {
      // two queries - first to get groups eperson is a member of
      // second query gets parent groups for groups eperson is a member of

      TableRowIterator tri =
          DatabaseManager.queryTable(
              c,
              "epersongroup2eperson",
              "SELECT * FROM epersongroup2eperson WHERE eperson_id= ?",
              e.getID());

      try {
        while (tri.hasNext()) {
          TableRow row = tri.next();

          int childID = row.getIntColumn("eperson_group_id");

          groupIDs.add(Integer.valueOf(childID));
        }
      } finally {
        // close the TableRowIterator to free up resources
        if (tri != null) {
          tri.close();
        }
      }
    }
    // Also need to get all "Special Groups" user is a member of!
    // Otherwise, you're ignoring the user's membership to these groups!
    // However, we only do this is we are looking up the special groups
    // of the current user, as we cannot look up the special groups
    // of a user who is not logged in.
    if ((c.getCurrentUser() == null)
        || (((c.getCurrentUser() != null) && (c.getCurrentUser().getID() == e.getID())))) {
      Group[] specialGroups = c.getSpecialGroups();
      for (Group special : specialGroups) {
        groupIDs.add(Integer.valueOf(special.getID()));
      }
    }

    // all the users are members of the anonymous group
    groupIDs.add(Integer.valueOf(0));

    // now we have all owning groups, also grab all parents of owning groups
    // yes, I know this could have been done as one big query and a union,
    // but doing the Oracle port taught me to keep to simple SQL!

    StringBuilder groupQuery = new StringBuilder();
    groupQuery.append("SELECT * FROM group2groupcache WHERE ");

    Iterator<Integer> i = groupIDs.iterator();

    // Build a list of query parameters
    Object[] parameters = new Object[groupIDs.size()];
    int idx = 0;
    while (i.hasNext()) {
      int groupID = (i.next()).intValue();

      parameters[idx++] = Integer.valueOf(groupID);

      groupQuery.append("child_id= ? ");
      if (i.hasNext()) {
        groupQuery.append(" OR ");
      }
    }

    // was member of at least one group
    // NOTE: even through the query is built dynamically, all data is
    // separated into the parameters array.
    TableRowIterator tri =
        DatabaseManager.queryTable(c, "group2groupcache", groupQuery.toString(), parameters);

    try {
      while (tri.hasNext()) {
        TableRow row = tri.next();

        int parentID = row.getIntColumn("parent_id");

        groupIDs.add(Integer.valueOf(parentID));
      }
    } finally {
      // close the TableRowIterator to free up resources
      if (tri != null) {
        tri.close();
      }
    }

    return groupIDs;
  }
  @Override
  public List<EPerson> getAllEPeople(Group group) {
    try {
      // two queries - first to get all groups which are a member of this
      // group second query gets all members of each group in the first
      // query

      // Get all groups which are a member of this group
      TableRowIterator tri =
          DatabaseManager.queryTable(
              context,
              "group2groupcache",
              "SELECT * FROM group2groupcache WHERE parent_id = ? ",
              group.getID());

      Set<Integer> groupIDs = new HashSet<Integer>();

      for (TableRow row : tri.toList()) {
        int childID = row.getIntColumn("child_id");
        groupIDs.add(childID);
      }

      // now we have all the groups (including this one) it is time to
      // find all the EPeople who belong to those groups and filter out
      // all duplicates

      Object[] parameters = new Object[groupIDs.size() + 1];
      int idx = 0;

      // don't forget to add the current group to this query!
      parameters[idx++] = group.getID();
      String epersonQuery = "eperson_group_id= ? ";

      if (groupIDs.size() > 0) {
        epersonQuery += " OR ";
      }

      for (Integer i : groupIDs) {
        parameters[idx++] = i;

        epersonQuery += "eperson_group_id= ? ";

        if (idx < groupIDs.size()) {
          epersonQuery += " OR ";
        }
      }

      // get all the EPerson IDs
      // Note: even through the query is dynamicaly built all data is
      // seperated into the parameters array.
      tri =
          DatabaseManager.queryTable(
              context,
              "epersongroup2eperson",
              "SELECT eperson_id FROM epersongroup2eperson WHERE " + epersonQuery,
              parameters);

      return returnAsList(tri);
    } catch (SQLException sqle) {
      throw new RuntimeException(sqle);
    }
  }
예제 #25
0
  public int[] getSpecialGroups(Context context, HttpServletRequest request) throws SQLException {
    if (request == null) {
      return new int[0];
    }
    List<Integer> groupIDs = new ArrayList<Integer>();

    // Get the user's IP address
    String addr = request.getRemoteAddr();
    if (useProxies == null) {
      useProxies = ConfigurationManager.getBooleanProperty("useProxies", false);
    }
    if (useProxies && request.getHeader("X-Forwarded-For") != null) {
      /* This header is a comma delimited list */
      for (String xfip : request.getHeader("X-Forwarded-For").split(",")) {
        if (!request.getHeader("X-Forwarded-For").contains(addr)) {
          addr = xfip.trim();
        }
      }
    }

    for (IPMatcher ipm : ipMatchers) {
      try {
        if (ipm.match(addr)) {
          // Do we know group ID?
          Integer g = ipMatcherGroupIDs.get(ipm);
          if (g != null) {
            groupIDs.add(g);
          } else {
            // See if we have a group name
            String groupName = ipMatcherGroupNames.get(ipm);

            if (groupName != null) {
              Group group = Group.findByName(context, groupName);
              if (group != null) {
                // Add ID so we won't have to do lookup again
                ipMatcherGroupIDs.put(ipm, Integer.valueOf(group.getID()));
                ipMatcherGroupNames.remove(ipm);

                groupIDs.add(Integer.valueOf(group.getID()));
              } else {
                log.warn(
                    LogManager.getHeader(
                        context, "configuration_error", "unknown_group=" + groupName));
              }
            }
          }
        }
      } catch (IPMatcherException ipme) {
        log.warn(LogManager.getHeader(context, "configuration_error", "bad_ip=" + addr), ipme);
      }
    }

    // Now remove any negative matches
    for (IPMatcher ipm : ipNegativeMatchers) {
      try {
        if (ipm.match(addr)) {
          // Do we know group ID?
          Integer g = ipMatcherGroupIDs.get(ipm);
          if (g != null) {
            groupIDs.remove(g);
          } else {
            // See if we have a group name
            String groupName = ipMatcherGroupNames.get(ipm);

            if (groupName != null) {
              Group group = Group.findByName(context, groupName);
              if (group != null) {
                // Add ID so we won't have to do lookup again
                ipMatcherGroupIDs.put(ipm, Integer.valueOf(group.getID()));
                ipMatcherGroupNames.remove(ipm);

                groupIDs.remove(Integer.valueOf(group.getID()));
              } else {
                log.warn(
                    LogManager.getHeader(
                        context, "configuration_error", "unknown_group=" + groupName));
              }
            }
          }
        }
      } catch (IPMatcherException ipme) {
        log.warn(LogManager.getHeader(context, "configuration_error", "bad_ip=" + addr), ipme);
      }
    }

    int[] results = new int[groupIDs.size()];
    for (int i = 0; i < groupIDs.size(); i++) {
      results[i] = (groupIDs.get(i)).intValue();
    }

    if (log.isDebugEnabled()) {
      StringBuffer gsb = new StringBuffer();

      for (int i = 0; i < results.length; i++) {
        if (i > 0) {
          gsb.append(",");
        }
        gsb.append(results[i]);
      }

      log.debug(LogManager.getHeader(context, "authenticated", "special_groups=" + gsb.toString()));
    }

    return results;
  }