Exemplo n.º 1
0
  @Override
  public void addCollection(Context context, Community community, Collection collection)
      throws SQLException, AuthorizeException {
    // Check authorisation
    authorizeService.authorizeAction(context, community, Constants.ADD);

    log.info(
        LogManager.getHeader(
            context,
            "add_collection",
            "community_id=" + community.getID() + ",collection_id=" + collection.getID()));

    if (!community.getCollections().contains(collection)) {
      community.addCollection(collection);
      collection.addCommunity(community);
    }
    context.addEvent(
        new Event(
            Event.ADD,
            Constants.COMMUNITY,
            community.getID(),
            Constants.COLLECTION,
            collection.getID(),
            community.getHandle(),
            getIdentifiers(context, community)));
  }
Exemplo n.º 2
0
  @Override
  public void removeCollection(Context context, Community community, Collection collection)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    authorizeService.authorizeAction(context, community, Constants.REMOVE);

    community.removeCollection(collection);
    ArrayList<String> removedIdentifiers = collectionService.getIdentifiers(context, collection);
    String removedHandle = collection.getHandle();
    UUID removedId = collection.getID();

    collection.removeCommunity(community);
    if (CollectionUtils.isEmpty(collection.getCommunities())) {
      collectionService.delete(context, collection);
    }

    log.info(
        LogManager.getHeader(
            context,
            "remove_collection",
            "community_id=" + community.getID() + ",collection_id=" + collection.getID()));

    // Remove any mappings
    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.COMMUNITY,
            community.getID(),
            Constants.COLLECTION,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
Exemplo n.º 3
0
  /** Internal method to process subcommunities recursively */
  protected void addCollectionList(Community community, List<Collection> collectionList)
      throws SQLException {
    for (Community subcommunity : community.getSubcommunities()) {
      addCollectionList(subcommunity, collectionList);
    }

    for (Collection collection : community.getCollections()) {
      collectionList.add(collection);
    }
  }
Exemplo n.º 4
0
 @Ignore
 @Test
 public void testCommunity() {
   // we can also add other tests within the same class; this was added after
   // a problem with createCommunity() to actually perform a specific test over
   // the problematic step narrowing the case
   Community comm = new Community();
   comm.setTitle("Test");
   assertEquals("Test", comm.getTitle());
 }
Exemplo n.º 5
0
  @Override
  public void update(Context context, Community community) throws SQLException, AuthorizeException {
    // Check authorisation
    canEdit(context, community);

    log.info(
        LogManager.getHeader(context, "update_community", "community_id=" + community.getID()));

    communityDAO.save(context, community);
    if (community.isModified()) {
      context.addEvent(
          new Event(
              Event.MODIFY,
              Constants.COMMUNITY,
              community.getID(),
              null,
              getIdentifiers(context, community)));
      community.setModified();
    }
    if (community.isMetadataModified()) {
      context.addEvent(
          new Event(
              Event.MODIFY_METADATA,
              Constants.COMMUNITY,
              community.getID(),
              community.getDetails(),
              getIdentifiers(context, community)));
      community.clearModified();
    }
    community.clearDetails();
  }
Exemplo n.º 6
0
  @Override
  public void addSubcommunity(Context context, Community parentCommunity, Community childCommunity)
      throws SQLException, AuthorizeException {
    // Check authorisation
    authorizeService.authorizeAction(context, parentCommunity, Constants.ADD);

    log.info(
        LogManager.getHeader(
            context,
            "add_subcommunity",
            "parent_comm_id="
                + parentCommunity.getID()
                + ",child_comm_id="
                + childCommunity.getID()));

    if (!parentCommunity.getSubcommunities().contains(childCommunity)) {
      parentCommunity.addSubCommunity(childCommunity);
      childCommunity.addParentCommunity(parentCommunity);
    }
    context.addEvent(
        new Event(
            Event.ADD,
            Constants.COMMUNITY,
            parentCommunity.getID(),
            Constants.COMMUNITY,
            childCommunity.getID(),
            parentCommunity.getHandle(),
            getIdentifiers(context, parentCommunity)));
  }
Exemplo n.º 7
0
  @Override
  public void removeSubcommunity(
      Context context, Community parentCommunity, Community childCommunity)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    authorizeService.authorizeAction(context, parentCommunity, Constants.REMOVE);

    ArrayList<String> removedIdentifiers = getIdentifiers(context, childCommunity);
    String removedHandle = childCommunity.getHandle();
    UUID removedId = childCommunity.getID();

    parentCommunity.removeSubCommunity(childCommunity);
    childCommunity.getParentCommunities().remove(parentCommunity);
    if (CollectionUtils.isEmpty(childCommunity.getParentCommunities())) {
      rawDelete(context, childCommunity);
    }
    log.info(
        LogManager.getHeader(
            context,
            "remove_subcommunity",
            "parent_comm_id="
                + parentCommunity.getID()
                + ",child_comm_id="
                + childCommunity.getID()));

    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.COMMUNITY,
            parentCommunity.getID(),
            Constants.COMMUNITY,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
