Package com.ikanow.infinit.e.data_model.api

Examples of com.ikanow.infinit.e.data_model.api.ResponsePojo


    // Note: Only Sys Admins, Community Owner, and Community Moderators can remove users
    boolean isOwnerOrModerator = SocialUtils.isOwnerOrModerator(communityIdStr, userIdStr);
    boolean isSysAdmin = RESTTools.adminLookup(userIdStr);
    boolean canRemove = (isOwnerOrModerator || isSysAdmin) ? true : false;
   
    ResponsePojo rp = new ResponsePojo();
   
    if (canRemove)
    {
      try
      {
        // Find person record to update
        BasicDBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(communityIdStr));
        DBObject dbo = DbManager.getSocial().getCommunity().findOne(query);

        if (dbo != null)
        {
          // Get GsonBuilder object with MongoDb de/serializers registered
          CommunityPojo community = CommunityPojo.fromDb(dbo, CommunityPojo.class);

          Boolean isMember = false;

          Set<CommunityMemberPojo> cmps = null;
          CommunityMemberPojo cmp = null;
          if (community.getMembers() != null)
          {
            cmps = community.getMembers();
            for (CommunityMemberPojo c : cmps)
            {
              if (c.get_id().toStringMongod().equals(personIdStr))
              {
                cmp = c;
                isMember = true;
              }
            }
          }

          if (isMember)
          {
            cmps.remove(cmp);

            community.setNumberOfMembers(community.getNumberOfMembers() - 1);

            /////////////////////////////////////////////////////////////////////////////////////////////////
            // TODO (INF-1214): Make this code more robust to handle changes to the community that need to
            // Caleb: this means change update to $set
            /////////////////////////////////////////////////////////////////////////////////////////////////         
            DbManager.getSocial().getCommunity().update(query, community.toDb());

            PersonHandler person = new PersonHandler();
            person.removeCommunity(personIdStr, communityIdStr);

            rp.setData(community, new CommunityPojoApiMap());
            rp.setResponse(new ResponseObject("Remove member from community", true, "Member has been removed from community"))
          }         
          else
          {
            rp.setResponse(new ResponseObject("Remove member from community",true,"Person is not a member of this community."))
          }
        }
        else
        {
          rp.setResponse(new ResponseObject("Remove member from community", false, "Community not found."));
        }
      }
      catch (Exception e)
      {     
        // If an exception occurs log the error
        logger.error("Exception Message: " + e.getMessage(), e);
        rp.setResponse(new ResponseObject("Remove member from community", false,
            "Error removing member from community " + e.getMessage()));
     
    }
    else
    {
      rp.setResponse(new ResponseObject("Remove member from community", false,
          "The user does not have permissions to remove a user from the community."));
    }
   
    return rp;
  }
