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

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


      url.append(URLEncoder.encode(searchterm,"UTF-8"));
      url.append("/");     
      url.append(URLEncoder.encode(communityIdStr,"UTF-8"));
     
      String json = sendRequest(url.toString(), null);
      ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
      ResponseObject internal_ro = internal_responsePojo.getResponse();
      response = shallowCopy(response, internal_ro);
     
      return new Gson().fromJson((JsonElement)internal_responsePojo.getData(), DimensionListPojo.class);   
    }
    catch (Exception e)
    {
      response.setSuccess(false);
      response.setMessage(e.getMessage());
View Full Code Here


      url.append(URLEncoder.encode(searchterm,"UTF-8"));
      url.append("/");     
      url.append(URLEncoder.encode(communityIdStr,"UTF-8"));
     
      String json = sendRequest(url.toString(), null);
      ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
      ResponseObject internal_ro = internal_responsePojo.getResponse();
      response = shallowCopy(response, internal_ro);
     
      locations = ApiManager.mapListFromApi((JsonElement)internal_responsePojo.getData(), SearchSuggestPojo.listType(), null);     
    }
    catch (Exception e)
    {
      response.setSuccess(false);
      response.setMessage(e.getMessage());
View Full Code Here

      //DEBUG
      //System.out.println("COMMS="+communityIdStrList.toString() + ": QUERY=" + query.toApi());
     
      // (should have a version of this that just returns the IPs from the index engine)
      // (for now this will do)
      ResponsePojo rp = queryHandler.doQuery(savedQuery._parentShare.getOwner().get_id().toString(),
          query, communityIdStrList.toString(), errorString);
     
      if (null == rp) {
        throw new RuntimeException(errorString.toString()); // (handled below)
      }
     
      // 4) Add the results to the original data
     
      SharePojo savedQueryShare = SharePojo.fromDb(DbManager.getSocial().getShare().findOne(
          new BasicDBObject(SharePojo._id_, savedQuery._parentShare.get_id())), SharePojo.class);
     
      if (null != savedQueryShare) {
        DocumentQueueControlPojo toModify = DocumentQueueControlPojo.fromApi(savedQueryShare.getShare(), DocumentQueueControlPojo.class);
        List<BasicDBObject> docs = (List<BasicDBObject>) rp.getData();
        if ((null != docs) && !docs.isEmpty()) {
          if (null == toModify.getQueueList()) {
            toModify.setQueueList(new ArrayList<ObjectId>(docs.size()));
          }
          ObjectId ignoreBeforeId = toModify.getLastDocIdInserted();
View Full Code Here

   
    QueryHandler queryHandler = new QueryHandler();
   
    // Create query object
   
    ResponsePojo rp = null;
    StringBuffer errorString = new StringBuffer("Saved query error");
    try
    {
      String queryString = InfiniteHadoopUtils.getQueryOrProcessing(savedQuery.query, InfiniteHadoopUtils.QuerySpec.QUERY);     
      AdvancedQueryPojo query = QueryHandler.createQueryPojo(queryString);
      StringBuffer communityIdStrList = new StringBuffer();
      for (ObjectId commId: savedQuery.communityIds)
      {
        if (communityIdStrList.length() > 0)
        {
          communityIdStrList.append(',');
        }
        communityIdStrList.append(commId.toString());
      }
      rp = queryHandler.doQuery(savedQuery.submitterID.toString(), query, communityIdStrList.toString(), errorString);
    }
    catch (Exception e)
    {
      //DEBUG
      e.printStackTrace();
      errorString.append(": " + e.getMessage());
    }
    if ((null == rp) || (null == rp.getResponse())) { // (this is likely some sort of internal error)
      if (null == rp)
      {
        rp = new ResponsePojo();
      }
      rp.setResponse(new ResponseObject("Query", false, "Unknown error"));
    }
    if (!rp.getResponse().isSuccess()) {
      rp.getResponse().setMessage(errorString.append('/').append(rp.getResponse().getMessage()).toString());
      return rp;
    }
 
    return rp;
  }
View Full Code Here

    {
      CustomOutputManager.prepareOutputCollection(job);

      // This may be a saved query, if so handle that separately
      if (null == job.jarURL) {
        ResponsePojo rp = new CustomSavedQueryTaskLauncher().runSavedQuery(job);
        if (!rp.getResponse().isSuccess()) {
          _statusManager.setJobComplete(job, true, true, -1, -1, rp.getResponse().getMessage());
        }
        else { // Success, write to output
          try {   
            // Write to the temp output collection:
         
            String outCollection = job.outputCollectionTemp;
            if ((job.appendResults != true) && job.appendResults)
              outCollection = job.outputCollection;
            //TESTED
           
            DBCollection dbTemp =  DbManager.getCollection(job.getOutputDatabase(), outCollection);
            BasicDBObject outObj = new BasicDBObject();
            outObj.put("key", new Date());
            outObj.put("value", com.mongodb.util.JSON.parse(BaseDbPojo.getDefaultBuilder().create().toJson(rp)));
            dbTemp.save(outObj);
           
            _statusManager.setJobComplete(job, true, false, 1, 1, ApiManager.mapToApi(rp.getStats(), null));         
            job.jobidS = null;
          }
          catch (Exception e) { // Any sort of error, just make sure we set the job to complete     
            _statusManager.setJobComplete(job, true, true, 1, 1, e.getMessage());
            job.jobidS = null;
View Full Code Here

   * leaveCommunity (REST)
   */
 
  public ResponsePojo leaveCommunity(String personIdStr, String communityIdStr)
  {
    ResponsePojo rp = new ResponsePojo();
    try
    {
      communityIdStr = allowCommunityRegex(personIdStr, communityIdStr);
      BasicDBObject query = new BasicDBObject("_id",new ObjectId(communityIdStr));
      DBObject dboComm = DbManager.getSocial().getCommunity().findOne(query);
      if ( dboComm != null )
      {
        CommunityPojo cp = CommunityPojo.fromDb(dboComm, CommunityPojo.class);
        if ( !cp.getIsPersonalCommunity())
        {
          BasicDBObject queryPerson = new BasicDBObject("_id",new ObjectId(personIdStr));
          DBObject dboPerson = DbManager.getSocial().getPerson().findOne(queryPerson);
          PersonPojo pp = PersonPojo.fromDb(dboPerson,PersonPojo.class);
          cp.removeMember(new ObjectId(personIdStr));
          pp.removeCommunity(cp);         
          //write both objects back to db now
          /////////////////////////////////////////////////////////////////////////////////////////////////
          // 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, cp.toDb());
          DbManager.getSocial().getPerson().update(queryPerson, pp.toDb());
          rp.setResponse(new ResponseObject("Leave Community",true,"Left community successfully"));
        }
        else
        {
          rp.setResponse(new ResponseObject("Leave Community",false,"Cannot leave personal community"));
        }
      }
      else
      {
        rp.setResponse(new ResponseObject("Leave Community",false,"Community does not exist"));
      }
    }
    catch(Exception ex)
    {
      rp.setResponse(new ResponseObject("Leave Community",false,"General Error, bad params maybe? " + ex.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param communityIdStr
   * @return
   */
  public ResponsePojo inviteCommunity(String userIdStr, String personIdStr, String communityIdStr, String skipInvitation)
  {
    ResponsePojo rp = new ResponsePojo();
    try {
      communityIdStr = allowCommunityRegex(userIdStr, communityIdStr);
    }
    catch (Exception e) {
      rp.setResponse(new ResponseObject("Invite Community", false, "Error returning community info: " + e.getMessage()));
      return rp;
    }
   
    boolean skipInvite = ((null != skipInvitation) && (skipInvitation.equalsIgnoreCase("true"))) ? true : false;
   
    /////////////////////////////////////////////////////////////////////////////////////////////////
    // Note: Only Sys Admins, Community Owner, and Community Moderators can invite users to
    // private communities however any member can be able to invite someone to a public community
    boolean isOwnerOrModerator = SocialUtils.isOwnerOrModerator(communityIdStr, userIdStr);
    boolean isSysAdmin = RESTTools.adminLookup(userIdStr);
    boolean canInvite = (isOwnerOrModerator || isSysAdmin) ? true : false;

    try
    {
      BasicDBObject query = new BasicDBObject("_id",new ObjectId(communityIdStr));
      DBObject dboComm = DbManager.getSocial().getCommunity().findOne(query);
     
      if ( dboComm != null )
      {
        CommunityPojo cp = CommunityPojo.fromDb(dboComm, CommunityPojo.class);
       
        // Make sure this isn't a personal community
        if ( !cp.getIsPersonalCommunity() )
        {
          // Check to see if the user has permissions to invite or selfregister
          boolean selfRegister = canSelfRegister(cp);
          if ( canInvite || cp.getOwnerId().toString().equalsIgnoreCase(userIdStr) || selfRegister )
          {
            BasicDBObject dboPerson = (BasicDBObject) DbManager.getSocial().getPerson().findOne(new BasicDBObject("email", personIdStr));
            if (null == dboPerson) { // (ie personId isn't an email address... convert to ObjectId and try again)
              dboPerson = (BasicDBObject) DbManager.getSocial().getPerson().findOne(new BasicDBObject("_id", new ObjectId(personIdStr)));
            }
            else {
              personIdStr = dboPerson.getString("_id");
            }
            // OK from here on, personId is the object Id...
           
            if ( dboPerson != null )
            {
              PersonPojo pp = PersonPojo.fromDb(dboPerson,PersonPojo.class);             
              //need to check for if a person is pending, and skipInvite and isSysAdmin, otherwise
              //they would just get sent an email again, so leave it be
              boolean isPending = false;
              if ( isSysAdmin && skipInvite )
              {
                isPending = isMemberPending(cp, pp);
              }
             
              if ( selfRegister )
              {
                //If the comm allows for self registering, just call join community
                //instead of invite, it will handle registration
                return this.joinCommunity(pp.get_id().toString(), communityIdStr, isSysAdmin);
              }
              else if ( !cp.isMember(pp.get_id()) || isPending )
              {
                if (isSysAdmin && skipInvite) // Can only skip invite if user is Admin
                {
                  // Update community with new member
                  cp.addMember(pp, false); // Member status set to Active
                  cp.setNumberOfMembers(cp.getNumberOfMembers() + 1); // Increment number of members
                  /////////////////////////////////////////////////////////////////////////////////////////////////
                  // 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, cp.toDb());
                 
                  // Add community to persons object and save to db
                  pp.addCommunity(cp);
                  /////////////////////////////////////////////////////////////////////////////////////////////////
                  // 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().getPerson().update(new BasicDBObject("_id", pp.get_id()), pp.toDb());
                 
                  rp.setResponse(new ResponseObject("Invite Community",true,"User added to community successfully."));
                }
                else
                {
                  cp.addMember(pp, true); // Member status set to Pending
                  /////////////////////////////////////////////////////////////////////////////////////////////////
                  // 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, cp.toDb());
                 
                  //send email out inviting user
                  CommunityApprovePojo cap = cp.createCommunityApprove(personIdStr,communityIdStr,"invite",userIdStr);
                  DbManager.getSocial().getCommunityApprove().insert(cap.toDb());
                 
                  PropertiesManager propManager = new PropertiesManager();
                  String rootUrl = propManager.getUrlRoot();
                 
                  if (null == rootUrl) {
                    rp.setResponse(new ResponseObject("Invite Community",false,"The system was unable to email the invite because an invite was required and root.url is not set up."));
                    return rp;
                  }
                 
                  String subject = "Invite to join infinit.e community: " + cp.getName();
                  String body = "You have been invited to join the community " + cp.getName() +
                    "<br/><a href=\"" + rootUrl + "social/community/requestresponse/"+cap.get_id().toString() + "/true\">Accept</a> " +
                    "<a href=\"" + rootUrl + "social/community/requestresponse/"+cap.get_id().toString() + "/false\">Deny</a>";
                 
                  SendMail mail = new SendMail(new PropertiesManager().getAdminEmailAddress(), pp.getEmail(), subject, body);
                 
                  if (mail.send("text/html"))
                  {
                    if (isSysAdmin) {
                      rp.setResponse(new ResponseObject("Invite Community",true,"Invited user to community successfully: " + cap.get_id().toString()));
                    }
                    else {
                      rp.setResponse(new ResponseObject("Invite Community",true,"Invited user to community successfully"));                 
                    }
                  }
                  else
                  {
                    rp.setResponse(new ResponseObject("Invite Community",false,"The system was unable to email the invite for an unknown reason (eg an invite was required and the mail server is not setup)."));
                  }
                }
              }
              else
              {               
                //otherwise just return we failed
                rp.setResponse(new ResponseObject("Invite Community",false,"The user is already a member of this community."));
              }
            }
            else
            {
              rp.setResponse(new ResponseObject("Invite Community",false,"Person does not exist"));
            }
          }
          else
          {
            rp.setResponse(new ResponseObject("Invite Community",false,"You must be owner to invite other members, if you received an invite, you must accept it through that"));
          }
        }
        else
        {
          rp.setResponse(new ResponseObject("Invite Community",false,"Cannot invite members to personal community"));
        }
      }
      else
      {
        rp.setResponse(new ResponseObject("Invite Community",false,"Community does not exist"));
      }
    }
    catch(Exception ex)
    {
      rp.setResponse(new ResponseObject("Invite Community",false,"General Error, bad params maybe? " + ex.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param resp
   * @return
   */
  public ResponsePojo requestResponse(String requestIdStr, String resp)
  {
    ResponsePojo rp = new ResponsePojo();
    try
    {
      // Check for valid text response value
      if ( resp.equals("true") || resp.equals("false") )
      {
        // Attempt to retrieve the invite from the social.communityapprove collection
        DBObject dbo = DbManager.getSocial().getCommunityApprove().findOne(new BasicDBObject("_id", new ObjectId(requestIdStr)));
       
        if (dbo != null )
        {
          CommunityApprovePojo cap = CommunityApprovePojo.fromDb(dbo, CommunityApprovePojo.class);
          if ( cap.getType().equals("source"))
          {
            //approving a source
            if ( resp.equals("true"))
            {
              rp = sourceHandler.approveSource(cap.getSourceId(), cap.getCommunityId(), cap.getRequesterId());
            }
            else
            {
              rp = sourceHandler.denySource(cap.getSourceId(), cap.getCommunityId(), cap.getRequesterId());
            }
            if ( rp.getResponse().isSuccess() )
            {
              //remove request object now
              DbManager.getSocial().getCommunityApprove().remove(new BasicDBObject("_id",new ObjectId(requestIdStr)));
            }
          }
          else
          {
            //approving a user joining a community
            BasicDBObject query = new BasicDBObject("_id",new ObjectId(cap.getCommunityId()));
            DBObject dboComm = DbManager.getSocial().getCommunity().findOne(query);
           
            //get user
            BasicDBObject queryPerson = new BasicDBObject("_id",new ObjectId(cap.getPersonId()));
            DBObject dboperson = DbManager.getSocial().getPerson().findOne(queryPerson);
            PersonPojo pp = PersonPojo.fromDb(dboperson, PersonPojo.class);
           
            if ( dboComm != null )
            {
              CommunityPojo cp = CommunityPojo.fromDb(dboComm, CommunityPojo.class);
              boolean isStillPending = isMemberPending(cp, pp);
              //make sure the user is still waiting to join the community, otherwise remove this request and return
              if ( isStillPending )
              {
                if ( resp.equals("false"))
                {
                  //if response is false (deny), always just remove user from community             
                  cp.removeMember(new ObjectId(cap.getPersonId()));
                  /////////////////////////////////////////////////////////////////////////////////////////////////
                  // 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, cp.toDb());
                }
                else
                {
                  //if response is true (allow), always just add community info to user, and change status to active
                 
                  if ( dboperson != null)
                  {
                    cp.updateMemberStatus(cap.getPersonId(), "active");
                    cp.setNumberOfMembers(cp.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, cp.toDb());
                    pp.addCommunity(cp);
                    /////////////////////////////////////////////////////////////////////////////////////////////////
                    // 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().getPerson().update(queryPerson, pp.toDb());
                  }
                  else
                  {
                    rp.setResponse(new ResponseObject("Request Response",false,"The person does not exist."));
                  }
                }
                //return successfully
                rp.setResponse(new ResponseObject("Request Response",true,"Request answered successfully!"));
              }
              else
              {
                //return fail
                rp.setResponse(new ResponseObject("Request Response",false,"Request has already been answered!"));
              }
              //remove request object now
              DbManager.getSocial().getCommunityApprove().remove(new BasicDBObject("_id",new ObjectId(requestIdStr)));
             
            }
            else
            {
              rp.setResponse(new ResponseObject("Request Response",false,"The community does not exist."));
            }
          }
        }
        else
        {
          rp.setResponse(new ResponseObject("Request Response",false,"This request does not exist, possibly answered already?"));
        }
      }
      else
      {
        rp.setResponse(new ResponseObject("Request Response",false,"Reponse must be true or false"));
      }
    }
    catch(Exception ex)
    {
      rp.setResponse(new ResponseObject("Request Response",false,"General Error, bad params maybe?"  + ex.getMessage()));
    }
    return rp;
  }
View Full Code Here

   * @param json
   * @return
   */
  public ResponsePojo updateCommunity(String userIdStr, String communityIdStr, String json)
  {
    ResponsePojo rp = new ResponsePojo();
    try {
      communityIdStr = allowCommunityRegex(userIdStr, communityIdStr);
    }
    catch (Exception e) {
      rp.setResponse(new ResponseObject("Update Community", false, "Error returning community info: " + e.getMessage()));
      return rp;
    }
   
    /////////////////////////////////////////////////////////////////////////////////////////////////
    // Note: Only Sys Admins, Community Owner, and Community Moderators can add update communities
    boolean isOwnerOrModerator = SocialUtils.isOwnerOrModerator(communityIdStr, userIdStr);
    boolean isSysAdmin = RESTTools.adminLookup(userIdStr);
    boolean canUpdate = (isOwnerOrModerator || isSysAdmin) ? true : false
    if (!canUpdate)
    {
      rp.setResponse(new ResponseObject("Update Community",false,"User does not have permission to update the community."));
      return rp;
    }
   
    /////////////////////////////////////////////////////////////////////////////////////////////////
    // Attempt to parse the JSON passed in to a CommunityPojo
    CommunityPojo updateCommunity = null;
    try
    {
      updateCommunity = ApiManager.mapFromApi(json, CommunityPojo.class, new CommunityPojoApiMap());
    }
    catch (Exception ex)
    {
      rp.setResponse(new ResponseObject("Update Community",false,"Update json is badly formatted, could not deserialize."));
      return rp;
    }
   
    try
    {
      // Retrieve community we are trying to update from the database
      BasicDBObject query = new BasicDBObject("_id", new ObjectId(communityIdStr));
      DBObject dbo = DbManager.getSocial().getCommunity().findOne(query);
      String originalName = null;
     
      if ( dbo != null )
      {
       
        CommunityPojo cp = CommunityPojo.fromDb(dbo, CommunityPojo.class);
       
        if (null == cp) {
          rp.setResponse(new ResponseObject("Update Community",false,"Community to update does not exist"));
          return rp;
        }
        // Here are the fields you are allowed to change:
        // name:
        if (null != updateCommunity.getName())
        {
          // If you're changing name then ensure it's unique for consistency
          //TODO (INF-1214): see addCommunity, this is currently something of a security hole
          BasicDBObject nameCheck = new BasicDBObject("name", updateCommunity.getName());
          nameCheck.put("_id", new BasicDBObject(MongoDbManager.ne_, cp.getId()));
          if (null != MongoDbManager.getSocial().getCommunity().findOne(nameCheck)) {
            rp.setResponse(new ResponseObject("Update Community",false,"Can't change name to an existing community"));
            return rp;           
          }//TESTED (tested changing names of existing community works...)   
          originalName = cp.getName();
          cp.setName(updateCommunity.getName());
        }
        if (null != updateCommunity.getDescription()) {
          cp.setDescription(updateCommunity.getDescription());         
        }
        if (null != updateCommunity.getTags()) {
          cp.setTags(updateCommunity.getTags());         
        }
        if ((null != updateCommunity.getCommunityAttributes() && !updateCommunity.getCommunityAttributes().isEmpty()))
        {
          cp.setCommunityAttributes(updateCommunity.getCommunityAttributes());         
        }
        if ((null != updateCommunity.getCommunityUserAttribute() && !updateCommunity.getCommunityUserAttribute().isEmpty()))
        {
          cp.setCommunityUserAttribute(updateCommunity.getCommunityUserAttribute());         
        }
        // Change owner: not allowed here, use community/update/status
        if ((null != updateCommunity.getOwnerId()) && !updateCommunity.getOwnerId().equals(cp.getOwnerId()))
        {
          rp.setResponse(new ResponseObject("Update Community",false,"Use community/update/status to change ownership"));
          return rp;
        }//TESTED
               
        DbManager.getSocial().getCommunity().update(query, cp.toDb());
               
        // Community name has changed, member records need to be updated to reflect the name change
        if (originalName != null)
        {
          DBObject query_person = new BasicDBObject("communities.name", originalName);
          DBObject update_person = new BasicDBObject("$set",new BasicDBObject("communities.$.name", updateCommunity.getName()));         
          DbManager.getSocial().getPerson().update(query_person, update_person, false, true);
         
          //Also need to update share community names to reflect the name change
          DBObject query_share = new BasicDBObject("communities.name", originalName);
          DBObject update_share = new BasicDBObject("$set",new BasicDBObject("communities.$.name", updateCommunity.getName()));         
          DbManager.getSocial().getShare().update(query_share, update_share, false, true);
        }
       
       
        /////////////////////////////////////////////////////////////////////////////////////////////////
        // TODO (INF-1214): Make this code more robust to handle changes to the community that need to
        // propagate out to other records like Person
        // caleb note: 1/7 (change this to use $set is what this means,
        // including above DbManager.getSocial().getCommunity().update(query, cp.toDb()); )
        // and the below unwritten communityuserattri
        /////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////
        // Community.communityUserAttribute
        // If user attributes have changed we might need to update member records...

       
        rp.setResponse(new ResponseObject("Update Community", true, "Community updated successfully."));
      }
      else
      {
        rp.setResponse(new ResponseObject("Update Community",false,"Community does not exist"));
      }
    }
    catch (Exception ex)
    {
      rp.setResponse(new ResponseObject("Update Community",false,"Unable to update community. Error:" + ex.getMessage()));
    }
    return rp;
  }
View Full Code Here

    // Note: Only Sys Admins, Community Owner, and Community Moderators can add users to communities
    boolean isOwnerOrModerator = SocialUtils.isOwnerOrModerator(communityIdStr, userIdStr);
    boolean isSysAdmin = RESTTools.adminLookup(userIdStr);
    boolean canAdd = (isOwnerOrModerator || isSysAdmin || override) ? true : false;
   
    ResponsePojo rp = new ResponsePojo();
   
    if (canAdd)
    {
      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);

          // Get the list of existing members, check to see if user is already
          // a member of the community, make sure CommunityMember obj isn't null/empty
          Boolean alreadyMember = false;       
          Set<CommunityMemberPojo> cmps = null;
          if (community.getMembers() != null)
          {
            cmps = community.getMembers();
            for (CommunityMemberPojo c : cmps)
            {
              if (c.get_id().toStringMongod().equals(personIdStr)) alreadyMember = true;
            }
          }
          else
          {
            cmps = new HashSet<CommunityMemberPojo>();
            community.setMembers(cmps);
          }

          if (!alreadyMember)
          {
            // Note: This changes community owner
            if (userType.equals("owner"))
            {
              community.setOwnerId(new ObjectId(personIdStr));
              community.setOwnerDisplayName(displayName);
            }

            // Create the new member object
            CommunityMemberPojo cmp = new CommunityMemberPojo();
            cmp.set_id(new ObjectId(personIdStr));
            cmp.setEmail(email);
            cmp.setDisplayName(displayName);
            cmp.setUserStatus(userStatus);
            cmp.setUserType(userType);

            // Set the userAttributes based on default
            Set<CommunityMemberUserAttributePojo> cmua = new HashSet<CommunityMemberUserAttributePojo>();
            Map<String,CommunityUserAttributePojo> cua = community.getCommunityUserAttribute();

            Iterator<Map.Entry<String,CommunityUserAttributePojo>> it = cua.entrySet().iterator();
            while (it.hasNext())
            {
              CommunityMemberUserAttributePojo c = new CommunityMemberUserAttributePojo();
              Map.Entry<String,CommunityUserAttributePojo> pair = it.next();
              c.setType(pair.getKey().toString());
              CommunityUserAttributePojo v = (CommunityUserAttributePojo)pair.getValue();
              c.setValue(v.getDefaultValue());
              cmua.add(c);
            }
            cmp.setUserAttributes(cmua);

            // Get Person data to added to member record
            BasicDBObject query2 = new BasicDBObject();
            query2.put("_id", new ObjectId(personIdStr));
            DBObject dbo2 = DbManager.getSocial().getPerson().findOne(query2);
            PersonPojo p = PersonPojo.fromDb(dbo2, PersonPojo.class);

            if (p.getContacts() != null)
            {
              // Set contacts from person record
              Set<CommunityMemberContactPojo> contacts = new HashSet<CommunityMemberContactPojo>();
              Map<String, PersonContactPojo> pcp = p.getContacts();
              Iterator<Map.Entry<String, PersonContactPojo>> it2 = pcp.entrySet().iterator();
              while (it2.hasNext())
              {
                CommunityMemberContactPojo c = new CommunityMemberContactPojo();
                Map.Entry<String, PersonContactPojo> pair = it2.next();
                c.setType(pair.getKey().toString());
                PersonContactPojo v = (PersonContactPojo)pair.getValue();
                c.setValue(v.getValue());
                contacts.add(c);
              }
              cmp.setContacts(contacts);
            }

            // Set links from person record
            if (p.getLinks() != null)
            {
              // Set contacts from person record
              Set<CommunityMemberLinkPojo> links = new HashSet<CommunityMemberLinkPojo>();
              Map<String, PersonLinkPojo> plp = p.getLinks();
              Iterator<Map.Entry<String, PersonLinkPojo>> it3 = plp.entrySet().iterator();
              while (it.hasNext())
              {
                CommunityMemberLinkPojo c = new CommunityMemberLinkPojo();
                Map.Entry<String, PersonLinkPojo> pair = it3.next();
                c.setTitle(pair.getKey().toString());
                PersonLinkPojo v = (PersonLinkPojo)pair.getValue();
                c.setUrl(v.getUrl());
                links.add(c);
              }
              cmp.setLinks(links);
            }

            // Add new member object to the set
            cmps.add(cmp);

            // Increment number of members by 1
            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.addCommunity(personIdStr, communityIdStr, communityName);

            rp.setData(community, new CommunityPojoApiMap());

            rp.setResponse(new ResponseObject("Add member to community", true, "Person has been added as member of community"))
          }         
          else
          {
            rp.setResponse(new ResponseObject("Add member to community",true,"Person is already a member of the community."))
          }
        }
        else
        {
          rp.setResponse(new ResponseObject("Add member to 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("Add member to community", false,
            "Error adding member to community " + e.getMessage()));
     
    }
    else
    {
      rp.setResponse(new ResponseObject("Add member to community", false,
        "The user does not have permissions to add a user to the community."));
    }
   
    return rp;
  }
View Full Code Here

TOP

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

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.