Exemplo n.º 8
0
  @Override
  public List<Collection> getAllCollections(Context context, Community community)
      throws SQLException {
    List<Collection> collectionList = new ArrayList<Collection>();
    List<Community> subCommunities = community.getSubcommunities();
    for (Community subCommunity : subCommunities) {
      addCollectionList(subCommunity, collectionList);
    }

    List<Collection> collections = community.getCollections();
    for (Collection collection : collections) {
      collectionList.add(collection);
    }
    return collectionList;
  }
Exemplo n.º 9
0
  @Ignore
  @Test
  public void testCreate() throws Exception {

    CommunityService svc = new CommunityService();
    Community comm = new Community();

    // using static constants allow to make assertions about them within the test client
    comm.setTitle(NEW_COMMUNITY);
    comm.setContent(TEST_COMMUNITY_DESCRIPTION);

    comm = svc.createCommunity(comm, true);
    assertEquals("NEW_COMMUNITY", comm.getTitle());
    assertEquals("TEST_COMMUNITY_DESCRIPTION", comm.getContent());
  }
Exemplo n.º 10
0
 @Override
 public int countItems(Context context, Community community) throws SQLException {
   int total = 0;
   // add collection counts
   List<Collection> cols = community.getCollections();
   for (Collection col : cols) {
     total += itemService.countItems(context, col);
   }
   // add sub-community counts
   List<Community> comms = community.getSubcommunities();
   for (int j = 0; j < comms.size(); j++) {
     total += countItems(context, comms.get(j));
   }
   return total;
 }
Exemplo n.º 11
0
  @Override
  public void removeAdministrators(Context context, Community community)
      throws SQLException, AuthorizeException {
    // Check authorisation - Must be an Admin of the parent community (or system admin) to delete
    // Admin group
    AuthorizeUtil.authorizeRemoveAdminGroup(context, community);

    // just return if there is no administrative group.
    if (community.getAdministrators() == null) {
      return;
    }

    // Remove the link to the community table.
    community.setAdmins(null);
  }
Exemplo n.º 12
0
  @Override
  public void setMetadata(Context context, Community community, String field, String value)
      throws MissingResourceException, SQLException {
    if ((field.trim()).equals("name") && (value == null || value.trim().equals(""))) {
      try {
        value = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled");
      } catch (MissingResourceException e) {
        value = "Untitled";
      }
    }

    String[] MDValue = getMDValueByLegacyField(field);

    /*
     * Set metadata field to null if null
     * and trim strings to eliminate excess
     * whitespace.
     */
    if (value == null) {
      clearMetadata(context, community, MDValue[0], MDValue[1], MDValue[2], Item.ANY);
    } else {
      setMetadataSingleValue(context, community, MDValue[0], MDValue[1], MDValue[2], null, value);
    }
    community.addDetails(field);
  }
Exemplo n.º 13
0
  @Override
  public void delete(Context context, Community community)
      throws SQLException, AuthorizeException, IOException {
    // Check authorisation
    // FIXME: If this was a subcommunity, it is first removed from it's
    // parent.
    // This means the parentCommunity == null
    // But since this is also the case for top-level communities, we would
    // give everyone rights to remove the top-level communities.
    // The same problem occurs in removing the logo
    if (!authorizeService.authorizeActionBoolean(
        context, getParentObject(context, community), Constants.REMOVE)) {
      authorizeService.authorizeAction(context, community, Constants.DELETE);
    }
    ArrayList<String> removedIdentifiers = getIdentifiers(context, community);
    String removedHandle = community.getHandle();
    UUID removedId = community.getID();

    // If not a top-level community, have parent remove me; this
    // will call rawDelete() before removing the linkage
    Community parent = (Community) getParentObject(context, community);

    if (parent != null) {
      // remove the subcommunities first
      Iterator<Community> subcommunities = community.getSubcommunities().iterator();
      while (subcommunities.hasNext()) {
        Community subCommunity = subcommunities.next();
        subcommunities.remove();
        delete(context, subCommunity);
      }
      // now let the parent remove the community
      removeSubcommunity(context, parent, community);

      return;
    }

    rawDelete(context, community);
    context.addEvent(
        new Event(
            Event.REMOVE,
            Constants.SITE,
            siteService.findSite(context).getID(),
            Constants.COMMUNITY,
            removedId,
            removedHandle,
            removedIdentifiers));
  }
Exemplo n.º 14
0
  @Ignore
  @Test
  public void testLoad() throws Exception {

    // test should use code in the same way we expect implementors to use it,
    // i.e. no changes at all from the java samples.

    CommunityService svc = new CommunityService();

    Collection<Community> communities = svc.getPublicCommunities();
    // some sample assertion, a proper test would be much more detailed than this
    for (Community community : communities) {
      assertNotNull(community.getTitle());
    }

    assertEquals(communities.size(), 2);
  }