View Full Code Here


   * @param shareIdStr
   * @return
   */
  public ResponsePojo getShare(String userIdStr, String shareIdStr, boolean returnContent)
  {
    ResponsePojo rp = new ResponsePojo();
   
    BasicDBObject query = new BasicDBObject("_id", new ObjectId(shareIdStr));
    HashSet<ObjectId> memberOf = null;
   
    if (!RESTTools.adminLookup(userIdStr)) { // (admins can see all shares)     
      memberOf = SocialUtils.getUserCommunities(userIdStr);
      if (null != memberOf) {
        query.put("communities._id", new BasicDBObject("$in", memberOf));
      }
      else { // (some error but we'll let this go if the share has no security)
        query.put("communities", new BasicDBObject("$exists", false));
      }
    }
   
    try
    {
      BasicDBObject dbo = (BasicDBObject)DbManager.getSocial().getShare().findOne(query);
      if (null != dbo) {
        byte[] bytes = (byte[]) dbo.remove("binaryData");
       
        SharePojo share = SharePojo.fromDb(dbo, SharePojo.class);
        share.setBinaryData(bytes);
       
        //new way of handling bytes, if has a binaryid, get bytes from there and set
 
        if (returnContent) {         
          if (null != share.getBinaryId()) {
            share.setBinaryData(getGridFile(share.getBinaryId()));           
          }//TESTED
          else if (null != share.getDocumentLocation()) {
            try {
              if ((null != share.getType()) && share.getType().equalsIgnoreCase("binary")) {
                File x = new File(share.getDocumentLocation().getCollection());
                share.setBinaryData(FileUtils.readFileToByteArray(x));
              }//TESTED
              else { // text
                share.setShare(getReferenceString(share));               
              }//TESTED
            }
            catch (Exception e) {
              rp.setResponse(new ResponseObject("Get Share", false, "Unable to get share reference: " + e.getMessage()));           
              return rp;
            }//TESTED
         
          // (else share.share already set)
        }
        else { // don't return content
          share.setShare(null);         
        }//TESTED
       
        rp.setData(share, new SharePojoApiMap(memberOf));               
        rp.setResponse(new ResponseObject("Share", true, "Share returned successfully"));
      }
      else {
        rp.setResponse(new ResponseObject("Get Share", false, "Unable to get share, not found or no access permission"));       
      }
    }
    catch (Exception e)
    {
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Get Share", false, "Unable to get share: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

 
  //TODO (): be able to specify not returning content?
 
  public ResponsePojo searchShares(String personIdStr, String searchby, String idStrList, String sharetypes, String skip, String limit, boolean ignoreAdmin, boolean returnContent, boolean searchParent)
  {
    ResponsePojo rp = new ResponsePojo();
   
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // Sample search queries
    // share/search/
    // share/search/?type=binary
    // share/search/?searchby=person&id=admin_infinite@ikanow.com
    // share/search/?searchby=community&id=4d88d0f1f9a624a4b0c8bd71,4d88d0f1f9a624a4b0c8bd72&type=dataset&skip=0&limit=10
    ///////////////////////////////////////////////////////////////////////////////////////////////
   
    // Create Query Object
    BasicDBObject query = new BasicDBObject();
   
    HashSet<ObjectId> memberOf = SocialUtils.getUserCommunities(personIdStr);
      // (need this to sanitize share communities even if searching explicitly by community)
   
    boolean bAdmin = false;
    if (!ignoreAdmin) {
      bAdmin = RESTTools.adminLookup(personIdStr);
    }
   
    // Community search, supports one or more communities._id values
    if ((searchby != null) && (searchby.equalsIgnoreCase("community") || searchby.equalsIgnoreCase("communities")))
    {
      query = getCommunityQueryObject(query, idStrList, personIdStr, ignoreAdmin, bAdmin, memberOf, searchParent);         
      //TESTED regex and list versions (single and multiple), no allowed commmunity versions
    }
    else if ((searchby != null) && searchby.equalsIgnoreCase("person"))
    {
      if ((ignoreAdmin || !bAdmin) || (null == idStrList)) { // not admin or no ids spec'd
       
        query.put("owner._id", new ObjectId(personIdStr));
      }//TESTED
      else { // admin and spec'd - can either be an array of ids or an array of email addresses
        memberOf = null; // (also returns all the communities in the mapper below)
       
        // List of communities to search on
        String[] idStrArray = idStrList.split(",");
        List<ObjectId> peopleIds = new ArrayList<ObjectId>();
        for (String idStr : idStrArray)
        {
          try {
            ObjectId id = new ObjectId(idStr);
            peopleIds.add(id);
          }
          catch (Exception e) { // Try as people's email addresses
            query.put("owner.email", new BasicDBObject("$in", idStrArray));
            peopleIds.clear();
            break;
          }//TESTED
        }
        if (peopleIds.size() > 0) {
          BasicDBObject communities = new BasicDBObject();
          communities.append("$in", peopleIds);
          query.put("owner._id", communities);
        }//TESTED
      }
      //TESTED: nobody, ids, emails
    }
    else { // Defaults to all communities to which a user belongs (or everything for admins)
     
      if (ignoreAdmin || !bAdmin) {     
        if (null != memberOf) {
          query.put("communities._id", new BasicDBObject("$in", memberOf));
        }
        else { // (some error but we'll let this go if the share has no security)
          query.put("communities", new BasicDBObject("$exists", false));
        }
      }
      else {
        memberOf = null; // (also returns all the communities in the mapper below)
      }
    }
   
    // Search on share type or types
    if (sharetypes != null && sharetypes.length() > 0)
    {
      if (sharetypes.split(",").length > 1)
      {
        BasicDBObject types = new BasicDBObject();
        String[] typeArray = sharetypes.split(",");
        types.append("$in", typeArray);
        query.put("type", types);
      }
      else
      {
        query.put("type", sharetypes);
      }
    }
   
    //REMOVING BINARY, if you want to return it you can't do deserialize on it
    BasicDBObject removeFields = new BasicDBObject("binaryData",false);
    if (!returnContent) {
      removeFields.put("share", false);
    }
   
    try
    {
      DBCursor dbc = null;
     
      // Attempt to parse skip and limit into ints if they aren't null
      int numToSkip = 0;
      int limitToNum = 0;
      if (skip != null) try { numToSkip = Integer.parseInt(skip); } catch (Exception e) {}
      if (limit != null) try { limitToNum = Integer.parseInt(limit); } catch (Exception e) {}
     
      // Run find query based on whether or not to skip and limit the number of results to return
      if (skip != null && limit != null)
      {
        dbc = (DBCursor)DbManager.getSocial().getShare().find(query,removeFields).skip(numToSkip).limit(limitToNum);
      }
      else if (skip != null && limit == null)
      {
        dbc = (DBCursor)DbManager.getSocial().getShare().find(query,removeFields).skip(numToSkip);
      }
      else if (skip == null && limit != null)
      {
        dbc = (DBCursor)DbManager.getSocial().getShare().find(query,removeFields).limit(limitToNum);
      }
      else
      {
        dbc = (DBCursor)DbManager.getSocial().getShare().find(query,removeFields);
      }
     
      List<SharePojo> shares = SharePojo.listFromDb(dbc, SharePojo.listType());
      if (!shares.isEmpty()) {
       
        Iterator<SharePojo> shareIt = shares.iterator();
        while (shareIt.hasNext()) {
          SharePojo share = shareIt.next();
          if (null != share.getDocumentLocation()) {
            try {
              if ((null == share.getType()) || !share.getType().equalsIgnoreCase("binary")) {
                // (ignore binary references)
                share.setShare(this.getReferenceString(share));
              }//TESTED
            }
            catch (Exception e) { // couldn't access data, just remove data from list
              share.setShare("{}");
            }
          }
        }//TESTED
       
        rp.setData(shares, new SharePojoApiMap(memberOf));
        rp.setResponse(new ResponseObject("Share", true, "Shares returned successfully"));       
      }
      else {
        rp.setResponse(new ResponseObject("Share", true, "No shares matching search critera found."));       
      }
    }
    catch (Exception e)
    {
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Share", false, "Unable to search for shares: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param bytes
   * @return
   */
  public ResponsePojo addBinary(String ownerIdStr, String type, String title, String description, String mediatype, byte[] bytes)
  {
    ResponsePojo rp = new ResponsePojo();   
    try
    {     
      // Create a new SharePojo object
      SharePojo share = new SharePojo();
      share.setCreated(new Date());
      share.setModified(new Date());
      share.setType(type);
      share.setTitle(title);
      share.setDescription(description);     
      HashSet<ObjectId> endorsedSet = new HashSet<ObjectId>();
      share.setEndorsed(endorsedSet); // (you're always endorsed within your personal community)
      endorsedSet.add(new ObjectId(ownerIdStr));       
      share.setMediaType(mediatype);
      ObjectId id = new ObjectId();
      share.set_id(id);
     
      // Get ShareOwnerPojo object and personal community
      PersonPojo owner = getPerson(new ObjectId(ownerIdStr));
      share.setOwner(getOwner(owner));
      share.setCommunities(getPersonalCommunity(owner));

      // Serialize the ID and Dates in the object to MongoDB format
      //Save the binary objects into separate db
      ObjectId gridid = saveGridFile(bytes);
      share.setBinaryId(gridid);
     
      // Save the document to the share collection
      DbManager.getSocial().getShare().save(share.toDb());
      rp.setResponse(new ResponseObject("Share", true, "New binary share added successfully. ID in data field"));
      rp.setData(id.toString(), null);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Share", false, "Unable to add share: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param bytes
   * @return
   */
  public ResponsePojo updateBinary(String ownerIdStr, String shareIdStr, String type, String title, String description, String mediatype, byte[] bytes)
  {
    ResponsePojo rp = new ResponsePojo();
    try
    {     
      //get old share
      BasicDBObject query = new BasicDBObject("_id",new ObjectId(shareIdStr));
      DBObject dboshare = DbManager.getSocial().getShare().findOne(query);
      if ( dboshare != null )
      {
        //write everything but binary
        dboshare.removeField("binaryData");
        SharePojo share = SharePojo.fromDb(dboshare, SharePojo.class);
        // Check ... am I the owner?
        ObjectId ownerId = new ObjectId(ownerIdStr);
        boolean bAdminOrModOfAllCommunities = RESTTools.adminLookup(ownerIdStr);
        if (!share.getOwner().get_id().equals(ownerId)) { // Then I have to be admin (except for one special case)
          if (!bAdminOrModOfAllCommunities) {
            // Special case: I am also community admin/moderator of every community to which this share belongs
            bAdminOrModOfAllCommunities = true;
            for (ShareCommunityPojo comm: share.getCommunities()) {
              if (!SocialUtils.isOwnerOrModerator(comm.get_id().toString(), ownerIdStr)) {
                bAdminOrModOfAllCommunities = false;
              }
            }//TESTED
           
            if (!bAdminOrModOfAllCommunities) {           
              rp.setResponse(new ResponseObject("Update Share",false,"Unable to update share: you are not owner or admin"));
              return rp;
            }
          }         
        }//end if not owner
       
        // Check: am I trying to update a reference or json?
        if (null == share.getBinaryId()) {
          rp.setResponse(new ResponseObject("Update Share",false,"Unable to update share: this is not a binary share"));
          return rp;         
        }

        if (!bAdminOrModOfAllCommunities) { // quick check whether I'm admin on-request - if so can endorse
          bAdminOrModOfAllCommunities = RESTTools.adminLookup(ownerIdStr, false);
        }//TESTED
       
        // Remove endorsements unless I'm admin (if I'm not admin I must be owner...)
        if (!bAdminOrModOfAllCommunities) { // Now need to check if I'm admin/mod/content publisher for each community..
          if (null == share.getEndorsed()) { // fill this with all allowed communities
            share.setEndorsed(new HashSet<ObjectId>());
            share.getEndorsed().add(share.getOwner().get_id()); // (will be added later)
            for (ShareCommunityPojo comm: share.getCommunities()) {
              if (SocialUtils.isOwnerOrModeratorOrContentPublisher(comm.get_id().toString(), ownerIdStr)) {
                share.getEndorsed().add(comm.get_id());
              }
            }
          }//TESTED
          else {
            for (ShareCommunityPojo comm: share.getCommunities()) {
              // (leave it as is except remove anything that I can't endorse)
              if (!SocialUtils.isOwnerOrModeratorOrContentPublisher(comm.get_id().toString(), ownerIdStr)) {
                share.getEndorsed().remove(comm.get_id());
              }         
            }
          }//TESTED 
        }//TESTED
        else {
          if (null == share.getEndorsed()) { // fill this with all communities
            share.setEndorsed(new HashSet<ObjectId>());
            share.getEndorsed().add(share.getOwner().get_id());
            for (ShareCommunityPojo comm: share.getCommunities()) {
              share.getEndorsed().add(comm.get_id());             
            }
          }
          //(else just leave with the same set of endorsements as before)
        }//TESTED
       
        share.setModified(new Date());
        share.setType(type);
        share.setTitle(title);
        share.setDescription(description);
        share.setMediaType(mediatype);
        share.setBinaryData(null);
        share.setBinaryId(updateGridFile(share.getBinaryId(), bytes));
       
        DbManager.getSocial().getShare().update(query, share.toDb());
       
        rp.setResponse(new ResponseObject("Update Share", true, "Binary share updated successfully"));
      }
      else
      {
        rp.setResponse(new ResponseObject("Update Share",false,"Shareid does not exist or you are not owner or admin"));
      }     
    }
    catch(Exception e)
    {
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Update Share", false, "Unable to update share: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param json
   * @return
   */
  public ResponsePojo saveJson(String ownerIdStr, String shareIdStr, String type, String title, String description, String json)
  {
    ResponsePojo rp = new ResponsePojo();
    try
    {
      SharePojo share = null;
      BasicDBObject dbo = null;
      BasicDBObject query = null;
     
      // Retrieve the share to update (if it exists)
      if (shareIdStr != null && ObjectId.isValid(shareIdStr))
      {
        query = new BasicDBObject();
        query.put("_id", new ObjectId(shareIdStr));
        dbo = (BasicDBObject)DbManager.getSocial().getShare().findOne(query);
      }
      else
      {
        shareIdStr = new ObjectId().toString();
      }
     
      // Update existing share
      if (dbo != null)
      {
        // 1a) if I'm the owner then GOTO_UPDATE
        // 1b) if I'm the admin/mod
        // (NEW) if I am a content publisher for all communities for which this share is read/write
       
        share = SharePojo.fromDb(dbo, SharePojo.class);
        // Check ... am I the owner?
        ObjectId ownerId = new ObjectId(ownerIdStr);
        boolean bAdminOrModOfAllCommunities = RESTTools.adminLookup(ownerIdStr);
       
        if (!share.getOwner().get_id().equals(ownerId)) { // Then I have to be admin (except for one special case)
          if (!bAdminOrModOfAllCommunities) {
            // Special case #1: I am also community admin/moderator of every community to which this share belongs
            bAdminOrModOfAllCommunities = true;
            for (ShareCommunityPojo comm: share.getCommunities()) {
              if (!SocialUtils.isOwnerOrModerator(comm.get_id().toString(), ownerIdStr)) {
                bAdminOrModOfAllCommunities = false;
              }
            }//TESTED
           
            if (!bAdminOrModOfAllCommunities) {
              // Special case #2: I am a admin/mod/content publisher of *any* community that is read/write
              boolean readWriteCase = false;
              if (null != share.getReadWrite()) {
                // I need to be content publisher across all shares
                for (ObjectId readWriteCommId: share.getReadWrite()) {
                  if (SocialUtils.isOwnerOrModeratorOrContentPublisher(readWriteCommId.toString(), ownerIdStr)) {
                    readWriteCase = true;
                    break;
                  }                 
                }
              }//TESTED
             
              if (!readWriteCase) {
                rp.setResponse(new ResponseObject("Update Share",false,"Unable to update share: you are not owner or admin"));
                return rp;
              }
            }
          }         
        }//end if not owner
       
        // Check: am I trying to update a reference or binary?
        if ((null != share.getDocumentLocation()) || (null != share.getBinaryId())) {
          rp.setResponse(new ResponseObject("Update Share",false,"Unable to update share: this is not a JSON share"));
          return rp;         
        }
       
        if (!bAdminOrModOfAllCommunities) { // quick check whether I'm admin on-request - if so can endorse
          bAdminOrModOfAllCommunities = RESTTools.adminLookup(ownerIdStr, false);
        }//TESTED
               
        // Remove endorsements unless I'm admin (if I'm not admin I must be owner...)
        if (!bAdminOrModOfAllCommunities) { // Now need to check if I'm admin/mod/content publisher for each community..
          if (null == share.getEndorsed()) { // fill this with all allowed communities
            share.setEndorsed(new HashSet<ObjectId>());
            share.getEndorsed().add(share.getOwner().get_id()); // (will be added later)
            for (ShareCommunityPojo comm: share.getCommunities()) {
              if (SocialUtils.isOwnerOrModeratorOrContentPublisher(comm.get_id().toString(), ownerIdStr)) {
                share.getEndorsed().add(comm.get_id());
              }
            }
          }//TESTED
          else {
            for (ShareCommunityPojo comm: share.getCommunities()) {
              // (leave it as is except remove anything that I can't endorse)
              if (!SocialUtils.isOwnerOrModeratorOrContentPublisher(comm.get_id().toString(), ownerIdStr)) {
                share.getEndorsed().remove(comm.get_id());
              }         
            }
          }//TESTED 
        }//TESTED
        else {
          if (null == share.getEndorsed()) { // fill this with all communities
            share.setEndorsed(new HashSet<ObjectId>());
            share.getEndorsed().add(share.getOwner().get_id());
            for (ShareCommunityPojo comm: share.getCommunities()) {
              share.getEndorsed().add(comm.get_id());             
            }
          }
          //(else just leave with the same set of endorsements as before)
        }//TESTED
       
        share.setModified(new Date());
        share.setType(type);
        share.setTitle(title);
        share.setDescription(description);
        share.setShare(json);
       
        // Save the document to the share collection
        DbManager.getSocial().getShare().update(query, share.toDb());
        rp.setData(share, new SharePojoApiMap(null));
        rp.setResponse(new ResponseObject("Share", true, "Share updated successfully."));
      }
      // Create new share
      else
      {
        // Create a new SharePojo object
        share = new SharePojo();
        share.set_id(new ObjectId(shareIdStr));
        share.setCreated(new Date());
        share.setModified(new Date());
        share.setType(type);
        share.setTitle(title);
        share.setDescription(description);
        share.setShare(json);
       
        HashSet<ObjectId> endorsedSet = new HashSet<ObjectId>();
        share.setEndorsed(endorsedSet); // (you're always endorsed within your own community)
        endorsedSet.add(new ObjectId(ownerIdStr));       
       
        // Get ShareOwnerPojo object and personal community
        PersonPojo owner = getPerson(new ObjectId(ownerIdStr));
        share.setOwner(getOwner(owner));
        share.setCommunities(getPersonalCommunity(owner));

        // Serialize the ID and Dates in the object to MongoDB format
        // Save the document to the share collection
        DbManager.getSocial().getShare().save(share.toDb());
        rp.setData(share, new SharePojoApiMap(null));
        rp.setResponse(new ResponseObject("Share", true, "New share added successfully."));
      }
    }
    catch (Exception e)
    {
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Share", false, "Unable to update share: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param description
   * @return
   */
  public ResponsePojo addRef(String ownerIdStr, String type, String location, String idStr, String title, String description)
  {
    ResponsePojo rp = new ResponsePojo();
    try
    {
      ObjectId shareId = new ObjectId();

      // Create a new SharePojo object
      SharePojo share = new SharePojo();
      share.set_id(shareId);
      share.setType(type);
      share.setTitle(title);
      share.setDescription(description);
      share.setCreated(new Date());
      share.setModified(new Date());
     
      // Create DocumentLocationPojo and add to the share
      DocumentLocationPojo documentLocation = new DocumentLocationPojo();
      setRefLocation(location, documentLocation);
      share.setDocumentLocation(documentLocation);
      if (null == documentLocation.getDatabase()) { // (local file)
        // Check, need to be admin:
        if (!RESTTools.adminLookup(ownerIdStr, false)) {
          rp.setResponse(new ResponseObject("Share", false, "Permission denied: you need to be admin to create a local file ref"));
          return rp;
        }       
        if ((null != type) && (type.equalsIgnoreCase("binary") || type.startsWith("binary:"))) {
          String[] binaryType = type.split(":", 2);
          if (binaryType.length > 1) {
            share.setMediaType(binaryType[1]);
            share.setType("binary");
          }
          else {
            share.setMediaType(MimeUtils.getMimeType(FilenameUtils.getExtension(idStr)));
          }
        }
        documentLocation.setCollection(idStr); // collection==file, database==id==null
      }//TESTED
      else {
        documentLocation.set_id(new ObjectId(idStr));       
      }
     
      // Get ShareOwnerPojo object
      PersonPojo owner = getPerson(new ObjectId(ownerIdStr));
      share.setOwner(getOwner(owner));
     
      // Endorsements:
      HashSet<ObjectId> endorsedSet = new HashSet<ObjectId>();
      share.setEndorsed(endorsedSet); // (you're always endorsed within your own community)
      endorsedSet.add(new ObjectId(ownerIdStr));       

      // Set Personal Community
      share.setCommunities(getPersonalCommunity(owner));

      // Serialize the ID and Dates in the object to MongoDB format
      // Save the document to the share collection
      DbManager.getSocial().getShare().save(share.toDb());
      rp.setResponse(new ResponseObject("Share", true, "New share added successfully. ID in data field."));
      rp.setData(share.get_id().toString(), null);
    }
    catch (Exception e)
    {
      //logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Share", false, "Unable to add new share: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

  }
 
 
  public ResponsePojo updateRef(String ownerIdStr, String shareIdStr, String type, String location, String idStr, String title, String description)
  {
    ResponsePojo rp = new ResponsePojo();
    try
    {
      // Get Share Object from Collection
      BasicDBObject query = new BasicDBObject();
      query.put("_id", new ObjectId(shareIdStr));

      BasicDBObject dbo = (BasicDBObject)DbManager.getSocial().getShare().findOne(query);
      if (dbo != null)
      {
        SharePojo share = SharePojo.fromDb(dbo, SharePojo.class);
       
        // Check ... am I the owner?
        ObjectId ownerId = new ObjectId(ownerIdStr);
        boolean bAdminOrModOfAllCommunities = RESTTools.adminLookup(ownerIdStr);
        if (!share.getOwner().get_id().equals(ownerId)) { // Then I have to be admin (except for one special case)
          if (!bAdminOrModOfAllCommunities) {
            // Special case: I am also community admin/moderator of every community to which this share belongs
            bAdminOrModOfAllCommunities = true;
            for (ShareCommunityPojo comm: share.getCommunities()) {
              if (!SocialUtils.isOwnerOrModerator(comm.get_id().toString(), ownerIdStr)) {
                bAdminOrModOfAllCommunities = false;
              }
            }//TESTED
           
            if (!bAdminOrModOfAllCommunities) {           
              rp.setResponse(new ResponseObject("Update Share",false,"Unable to update share: you are not owner or admin"));
              return rp;
            }
          }         
        }//end if not owner
       
        // Check: am I trying to update a reference or json?
        if (null == share.getDocumentLocation()) {
          rp.setResponse(new ResponseObject("Update Share",false,"Unable to update share: this is not a reference share"));
          return rp;         
        }
       
        if (!bAdminOrModOfAllCommunities) { // quick check whether I'm admin on-request - if so can endorse
          bAdminOrModOfAllCommunities = RESTTools.adminLookup(ownerIdStr, false);
        }//TESTED
               
        // Remove endorsements unless I'm admin (if I'm not admin I must be owner...)
        if (!bAdminOrModOfAllCommunities) { // Now need to check if I'm admin/mod/content publisher for each community..
          if (null == share.getEndorsed()) { // fill this with all allowed communities
            share.setEndorsed(new HashSet<ObjectId>());
            share.getEndorsed().add(share.getOwner().get_id()); // (will be added later)
            for (ShareCommunityPojo comm: share.getCommunities()) {
              if (SocialUtils.isOwnerOrModeratorOrContentPublisher(comm.get_id().toString(), ownerIdStr)) {
                share.getEndorsed().add(comm.get_id());
              }
            }
          }//TESTED
          else {
            for (ShareCommunityPojo comm: share.getCommunities()) {
              // (leave it as is except remove anything that I can't endorse)
              if (!SocialUtils.isOwnerOrModeratorOrContentPublisher(comm.get_id().toString(), ownerIdStr)) {
                share.getEndorsed().remove(comm.get_id());
              }         
            }
          }//TESTED 
        }//TESTED
        else {
          if (null == share.getEndorsed()) { // fill this with all communities
            share.setEndorsed(new HashSet<ObjectId>());
            share.getEndorsed().add(share.getOwner().get_id());
            for (ShareCommunityPojo comm: share.getCommunities()) {
              share.getEndorsed().add(comm.get_id());             
            }
          }
          //(else just leave with the same set of endorsements as before)
        }//TESTED
       
        share.setType(type);
        share.setTitle(title);
        share.setDescription(description);
        share.setModified(new Date());

        // Create DocumentLocationPojo and add to the share
        DocumentLocationPojo documentLocation = new DocumentLocationPojo();
        setRefLocation(location, documentLocation);
        share.setDocumentLocation(documentLocation);
        if (null == documentLocation.getDatabase()) { // (local file)
          // Check, need to be admin:
          if (!RESTTools.adminLookup(ownerIdStr, false)) {
            rp.setResponse(new ResponseObject("Share", false, "Permission denied: you need to be admin to update a local file ref"));
            return rp;
          }       
          if ((null != type) && (type.equalsIgnoreCase("binary") || type.startsWith("binary:"))) {
            String[] binaryType = type.split(":", 2);
            if (binaryType.length > 1) {
              share.setMediaType(binaryType[1]);
              share.setType("binary");
            }
            else {
              share.setMediaType(MimeUtils.getMimeType(FilenameUtils.getExtension(idStr)));
            }
          }
          documentLocation.setCollection(idStr); // collection==file, database==id==null
        }//TESTED
        else {
          documentLocation.set_id(new ObjectId(idStr));       
        }

        // Get ShareOwnerPojo object
        PersonPojo owner = getPerson(new ObjectId(ownerIdStr));
        share.setOwner(getOwner(owner));

        // Set Personal Community
        share.setCommunities(getPersonalCommunity(owner));

        // Serialize the ID and Dates in the object to MongoDB format
        // Save the document to the share collection
        DbManager.getSocial().getShare().update(query, share.toDb());
        rp.setResponse(new ResponseObject("Share", true, "Share updated successfully."));
      }
      else
      {
        rp.setResponse(new ResponseObject("Share", false, "Unable to update share: only the owner of the share or admin can update it."));
        return rp;
      }
    }
    catch (Exception e)
    {
      //logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Share", false, "Unable to update share: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param shareIdStr
   * @return
   */
  public ResponsePojo endorseShare(String personIdStr, String communityIdStr, String shareIdStr, boolean isEndorsed)
  {
    ResponsePojo rp = new ResponsePojo();
    try
    {
      communityIdStr = allowCommunityRegex(personIdStr, communityIdStr);
      ObjectId communityId = new ObjectId(communityIdStr);

      // Do I have permission to do any endorsing?
      // I can be:
      // Admin (or admin on request, regardless of enabled state)
      // Community owner
      // Community moderator
      boolean bAdmin = RESTTools.adminLookup(personIdStr, false);
      if (!bAdmin) {
        if (!SocialUtils.isOwnerOrModeratorOrContentPublisher(communityIdStr, personIdStr))  { 
          rp.setResponse(new ResponseObject("Share", false, "Unable to endorse share: insufficient permissions"));
          return rp;
        }
      }//TESTED
     
      // Now check if the share is even in our community...
      BasicDBObject query = new BasicDBObject(SharePojo._id_, new ObjectId(shareIdStr));
      query.put(ShareCommunityPojo.shareQuery_id_, communityId);
      BasicDBObject fields = new BasicDBObject(ShareOwnerPojo.shareQuery_id_, 1);
      fields.put(SharePojo.endorsed_, 1);
      BasicDBObject shareObj = (BasicDBObject) DbManager.getSocial().getShare().findOne(query, fields);
      SharePojo shareToEndorse = SharePojo.fromDb(shareObj, SharePojo.class);
      if (null == shareToEndorse) {
        rp.setResponse(new ResponseObject("Share", false, "Failed to locate share in community: " + shareIdStr + " vs " + communityIdStr));       
        return rp;
      }//TESTED
      // If we've got this far we're good to go
      BasicDBObject update = null;
      if ((null == shareToEndorse.getEndorsed()) && (null != shareToEndorse.getOwner())) {
        //Legacy case: create the owner's personal community in there
        update = new BasicDBObject(DbManager.addToSet_, new BasicDBObject(SharePojo.endorsed_, shareToEndorse.getOwner().get_id()));
        DbManager.getSocial().getShare().update(query, update, false, true);
      }//TESTED
      if (isEndorsed) {
        update = new BasicDBObject(DbManager.addToSet_, new BasicDBObject(SharePojo.endorsed_, communityId));
      }//TESTED
      else {
        update = new BasicDBObject(DbManager.pull_, new BasicDBObject(SharePojo.endorsed_, communityId));       
      }//TESTED
      DbManager.getSocial().getShare().update(query, update, false, true);
      rp.setResponse(new ResponseObject("Share", true, "Share endorsed successfully."));
    }
    catch (Exception e)
    {
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Share", false, "Unable to endorse share: " + e.getMessage()));
    }
    return rp;
  }//TESTED
View Full Code Here

   * @param shareIdStr
   * @return
   */
  public ResponsePojo removeShare(String ownerIdStr, String shareIdStr)
  {
    ResponsePojo rp = new ResponsePojo();
    // Query = share._id and share.shareOwner._id (unless admin)
    BasicDBObject query = new BasicDBObject();
    query.put("_id", new ObjectId(shareIdStr));
    mustBeOwnerOrAdmin(ownerIdStr, query);
   
    try
    {
      //first we must get the share to see if we need to remove the binary portion
      SharePojo sp = SharePojo.fromDb(DbManager.getSocial().getShare().findOne(query),SharePojo.class);     
      WriteResult wr = DbManager.getSocial().getShare().remove(query);
      if (wr.getN() ==  1)
      {
        //if remvoe was successful, attempt to remove the gridfs entry
        if ( sp.getBinaryId() != null )
        {
          //remove gridfs
          DbManager.getSocial().getShareBinary().remove(sp.getBinaryId());
        }
        rp.setResponse(new ResponseObject("Share", true, "Share removed from database successfully"));
      }
      else
      {
        rp.setResponse(new ResponseObject("Share", false, "Unable to remove share from database successfully (reason: share does not exist or user does not own the share)."));
      }
    }
    catch (Exception e)
    {
      logger.error("Exception Message: " + e.getMessage(), e);
      rp.setResponse(new ResponseObject("Share", false, "Unable to remove share: " + e.getMessage()));
    }
    return rp;
  }
View Full Code Here

TOP

Related Classes of com.ikanow.infinit.e.data_model.api.ResponsePojo

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.