Exemplo n.º 15
0
 @Override
 public DSpaceObject getParentObject(Context context, Community community) throws SQLException {
   List<Community> parentCommunities = community.getParentCommunities();
   if (CollectionUtils.isNotEmpty(parentCommunities)) {
     return parentCommunities.iterator().next();
   } else {
     return null;
   }
 }
Exemplo n.º 16
0
  /**
   * Get a preserved community backup file and respective children from cloud.
   *
   * @param context context DSpace
   * @param ref ID of the community
   * @param establishConnection true if pretend establish connection to cloud
   * @return true if file correctly sent to cloud, or false if not
   */
  public Boolean getCommunityAndChilds(Context context, Integer ref, Boolean establishConnection) {
    // if true make the connection available
    if (establishConnection == true) {
      this.makeConnection();
      this.filesInCloud.putAll(this.newCloudConnection.getInfoFilesIn(Constants.COMMUNITY));
    }

    // get file community from cloud
    getCommunity(context, ref, false);

    Community obj;
    Community[] subCommunities;
    Collection[] collections;

    // get community and the respective sub-communities and childs
    try {
      obj = Community.find(context, ref);
      subCommunities = obj.getSubcommunities();
      collections = obj.getCollections();
    } catch (Exception ex) {
      // it means it is the first father in the order, so close connection
      if (establishConnection == true) this.closeConnection();
      Logger.getLogger(ActualContentManagement.class.getName()).log(Level.SEVERE, null, ex);
      return false;
    }

    // get from cloud all the respective files sub-communities and childs
    if (subCommunities.length != 0) {
      for (int i = 0; i < subCommunities.length; i++)
        getCommunityAndChilds(context, subCommunities[i].getID(), false);
    }

    // get from cloud all files collections and childs
    if (collections.length != 0) {
      for (int i = 0; i < collections.length; i++)
        getCollectionAndChilds(context, collections[i].getID(), false);
    }

    // it means it is the first father in the order
    if (establishConnection == true) this.closeConnection();

    return true;
  }
Exemplo n.º 17
0
  /**
   * Get an array of all the collections that the current SWORD context will allow deposit onto in
   * the given DSpace context
   *
   * <p>The user may submit to a community if the following conditions are met:
   *
   * <p>IF: the authenticated user is an administrator AND: (the on-behalf-of user is an
   * administrator OR the on-behalf-of user is authorised to READ OR the on-behalf-of user is null)
   * OR IF: the authenticated user is authorised to READ AND: (the on-behalf-of user is an
   * administrator OR the on-behalf-of user is authorised to READ OR the on-behalf-of user is null)
   *
   * @param community
   * @return the array of allowed collections
   * @throws DSpaceSwordException
   */
  public List<Community> getCommunities(SwordContext swordContext, Community community)
      throws DSpaceSwordException {
    // a community is allowed if the following conditions are met
    //
    // - the authenticated user is an administrator
    // -- the on-behalf-of user is an administrator
    // -- the on-behalf-of user is authorised to READ
    // -- the on-behalf-of user is null
    // - the authenticated user is authorised to READ
    // -- the on-behalf-of user is an administrator
    // -- the on-behalf-of user is authorised to READ
    // -- the on-behalf-of user is null
    try {
      Community[] comms = community.getSubcommunities();
      List<Community> allowed = new ArrayList<Community>();

      for (int i = 0; i < comms.length; i++) {
        boolean authAllowed = false;
        boolean oboAllowed = false;

        // check for obo null
        if (swordContext.getOnBehalfOf() == null) {
          oboAllowed = true;
        }

        // look up the READ policy on the community.  This will include determining if the user is
        // an administrator
        // so we do not need to check that separately
        if (!authAllowed) {
          authAllowed =
              AuthorizeManager.authorizeActionBoolean(
                  swordContext.getAuthenticatorContext(), comms[i], Constants.READ);
        }

        // if we have not already determined that the obo user is ok to submit, look up the READ
        // policy on the
        // community.  THis will include determining if the user is an administrator.
        if (!oboAllowed) {
          oboAllowed =
              AuthorizeManager.authorizeActionBoolean(
                  swordContext.getOnBehalfOfContext(), comms[i], Constants.READ);
        }

        // final check to see if we are allowed to READ
        if (authAllowed && oboAllowed) {
          allowed.add(comms[i]);
        }
      }
      return allowed;

    } catch (SQLException e) {
      log.error("Caught exception: ", e);
      throw new DSpaceSwordException(e);
    }
  }
Exemplo n.º 18
0
 @Override
 public void updateLastModified(Context context, Community community) {
   // Also fire a modified event since the community HAS been modified
   context.addEvent(
       new Event(
           Event.MODIFY,
           Constants.COMMUNITY,
           community.getID(),
           null,
           getIdentifiers(context, community)));
 }
Exemplo n.º 19
0
  @Override
  public Group createAdministrators(Context context, Community community)
      throws SQLException, AuthorizeException {
    // Check authorisation - Must be an Admin to create more Admins
    AuthorizeUtil.authorizeManageAdminGroup(context, community);

    Group admins = community.getAdministrators();
    if (admins == null) {
      // turn off authorization so that Community Admins can create Sub-Community Admins
      context.turnOffAuthorisationSystem();
      admins = groupService.create(context);
      context.restoreAuthSystemState();

      admins.setName(context, "COMMUNITY_" + community.getID() + "_ADMIN");
      groupService.update(context, admins);
    }

    authorizeService.addPolicy(context, community, Constants.ADMIN, admins);

    // register this as the admin group
    community.setAdmins(admins);
    return admins;
  }
Exemplo n.º 20
0
  /**
   * Internal method to remove the community and all its children from the database, and perform any
   * pre/post-cleanup
   *
   * @throws SQLException
   * @throws AuthorizeException
   * @throws IOException
   */
  protected void rawDelete(Context context, Community community)
      throws SQLException, AuthorizeException, IOException {
    log.info(
        LogManager.getHeader(context, "delete_community", "community_id=" + community.getID()));

    context.addEvent(
        new Event(
            Event.DELETE,
            Constants.COMMUNITY,
            community.getID(),
            community.getHandle(),
            getIdentifiers(context, community)));

    // Remove collections
    Iterator<Collection> collections = community.getCollections().iterator();

    while (collections.hasNext()) {
      Collection collection = collections.next();
      collections.remove();
      removeCollection(context, community, collection);
    }
    // delete subcommunities
    Iterator<Community> subCommunities = community.getSubcommunities().iterator();

    while (subCommunities.hasNext()) {
      Community subComm = subCommunities.next();
      subCommunities.remove();
      delete(context, subComm);
    }

    // Remove the logo
    setLogo(context, community, null);

    // Remove all authorization policies
    authorizeService.removeAllPolicies(context, community);

    // Remove any Handle
    handleService.unbindHandle(context, community);

    deleteMetadata(context, community);

    Group g = community.getAdministrators();

    // Delete community row
    communityDAO.delete(context, community);

    // Remove administrators group - must happen after deleting community

    if (g != null) {
      groupService.delete(context, g);
    }
  }
Exemplo n.º 21
0
 /**
  * Generic find for when the precise type of a DSO is not known, just the a pair of type number
  * and database ID.
  *
  * @param context - the context
  * @param type - type number
  * @param id - id within table of type'd objects
  * @return the object found, or null if it does not exist.
  * @throws SQLException only upon failure accessing the database.
  */
 public static DSpaceObject find(Context context, int type, int id) throws SQLException {
   switch (type) {
     case Constants.BITSTREAM:
       return Bitstream.find(context, id);
     case Constants.BUNDLE:
       return Bundle.find(context, id);
     case Constants.ITEM:
       return Item.find(context, id);
     case Constants.COLLECTION:
       return Collection.find(context, id);
     case Constants.COMMUNITY:
       return Community.find(context, id);
     case Constants.GROUP:
       return Group.find(context, id);
     case Constants.EPERSON:
       return EPerson.find(context, id);
     case Constants.SITE:
       return Site.find(context, id);
   }
   return null;
 }
Exemplo n.º 22
0
  @Override
  public Bitstream setLogo(Context context, Community community, InputStream is)
      throws AuthorizeException, IOException, SQLException {
    // Check authorisation
    // authorized to remove the logo when DELETE rights
    // authorized when canEdit
    if (!((is == null)
        && authorizeService.authorizeActionBoolean(context, community, Constants.DELETE))) {
      canEdit(context, community);
    }

    // First, delete any existing logo
    Bitstream oldLogo = community.getLogo();
    if (oldLogo != null) {
      log.info(LogManager.getHeader(context, "remove_logo", "community_id=" + community.getID()));
      community.setLogo(null);
      bitstreamService.delete(context, oldLogo);
    }

    if (is != null) {
      Bitstream newLogo = bitstreamService.create(context, is);
      community.setLogo(newLogo);

      // now create policy for logo bitstream
      // to match our READ policy
      List<ResourcePolicy> policies =
          authorizeService.getPoliciesActionFilter(context, community, Constants.READ);
      authorizeService.addPolicies(context, policies, newLogo);

      log.info(
          LogManager.getHeader(
              context,
              "set_logo",
              "community_id=" + community.getID() + "logo_bitstream_id=" + newLogo.getID()));
    }

    return community.getLogo();
  }
    private void addNodeTo(int node, Community to) {
      to.add(node);
      nodeCommunities[node] = to;

      for (Edge e : topology[node]) {
        int neighbor;
        neighbor = e.getTarget();

        // Remove Node Connection to this community
        Double neighEdgesTo = nodeConnectionsWeight[neighbor].get(to);
        if (neighEdgesTo == null) {
          nodeConnectionsWeight[neighbor].put(
              to, Double.parseDouble(e.getProperty("weight").toString()));
        } else {
          nodeConnectionsWeight[neighbor].put(
              to, neighEdgesTo + Double.parseDouble(e.getProperty("weight").toString()));
        }
        Integer neighCountEdgesTo = nodeConnectionsCount[neighbor].get(to);
        if (neighCountEdgesTo == null) {
          nodeConnectionsCount[neighbor].put(to, 1);
        } else {
          nodeConnectionsCount[neighbor].put(to, neighCountEdgesTo + 1);
        }

        Community adjCom = nodeCommunities[neighbor];
        Double wEdgesto = adjCom.connectionsWeight.get(to);
        if (wEdgesto == null) {
          adjCom.connectionsWeight.put(to, Double.parseDouble(e.getProperty("weight").toString()));
        } else {
          adjCom.connectionsWeight.put(
              to, wEdgesto + Double.parseDouble(e.getProperty("weight").toString()));
        }

        Integer cEdgesto = adjCom.connectionsCount.get(to);
        if (cEdgesto == null) {
          adjCom.connectionsCount.put(to, 1);
        } else {
          adjCom.connectionsCount.put(to, cEdgesto + 1);
        }

        Double nodeEdgesTo = nodeConnectionsWeight[node].get(adjCom);
        if (nodeEdgesTo == null) {
          nodeConnectionsWeight[node].put(
              adjCom, Double.parseDouble(e.getProperty("weight").toString()));
        } else {
          nodeConnectionsWeight[node].put(
              adjCom, nodeEdgesTo + Double.parseDouble(e.getProperty("weight").toString()));
        }

        Integer nodeCountEdgesTo = nodeConnectionsCount[node].get(adjCom);
        if (nodeCountEdgesTo == null) {
          nodeConnectionsCount[node].put(adjCom, 1);
        } else {
          nodeConnectionsCount[node].put(adjCom, nodeCountEdgesTo + 1);
        }

        if (to != adjCom) {
          Double comEdgesto = to.connectionsWeight.get(adjCom);
          if (comEdgesto == null) {
            to.connectionsWeight.put(
                adjCom, Double.parseDouble(e.getProperty("weight").toString()));
          } else {
            to.connectionsWeight.put(
                adjCom, comEdgesto + Double.parseDouble(e.getProperty("weight").toString()));
          }

          Integer comCountEdgesto = to.connectionsCount.get(adjCom);
          if (comCountEdgesto == null) {
            to.connectionsCount.put(adjCom, 1);
          } else {
            to.connectionsCount.put(adjCom, comCountEdgesto + 1);
          }
        }
      }
    }
Exemplo n.º 24
0
 public boolean equals(Community community) {
   if (id == community.getId()) {
     return true;
   }
   return false;
 }
  @RequestMapping("/my_configure")
  public ModelAndView my_configure() throws Exception {
    ModelAndView mav = new ModelAndView();
    User user = WebContextThreadLocal.getCurrentUser();
    if (user != null) {
      int role = user.getRole();
      HashMapReduce<Major, Course> hashMapReduce = new HashMapReduce<Major, Course>();
      String id = user.getId();
      user = this.userService.getUserByUserId(id);
      WebContextThreadLocal.setCurrentUser(user);
      Set<Course> courseSet = user.getCourses();
      HashMapReduce<String, Set<DoubanJson>> recommendBooks =
          new HashMapReduce<String, Set<DoubanJson>>();
      for (Course course : courseSet) {
        hashMapReduce.put(course.getMajor(), course);
        Set<DoubanJson> recommendBook = new HashSet<DoubanJson>();
        if (course.getDoubanJsons().size() == 0) {
          String str = null;
          if (course.getSearchKeyword() == null)
            str = this.academyService.wordAnalyzer(course.getName(), course);
          else {
            str = course.getSearchKeyword();
            String[] strs = str.split(" ");
            boolean first = true;
            for (int i = 0; i < strs.length; i++) {
              if (first) {
                String para = java.net.URLEncoder.encode(strs[i], "UTF-8");
                str = para;
                first = false;
              } else {
                String para = java.net.URLEncoder.encode(strs[i], "UTF-8");
                str = str + ',' + para;
              }
            }
          }
          // String str =
          // "https://api.douban.com/v2/book/search?apikey=00e256c12217228802a7044366456798&q="+course.getName();
          recommendBook = this.bookJsonService.getJsonString(str, course.getId());
        } else {
          recommendBook = course.getDoubanJsons();
        }
        recommendBooks.put(course.getName(), recommendBook);
      }
      // String str = this.academyService.wordAnalyzer("Java课程设计");

      List<Invite> inviteList = this.inviteService.getInviteByUserId();
      HashMap<String, List<DoubanJson>> bookList = new HashMap<String, List<DoubanJson>>();
      for (Invite invite : inviteList) {
        Course course = invite.getCourse();
        List<DoubanJson> bookInfos = this.bookJsonService.getBookByCourse(course.getId());
        bookList.put(course.getName(), bookInfos);
      }
      mav.getModel().put("bookList", bookList);

      mav.getModel().put("majorMap", hashMapReduce.getMap());

      // ArrayList<DoubanJson> recommendBooks = this.bookJsonService.getJsonString(str);
      mav.getModel().put("recommendBooks", recommendBooks.getMap());
      // unactiveCommunities对于老师指的是没有创建的社区,对于学生指的是没有加入,但已经存在的社区
      Set<Community> unactiveCommunities = new HashSet<Community>();
      if (role == 1) {
        unactiveCommunities = this.communityService.getAllCommunitiesByCurrentUserRole();
      } else if (role == 0) {
        for (Course course : courseSet) {
          Set<Community> communities = course.getCommunities();
          for (Community community : communities) {
            if (community.getState() == 1 && !user.getCommunities().contains(community)) {
              unactiveCommunities.add(community);
            }
          }
        }
      }
      mav.getModel().put("unactiveCommunities", unactiveCommunities);
      mav.getModel().put("invitedCommunities", this.inviteService.getInviteCommunities());
      if (role == 2) {
        Pager<Resource> pager = this.resourceOperationService.getReviewResource(1);
        mav.getModel().put("pager", pager);
        mav.getModel().put("htmlTag", 1);
        mav.setViewName("admin/reviewResource");
        return mav;
      }
    }

    mav.setViewName("user/myConfigure");
    return mav;
  }
    private void removeNodeFrom(int node, Community from) {

      Community community = nodeCommunities[node];
      for (Edge e : topology[node]) {
        int neighbor = e.getTarget();

        ////////
        // Remove Node Connection to this community
        Double edgesTo = nodeConnectionsWeight[neighbor].get(community);
        int countEdgesTo = nodeConnectionsCount[neighbor].get(community);
        if (countEdgesTo - 1 == 0) {
          nodeConnectionsWeight[neighbor].remove(community);
          nodeConnectionsCount[neighbor].remove(community);
        } else {
          nodeConnectionsWeight[neighbor].put(
              community, edgesTo - Double.parseDouble(e.getProperty("weight").toString()));
          nodeConnectionsCount[neighbor].put(community, countEdgesTo - 1);
        }

        ///////////////////
        // Remove Adjacency Community's connection to this community
        Community adjCom = nodeCommunities[neighbor];
        Double oEdgesto = adjCom.connectionsWeight.get(community);
        int oCountEdgesto = adjCom.connectionsCount.get(community);
        if (oCountEdgesto - 1 == 0) {
          adjCom.connectionsWeight.remove(community);
          adjCom.connectionsCount.remove(community);
        } else {
          adjCom.connectionsWeight.put(
              community, oEdgesto - Double.parseDouble(e.getProperty("weight").toString()));
          adjCom.connectionsCount.put(community, oCountEdgesto - 1);
        }

        if (node == neighbor) {
          continue;
        }

        if (adjCom != community) {
          Double comEdgesto = community.connectionsWeight.get(adjCom);
          Integer comCountEdgesto = community.connectionsCount.get(adjCom);
          if (comCountEdgesto - 1 == 0) {
            community.connectionsWeight.remove(adjCom);
            community.connectionsCount.remove(adjCom);
          } else {
            community.connectionsWeight.put(
                adjCom, comEdgesto - Double.parseDouble(e.getProperty("weight").toString()));
            community.connectionsCount.put(adjCom, comCountEdgesto - 1);
          }
        }

        Double nodeEgesTo = nodeConnectionsWeight[node].get(adjCom);
        Integer nodeCountEgesTo = nodeConnectionsCount[node].get(adjCom);
        if (nodeCountEgesTo - 1 == 0) {
          nodeConnectionsWeight[node].remove(adjCom);
          nodeConnectionsCount[node].remove(adjCom);
        } else {
          nodeConnectionsWeight[node].put(
              adjCom, nodeEgesTo - Double.parseDouble(e.getProperty("weight").toString()));
          nodeConnectionsCount[node].put(adjCom, nodeCountEgesTo - 1);
        }
      }
      from.remove(node);
    }
Exemplo n.º 27
0
  @Override
  public Community create(Community parent, Context context, String handle)
      throws SQLException, AuthorizeException {
    if (!(authorizeService.isAdmin(context)
        || (parent != null
            && authorizeService.authorizeActionBoolean(context, parent, Constants.ADD)))) {
      throw new AuthorizeException("Only administrators can create communities");
    }

    Community newCommunity = communityDAO.create(context, new Community());

    try {
      if (handle == null) {
        handleService.createHandle(context, newCommunity);
      } else {
        handleService.createHandle(context, newCommunity, handle);
      }
    } catch (IllegalStateException ie) {
      // If an IllegalStateException is thrown, then an existing object is already using this handle
      throw ie;
    }

    if (parent != null) {
      parent.addSubCommunity(newCommunity);
      newCommunity.addParentCommunity(parent);
    }

    // create the default authorization policy for communities
    // of 'anonymous' READ
    Group anonymousGroup = groupService.findByName(context, Group.ANONYMOUS);

    authorizeService.createResourcePolicy(
        context, newCommunity, anonymousGroup, null, Constants.READ, null);

    communityDAO.save(context, newCommunity);

    context.addEvent(
        new Event(
            Event.CREATE,
            Constants.COMMUNITY,
            newCommunity.getID(),
            newCommunity.getHandle(),
            getIdentifiers(context, newCommunity)));

    // if creating a top-level Community, simulate an ADD event at the Site.
    if (parent == null) {
      context.addEvent(
          new Event(
              Event.ADD,
              Constants.SITE,
              siteService.findSite(context).getID(),
              Constants.COMMUNITY,
              newCommunity.getID(),
              newCommunity.getHandle(),
              getIdentifiers(context, newCommunity)));
    }

    log.info(
        LogManager.getHeader(context, "create_community", "community_id=" + newCommunity.getID())
            + ",handle="
            + newCommunity.getHandle());

    return newCommunity;
  }
Exemplo n.º 28
0
  /**
   * Fills in the feed and entry-level metadata from DSpace objects.
   *
   * @param request request
   * @param context context
   * @param dso DSpaceObject
   * @param items array of objects
   * @param labels label map
   */
  public void populate(
      HttpServletRequest request,
      Context context,
      DSpaceObject dso,
      List<? extends DSpaceObject> items,
      Map<String, String> labels) {
    String logoURL = null;
    String objectURL = null;
    String defaultTitle = null;
    boolean podcastFeed = false;
    this.request = request;

    // dso is null for the whole site, or a search without scope
    if (dso == null) {
      defaultTitle = ConfigurationManager.getProperty("dspace.name");
      feed.setDescription(localize(labels, MSG_FEED_DESCRIPTION));
      objectURL = resolveURL(request, null);
      logoURL = ConfigurationManager.getProperty("webui.feed.logo.url");
    } else {
      Bitstream logo = null;
      if (dso.getType() == Constants.COLLECTION) {
        Collection col = (Collection) dso;
        defaultTitle = col.getName();
        feed.setDescription(collectionService.getMetadata(col, "short_description"));
        logo = col.getLogo();
        String cols = ConfigurationManager.getProperty("webui.feed.podcast.collections");
        if (cols != null && cols.length() > 1 && cols.contains(col.getHandle())) {
          podcastFeed = true;
        }
      } else if (dso.getType() == Constants.COMMUNITY) {
        Community comm = (Community) dso;
        defaultTitle = comm.getName();
        feed.setDescription(communityService.getMetadata(comm, "short_description"));
        logo = comm.getLogo();
        String comms = ConfigurationManager.getProperty("webui.feed.podcast.communities");
        if (comms != null && comms.length() > 1 && comms.contains(comm.getHandle())) {
          podcastFeed = true;
        }
      }
      objectURL = resolveURL(request, dso);
      if (logo != null) {
        logoURL = urlOfBitstream(request, logo);
      }
    }
    feed.setTitle(
        labels.containsKey(MSG_FEED_TITLE) ? localize(labels, MSG_FEED_TITLE) : defaultTitle);
    feed.setLink(objectURL);
    feed.setPublishedDate(new Date());
    feed.setUri(objectURL);

    // add logo if we found one:
    if (logoURL != null) {
      // we use the path to the logo for this, the logo itself cannot
      // be contained in the rdf. Not all RSS-viewers show this logo.
      SyndImage image = new SyndImageImpl();
      image.setLink(objectURL);
      if (StringUtils.isNotBlank(feed.getTitle())) {
        image.setTitle(feed.getTitle());
      } else {
        image.setTitle(localize(labels, MSG_LOGO_TITLE));
      }
      image.setUrl(logoURL);
      feed.setImage(image);
    }

    // add entries for items
    if (items != null) {
      List<SyndEntry> entries = new ArrayList<SyndEntry>();
      for (DSpaceObject itemDSO : items) {
        if (itemDSO.getType() != Constants.ITEM) {
          continue;
        }
        Item item = (Item) itemDSO;
        boolean hasDate = false;
        SyndEntry entry = new SyndEntryImpl();
        entries.add(entry);

        String entryURL = resolveURL(request, item);
        entry.setLink(entryURL);
        entry.setUri(entryURL);

        String title = getOneDC(item, titleField);
        entry.setTitle(title == null ? localize(labels, MSG_UNTITLED) : title);

        // "published" date -- should be dc.date.issued
        String pubDate = getOneDC(item, dateField);
        if (pubDate != null) {
          entry.setPublishedDate((new DCDate(pubDate)).toDate());
          hasDate = true;
        }
        // date of last change to Item
        entry.setUpdatedDate(item.getLastModified());

        StringBuffer db = new StringBuffer();
        for (String df : descriptionFields) {
          // Special Case: "(date)" in field name means render as date
          boolean isDate = df.indexOf("(date)") > 0;
          if (isDate) {
            df = df.replaceAll("\\(date\\)", "");
          }

          List<MetadataValue> dcv = itemService.getMetadataByMetadataString(item, df);
          if (dcv.size() > 0) {
            String fieldLabel = labels.get(MSG_METADATA + df);
            if (fieldLabel != null && fieldLabel.length() > 0) {
              db.append(fieldLabel).append(": ");
            }
            boolean first = true;
            for (MetadataValue v : dcv) {
              if (first) {
                first = false;
              } else {
                db.append("; ");
              }
              db.append(isDate ? new DCDate(v.getValue()).toString() : v.getValue());
            }
            db.append("\n");
          }
        }
        if (db.length() > 0) {
          SyndContent desc = new SyndContentImpl();
          desc.setType("text/plain");
          desc.setValue(db.toString());
          entry.setDescription(desc);
        }

        // This gets the authors into an ATOM feed
        List<MetadataValue> authors = itemService.getMetadataByMetadataString(item, authorField);
        if (authors.size() > 0) {
          List<SyndPerson> creators = new ArrayList<SyndPerson>();
          for (MetadataValue author : authors) {
            SyndPerson sp = new SyndPersonImpl();
            sp.setName(author.getValue());
            creators.add(sp);
          }
          entry.setAuthors(creators);
        }

        // only add DC module if any DC fields are configured
        if (dcCreatorField != null || dcDateField != null || dcDescriptionField != null) {
          DCModule dc = new DCModuleImpl();
          if (dcCreatorField != null) {
            List<MetadataValue> dcAuthors =
                itemService.getMetadataByMetadataString(item, dcCreatorField);
            if (dcAuthors.size() > 0) {
              List<String> creators = new ArrayList<String>();
              for (MetadataValue author : dcAuthors) {
                creators.add(author.getValue());
              }
              dc.setCreators(creators);
            }
          }
          if (dcDateField != null && !hasDate) {
            List<MetadataValue> v = itemService.getMetadataByMetadataString(item, dcDateField);
            if (v.size() > 0) {
              dc.setDate((new DCDate(v.get(0).getValue())).toDate());
            }
          }
          if (dcDescriptionField != null) {
            List<MetadataValue> v =
                itemService.getMetadataByMetadataString(item, dcDescriptionField);
            if (v.size() > 0) {
              StringBuffer descs = new StringBuffer();
              for (MetadataValue d : v) {
                if (descs.length() > 0) {
                  descs.append("\n\n");
                }
                descs.append(d.getValue());
              }
              dc.setDescription(descs.toString());
            }
          }
          entry.getModules().add(dc);
        }

        // iTunes Podcast Support - START
        if (podcastFeed) {
          // Add enclosure(s)
          List<SyndEnclosure> enclosures = new ArrayList();
          try {
            List<Bundle> bunds = itemService.getBundles(item, "ORIGINAL");
            if (bunds.get(0) != null) {
              List<Bitstream> bits = bunds.get(0).getBitstreams();
              for (Bitstream bit : bits) {
                String mime = bit.getFormat(context).getMIMEType();
                if (ArrayUtils.contains(podcastableMIMETypes, mime)) {
                  SyndEnclosure enc = new SyndEnclosureImpl();
                  enc.setType(bit.getFormat(context).getMIMEType());
                  enc.setLength(bit.getSize());
                  enc.setUrl(urlOfBitstream(request, bit));
                  enclosures.add(enc);
                } else {
                  continue;
                }
              }
            }
            // Also try to add an external value from dc.identifier.other
            // We are assuming that if this is set, then it is a media file
            List<MetadataValue> externalMedia =
                itemService.getMetadataByMetadataString(item, externalSourceField);
            if (externalMedia.size() > 0) {
              for (MetadataValue anExternalMedia : externalMedia) {
                SyndEnclosure enc = new SyndEnclosureImpl();
                enc.setType(
                    "audio/x-mpeg"); // We can't determine MIME of external file, so just picking
                                     // one.
                enc.setLength(1);
                enc.setUrl(anExternalMedia.getValue());
                enclosures.add(enc);
              }
            }

          } catch (Exception e) {
            System.out.println(e.getMessage());
          }
          entry.setEnclosures(enclosures);

          // Get iTunes specific fields: author, subtitle, summary, duration, keywords
          EntryInformation itunes = new EntryInformationImpl();

          String author = getOneDC(item, authorField);
          if (author != null && author.length() > 0) {
            itunes.setAuthor(author); // <itunes:author>
          }

          itunes.setSubtitle(
              title == null ? localize(labels, MSG_UNTITLED) : title); // <itunes:subtitle>

          if (db.length() > 0) {
            itunes.setSummary(db.toString()); // <itunes:summary>
          }

          String extent =
              getOneDC(
                  item,
                  "dc.format.extent"); // assumed that user will enter this field with length of
                                       // song in seconds
          if (extent != null && extent.length() > 0) {
            extent = extent.split(" ")[0];
            Integer duration = Integer.parseInt(extent);
            itunes.setDuration(new Duration(duration)); // <itunes:duration>
          }

          String subject = getOneDC(item, "dc.subject");
          if (subject != null && subject.length() > 0) {
            String[] subjects = new String[1];
            subjects[0] = subject;
            itunes.setKeywords(subjects); // <itunes:keywords>
          }

          entry.getModules().add(itunes);
        }
      }
      feed.setEntries(entries);
    }
  }