@Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public void updateCollectionItem(
     String collectionId,
     final String collectionItemId,
     CollectionItem newCollectionItem,
     User user) {
   final CollectionItem collectionItem =
       this.getCollectionDao().getCollectionItem(collectionItemId);
   rejectIfNull(collectionItem, GL0056, 404, _COLLECTION_ITEM);
   if (newCollectionItem.getNarration() != null) {
     collectionItem.setNarration(newCollectionItem.getNarration());
   }
   if (newCollectionItem.getStart() != null) {
     collectionItem.setStart(newCollectionItem.getStart());
   }
   if (newCollectionItem.getStop() != null) {
     collectionItem.setStop(newCollectionItem.getStop());
   }
   if (newCollectionItem.getPosition() != null) {
     Collection parentCollection =
         getCollectionDao().getCollectionByUser(collectionId, user.getPartyUid());
     this.resetSequence(
         parentCollection,
         collectionItem.getCollectionItemId(),
         newCollectionItem.getPosition(),
         user.getPartyUid(),
         COLLECTION_ITEM);
   }
   this.getCollectionDao().save(collectionItem);
 }
  @Override
  @Transactional(
      readOnly = false,
      propagation = Propagation.REQUIRED,
      rollbackFor = Exception.class)
  public ActionResponseDTO<Collection> createCollection(
      String folderId, User user, Collection collection) {
    if (collection.getBuildTypeId() != null) {
      collection.setBuildTypeId(Constants.BUILD_WEB_TYPE_ID);
    }
    final Errors errors = validateCollection(collection);
    if (!errors.hasErrors()) {
      Collection targetCollection = null;
      if (folderId != null) {
        targetCollection = this.getCollectionDao().getCollectionByType(folderId, FOLDER_TYPE);
        rejectIfNull(targetCollection, GL0056, 404, FOLDER);

      } else {
        targetCollection =
            getCollectionDao()
                .getCollection(user.getPartyUid(), CollectionType.SHElf.getCollectionType());
        if (targetCollection == null) {
          targetCollection = new Collection();
          targetCollection.setCollectionType(CollectionType.SHElf.getCollectionType());
          targetCollection.setTitle(CollectionType.SHElf.getCollectionType());
          super.createCollection(targetCollection, user);
        }
      }
      createCollection(user, collection, targetCollection);
      getAsyncExecutor().deleteFromCache(V2_ORGANIZE_DATA + user.getPartyUid() + "*");
    }
    return new ActionResponseDTO<Collection>(collection, errors);
  }
 private String moveCollection(String collectionId, Collection targetCollection, User user) {
   CollectionItem sourceCollectionItem =
       getCollectionDao().getCollectionItemById(collectionId, user);
   rejectIfNull(sourceCollectionItem, GL0056, 404, COLLECTION);
   // need to put validation for collaborator
   CollectionItem collectionItem = new CollectionItem();
   if (sourceCollectionItem.getItemType() != null) {
     collectionItem.setItemType(sourceCollectionItem.getItemType());
   }
   String collectionType =
       getParentCollection(
           sourceCollectionItem.getContent().getContentId(),
           sourceCollectionItem.getContent().getContentType().getName(),
           collectionId,
           targetCollection);
   String contentType = null;
   if (collectionType.equalsIgnoreCase(LESSON)) {
     contentType = sourceCollectionItem.getContent().getContentType().getName();
   }
   createCollectionItem(collectionItem, targetCollection, sourceCollectionItem.getContent(), user);
   resetSequence(
       sourceCollectionItem.getCollection().getGooruOid(),
       sourceCollectionItem.getCollectionItemId(),
       user.getPartyUid(),
       COLLECTION);
   getCollectionDao().remove(sourceCollectionItem);
   getAsyncExecutor().deleteFromCache(V2_ORGANIZE_DATA + user.getPartyUid() + "*");
   return contentType;
 }
  public void addNewCollaborators(
      Content content, List<User> userList, User apiCaller, String predicate, boolean addToShelf) {

    Set<ContentPermission> contentPermissions = content.getContentPermissions();

    if (contentPermissions == null) {
      contentPermissions = new HashSet<ContentPermission>();
    }

    if (userList != null && userList.size() > 0) {
      Date date = new Date();
      for (User user : userList) {
        if (!user.getGooruUId().equals(content.getUser().getGooruUId())) {
          boolean newFlag = true;
          for (ContentPermission contentPermission : contentPermissions) {
            if (contentPermission.getParty().getPartyUid().equals(user.getPartyUid())) {
              newFlag = false;
              break;
            }
          }
          if (newFlag) {
            ContentPermission contentPerm = new ContentPermission();
            contentPerm.setParty(user);
            contentPerm.setContent(content);
            contentPerm.setPermission(EDIT);
            contentPerm.setValidFrom(date);
            contentPermissions.add(contentPerm);
          }
        }
      }
    }
    if (contentPermissions != null && contentPermissions.size() > 0) {
      content.setContentPermissions(contentPermissions);
    }
  }
 @Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public void deleteCollection(
     String courseId, String unitId, String lessonId, String collectionId, User user) {
   CollectionItem collection =
       this.getCollectionDao().getCollectionItem(lessonId, collectionId, user.getPartyUid());
   rejectIfNull(collection, GL0056, 404, COLLECTION);
   reject(
       this.getOperationAuthorizer().hasUnrestrictedContentAccess(collectionId, user),
       GL0099,
       403,
       COLLECTION);
   Collection lesson = getCollectionDao().getCollectionByType(lessonId, LESSON_TYPE);
   rejectIfNull(lesson, GL0056, 404, LESSON);
   Collection course = getCollectionDao().getCollectionByType(courseId, COURSE_TYPE);
   rejectIfNull(course, GL0056, 404, COURSE);
   Collection unit = getCollectionDao().getCollectionByType(unitId, UNIT_TYPE);
   rejectIfNull(unit, GL0056, 404, UNIT);
   this.resetSequence(lessonId, collection.getCollectionItemId(), user.getPartyUid(), COLLECTION);
   this.deleteCollection(collectionId);
   this.updateContentMetaDataSummary(
       lesson.getContentId(), collection.getContent().getContentType().getName(), DELETE);
   collection.getContent().setIsDeleted((short) 1);
   this.getCollectionDao().save(collection);
   getCollectionEventLog()
       .collectionEventLog(courseId, unitId, lessonId, collection, user, null, DELETE);
 }
 public List<HashMap<String, String>> getSubscribtionUserList(String gooruOid) {
   List<ShelfItem> shelfItemList = shelfService.getShelfSubscribeUserList(gooruOid);
   List<HashMap<String, String>> subscriptions = new ArrayList<HashMap<String, String>>();
   if (shelfItemList != null) {
     for (ShelfItem shelfItem : shelfItemList) {
       User user = this.getUserRepository().findByGooruId(shelfItem.getShelf().getUserId());
       if (user != null) {
         if (shelfItem
             .getResource()
             .getUser()
             .getGooruUId()
             .equalsIgnoreCase(user.getGooruUId())) {
           continue;
         }
         HashMap<String, String> hMap = new HashMap<String, String>();
         hMap.put(SUBSCRIBED_ON, shelfItem.getCreatedOn().toString());
         hMap.put(CONT_USER_ID, shelfItem.getResource().getUser().getGooruUId());
         hMap.put(CONT_FIRSTNAME, user.getFirstName());
         hMap.put(CONT_LASTNAME, user.getLastName());
         hMap.put(SCB_USER_ID, shelfItem.getShelf().getUserId());
         subscriptions.add(hMap);
       }
     }
   }
   return subscriptions;
 }
 @AuthorizeOperations(operations = {GooruOperationConstants.OPERATION_FEEDBACK_UPDATE})
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 @RequestMapping(method = RequestMethod.PUT, value = "/{id}")
 public ModelAndView updateFeedback(
     @RequestBody String data,
     @PathVariable(value = ID) String feedbackId,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   User user = (User) request.getAttribute(Constants.USER);
   List<Feedback> feedbacks =
       getFeedbackService()
           .updateFeedback(feedbackId, this.buildFeedbackFromInputParameters(data, request));
   Feedback feedback = feedbacks.get(0);
   // To capture activity log
   SessionContextSupport.putLogParameter(
       EVENT_NAME, "update-" + feedback.getCategory().getValue());
   SessionContextSupport.putLogParameter(FEEDBACK_ID, feedback.getGooruOid());
   SessionContextSupport.putLogParameter(FEEDBACK_GOORU_OID, feedback.getAssocGooruOid());
   SessionContextSupport.putLogParameter(FEEDBACK_GOORU_UID, feedback.getAssocUserUid());
   SessionContextSupport.putLogParameter(GOORU_UID, user.getPartyUid());
   SessionContextSupport.putLogParameter(SCORE, feedback.getScore());
   SessionContextSupport.putLogParameter(CONTEXT, feedback.getContext());
   String includes[] = (String[]) ArrayUtils.addAll(FEEDBACK_INCLUDE_FIELDS, ERROR_INCLUDE);
   return toModelAndViewWithIoFilter(feedbacks, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, includes);
 }
  @Override
  @Transactional(
      readOnly = false,
      propagation = Propagation.REQUIRED,
      rollbackFor = Exception.class)
  public void inviteUserForClass(List<String> emails, final String classUid, final User user) {
    final UserClass userClass = this.getClassRepository().getClassById(classUid);
    rejectIfNull(userClass, GL0056, 404, CLASS);
    // To Do, Fix me

    CustomTableValue status =
        this.getCustomTableRepository().getCustomTableValue(INVITE_USER_STATUS, PENDING);
    List<String> emailIds = new ArrayList<String>();
    User creator = getUserRepository().findByGooruId(userClass.getUserUid());
    for (String email : emails) {
      InviteUser inviteUser =
          this.getInviteRepository().findInviteUserById(email, userClass.getPartyUid(), null);
      if (inviteUser == null) {
        inviteUser = new InviteUser(email, userClass.getPartyUid(), CLASS, user, status);
        this.getInviteRepository().save(inviteUser);
        emailIds.add(email);
      }
      try {
        String courseGooruOid = null;
        if (userClass.getCourseContentId() != null) {
          Content content =
              this.getContentRepository().findByContent(userClass.getCourseContentId());
          if (content != null) {
            courseGooruOid = content.getGooruOid();
          }
        }
        if (userClass.getVisibility() != null && !userClass.getVisibility()) {
          this.getMailHandler()
              .sendMailToInviteUser(
                  email,
                  userClass.getPartyUid(),
                  creator,
                  userClass.getName(),
                  user.getUsername(),
                  userClass.getGroupCode(),
                  courseGooruOid);
        } else {
          this.getMailHandler()
              .sendMailToOpenClassUser(
                  email,
                  userClass.getPartyUid(),
                  creator,
                  userClass.getName(),
                  user.getUsername(),
                  userClass.getGroupCode(),
                  courseGooruOid);
        }
      } catch (Exception e) {
        LOGGER.error(ERROR, e);
      }
    }
  }
 private Map<String, Object> getLastCollectionModifyUser(String userUid) {
   Map<String, Object> lastUserModifiedMap = null;
   final User lastUserModified = this.getUserService().findByGooruId(userUid);
   if (lastUserModified != null) {
     lastUserModifiedMap = new HashMap<String, Object>();
     lastUserModifiedMap.put(USER_NAME, lastUserModified.getUsername());
     lastUserModifiedMap.put(GOORU_UID, lastUserModified.getGooruUId());
   }
   return lastUserModifiedMap;
 }
 @Override
 @Transactional(readOnly = true, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
 public Map<String, Object> getCollection(
     String collectionId,
     String collectionType,
     User user,
     boolean includeItems,
     boolean includeLastModifiedUser) {
   Map<String, Object> collection = super.getCollection(collectionId, collectionType);
   StringBuilder key = new StringBuilder(ALL_);
   key.append(collection.get(GOORU_OID));
   collection.put(VIEWS, getDashboardCassandraService().readAsLong(key.toString(), COUNT_VIEWS));
   if (includeItems) {
     collection.put(COLLECTION_ITEMS, this.getCollectionItems(collectionId, MAX_LIMIT, 0));
   }
   if (includeLastModifiedUser) {
     Object lastModifiedUserUid = collection.get(LAST_MODIFIED_USER_UID);
     if (lastModifiedUserUid != null) {
       collection.put(
           LAST_USER_MODIFIED, getLastCollectionModifyUser(String.valueOf(lastModifiedUserUid)));
     }
   }
   collection.remove(LAST_MODIFIED_USER_UID);
   final boolean isCollaborator =
       this.getCollaboratorRepository().findCollaboratorById(collectionId, user.getPartyUid())
               != null
           ? true
           : false;
   collection.put(PERMISSIONS, getContentService().getContentPermission(collectionId, user));
   collection.put(IS_COLLABORATOR, isCollaborator);
   return collection;
 }
 @Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public ActionResponseDTO<CollectionItem> createResource(
     String collectionId, CollectionItem collectionItem, User user) {
   Resource resource = collectionItem.getResource();
   final Errors errors = validateResource(resource);
   if (!errors.hasErrors()) {
     Collection collection =
         getCollectionDao().getCollectionByType(collectionId, COLLECTION_TYPES);
     rejectIfNull(collection, GL0056, 404, COLLECTION);
     resource.setSharing(collection.getSharing());
     resource = getResourceBoService().createResource(resource, user);
     collectionItem.setItemType(ADDED);
     collectionItem = createCollectionItem(collectionItem, collection, resource, user);
     getCollectionEventLog()
         .collectionItemEventLog(
             collectionId, collectionItem, user.getPartyUid(), RESOURCE, collectionItem, ADD);
     updateCollectionMetaDataSummary(collection.getContentId(), RESOURCE, ADD);
     Map<String, Object> data =
         generateResourceMetaData(resource, collectionItem.getResource(), user);
     createContentMeta(resource, data);
   }
   return new ActionResponseDTO<CollectionItem>(collectionItem, errors);
 }
  private void sendMailToCollabrators(List<User> users, Resource resource, User apiCaller) {
    try {
      String flag = "";
      String collectionOrQuizTitle = "";
      Learnguide learnguide = learnguideRepository.findByContent(resource.getGooruOid());
      Assessment assessment = assessmentRepository.findQuizContent(resource.getGooruOid());
      if (resource
              .getResourceType()
              .getName()
              .equalsIgnoreCase(ResourceType.Type.CLASSPLAN.getType())
          || resource
              .getResourceType()
              .getName()
              .equalsIgnoreCase(ResourceType.Type.CLASSBOOK.getType())) {
        collectionOrQuizTitle = learnguide.getLesson();
        if (collectionOrQuizTitle == null) {
          collectionOrQuizTitle = learnguide.getTitle();
        }
        flag = COLLECTION;
      } else if (resource
              .getResourceType()
              .getName()
              .equalsIgnoreCase(ResourceType.Type.ASSESSMENT_QUIZ.getType())
          || resource
              .getResourceType()
              .getName()
              .equalsIgnoreCase(ResourceType.Type.ASSESSMENT_EXAM.getType())) {
        collectionOrQuizTitle = assessment.getName();
        if (collectionOrQuizTitle == null) {
          collectionOrQuizTitle = assessment.getTitle();
        }
        flag = "quiz";
      }
      for (User user : users) {

        mailHandler.sendMailForCollaborator(
            user.getPartyUid(),
            apiCaller.getUsername(),
            resource.getGooruOid(),
            collectionOrQuizTitle,
            flag);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 @Override
 public Classpage getClasspage(String collectionId, User user, String merge) {
   Classpage classpage = this.getCollectionRepository().getClasspageByGooruOid(collectionId, null);
   if (classpage != null && merge != null) {
     Map<String, Object> permissions = new HashMap<String, Object>();
     Boolean isMember = false;
     String status = NOTINVITED;
     InviteUser inviteUser = null;
     String mailId = null;
     UserGroup userGroup =
         this.getUserGroupService().findUserGroupByGroupCode(classpage.getClasspageCode());
     if (userGroup != null && !user.getGooruUId().equalsIgnoreCase(ANONYMOUS)) {
       isMember =
           this.getUserRepository()
                       .getUserGroupMemebrByGroupUid(userGroup.getPartyUid(), user.getPartyUid())
                   != null
               ? true
               : false;
       if (isMember) {
         status = ACTIVE;
       }
       if (user.getIdentities().size() > 0) {
         mailId = user.getIdentities().iterator().next().getExternalId();
       }
       inviteUser = this.getInviteRepository().findInviteUserById(mailId, collectionId);
       if (!isMember && inviteUser == null && classpage.getSharing().equalsIgnoreCase(PUBLIC)) {
         inviteUser =
             this.getInviteService().createInviteUserObj(mailId, collectionId, CLASS, user);
         this.getInviteRepository().save(inviteUser);
         this.getInviteRepository().flush();
       }
       if (inviteUser != null) {
         status = PENDING;
       }
     }
     if (merge.contains(PERMISSIONS)) {
       permissions.put(
           PERMISSIONS, this.getContentService().getContentPermission(collectionId, user));
     }
     permissions.put(STATUS, status);
     classpage.setMeta(permissions);
   }
   return classpage;
 }
  @AuthorizeOperations(operations = {GooruOperationConstants.OPERATION_FEEDBACK_ADD})
  @Transactional(
      readOnly = false,
      propagation = Propagation.REQUIRED,
      rollbackFor = Exception.class)
  @RequestMapping(method = RequestMethod.POST, value = "")
  public ModelAndView createFeedback(
      @RequestBody String data, HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    User user = (User) request.getAttribute(Constants.USER);
    Feedback newFeedback = this.buildFeedbackFromInputParameters(data, request);
    boolean list = newFeedback.getTypes() != null ? true : false;
    List<Feedback> feedbacks = getFeedbackService().createFeedbacks(newFeedback, user);
    Feedback feedback = feedbacks.get(0);
    response.setStatus(HttpServletResponse.SC_CREATED);
    // To capture activity log

    SessionContextSupport.putLogParameter(TARGET_TYPE, feedback.getTarget().getValue());
    SessionContextSupport.putLogParameter(FEEDBACK_GOORU_OID, feedback.getAssocGooruOid());
    SessionContextSupport.putLogParameter(FEEDBACK_GOORU_UID, feedback.getAssocUserUid());
    SessionContextSupport.putLogParameter(FEEDBACK_ID, feedback.getGooruOid());
    SessionContextSupport.putLogParameter(GOORU_UID, user.getPartyUid());
    SessionContextSupport.putLogParameter(SCORE, feedback.getScore());
    ContextDTO contextDTO = null;
    if (newFeedback.getContext() != null) {
      contextDTO = buildContextInputParam(newFeedback.getContext());
    }
    String eventName = "create-" + feedback.getCategory().getValue();
    if (contextDTO != null) {
      SessionContextSupport.putLogParameter("parentGooruId", contextDTO.getCollectionGooruId());
      SessionContextSupport.putLogParameter("contentGooruId", contextDTO.getResourceGooruId());
      if (contextDTO.getEventName() != null) {
        eventName = contextDTO.getEventName();
      }
    } else {
      SessionContextSupport.putLogParameter("parentGooruId", null);
      SessionContextSupport.putLogParameter("contentGooruId", null);
    }
    SessionContextSupport.putLogParameter(EVENT_NAME, eventName);
    String includes[] = (String[]) ArrayUtils.addAll(FEEDBACK_INCLUDE_FIELDS, ERROR_INCLUDE);
    return toModelAndViewWithIoFilter(
        list ? feedbacks : feedback, RESPONSE_FORMAT_JSON, EXCLUDE_ALL, true, includes);
  }
  public void deleteCollaborators(
      Content content, List<User> userList, User apiCaller, String predicate) {

    Set<ContentPermission> contentPermissions = content.getContentPermissions();
    Set<ContentPermission> removePermissions = new HashSet<ContentPermission>();

    for (ContentPermission contentPermission : contentPermissions) {
      for (User user : userList) {
        if (user.getPartyUid().equalsIgnoreCase(contentPermission.getParty().getPartyUid())) {
          removePermissions.add(contentPermission);
          break;
        }
      }
    }
    if (removePermissions.size() > 0) {
      contentPermissions.removeAll(removePermissions);
      this.getBaseRepository().removeAll(removePermissions);
    }

    this.getBaseRepository().saveAll(contentPermissions);
    this.getBaseRepository().flush();
  }
 public User updateNewCollaborators(
     Collection collection,
     List<String> collaboratorsList,
     User apiCaller,
     String predicate,
     String collaboratorOperation) {
   List<User> userList = null;
   if (collaboratorsList != null && collaboratorsList.size() > 0 && !collaboratorsList.isEmpty()) {
     userList = this.getUserRepository().findByIdentities(collaboratorsList);
     if (collaboratorOperation.equals(DELETE)) {
       deleteCollaborators(collection, userList, apiCaller, predicate);
     } else {
       addNewCollaborators(collection, userList, apiCaller, predicate, false);
     }
   }
   if (userList.size() > 0) {
     User user = userList.get(0);
     user.setEmailId(user.getIdentities().iterator().next().getExternalId());
     return user;
   }
   return null;
 }
 @AuthorizeOperations(operations = {GooruOperationConstants.OPERATION_FEEDBACK_DELETE})
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
 public void deleteFeedback(
     @PathVariable(value = ID) String feedbackId,
     @RequestBody String data,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception {
   User user = (User) request.getAttribute(Constants.USER);
   if (data != null && data.length() > 0) {
     Feedback feedback = this.buildFeedbackFromInputParameters(data, request);
     SessionContextSupport.putLogParameter(CONTEXT, feedback.getContext());
   }
   this.getFeedbackService().deleteFeedback(feedbackId, user.getPartyUid());
   SessionContextSupport.putLogParameter(EVENT_NAME, "delete-" + getFeedbackCategory(request));
   SessionContextSupport.putLogParameter(FEEDBACK_ID, feedbackId);
   response.setStatus(HttpServletResponse.SC_NO_CONTENT);
 }
 public JSONObject getContentSocialData(User user, String contentGooruOid) throws JSONException {
   JSONObject socialDataJSON = new JSONObject();
   Integer contentUserRating =
       ratingService.getContentRatingForUser(user.getPartyUid(), contentGooruOid);
   boolean isContentAlreadySubscribed =
       this.getShelfService().hasContentSubscribed(user, contentGooruOid);
   List<HashMap<String, String>> subscriptions = this.getSubscribtionUserList(contentGooruOid);
   Rating rating = ratingService.findByContent(contentGooruOid);
   socialDataJSON.put(CONTENT_USER_RATING, contentUserRating);
   socialDataJSON.put(IS_CONTENT_ALREADY_SUBSCRIBED, isContentAlreadySubscribed);
   socialDataJSON.put(CONTENT_RATING, new JSONObject(rating).put(VOTE_UP, rating.getVotesUp()));
   socialDataJSON.put(SUBSCRIPTION_COUNT, subscriptions.size());
   socialDataJSON.put(
       SUBSCRIPTION_LIST, new JSONArray(SerializerUtil.serializeToJson(subscriptions)));
   return socialDataJSON;
 }
 @Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public CollectionItem addResource(String collectionId, String resourceId, User user) {
   Collection collection = getCollectionDao().getCollectionByType(collectionId, COLLECTION_TYPES);
   rejectIfNull(collection, GL0056, 404, COLLECTION);
   Resource resource = getResourceBoService().getResource(resourceId);
   rejectIfNull(resource, GL0056, 404, RESOURCE);
   reject(!resource.getContentType().getName().equalsIgnoreCase(QUESTION), GL0056, 404, RESOURCE);
   updateCollectionMetaDataSummary(collection.getContentId(), RESOURCE, ADD);
   CollectionItem collectionItem = new CollectionItem();
   getCollectionEventLog()
       .collectionItemEventLog(
           collectionId, collectionItem, user.getPartyUid(), RESOURCE, null, ADD);
   collectionItem.setItemType(ADDED);
   return createCollectionItem(collectionItem, collection, resource, user);
 }
  public boolean hasRelatedContentPlayPermission(Learnguide learnguide, User user) {
    if (learnguide == null) {
      // To an empty collection people don't have access!
      return false;
    }

    boolean hasCollaboratorPermission = hasCollaboratorPermission(learnguide, user);

    boolean hasUnrestrictedContentAccess = getOperationAuthorizer().hasUnrestrictedContentAccess();

    if (hasUnrestrictedContentAccess
        || learnguide.getSharing().equalsIgnoreCase(PUBLIC)
        || hasCollaboratorPermission
        || learnguide.getUser().getUserId() == user.getUserId()
        || hasSubOrgPermission(learnguide.getOrganization().getPartyUid())) {
      return true;
    }
    return false;
  }
 @Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public ActionResponseDTO<Organization> updateOrganization(
     Organization newOrganization, String existingOrganizationUid, User apiCaller)
     throws Exception {
   Organization existingOrganization = null;
   Errors errors = validateNullFields(newOrganization);
   if (!errors.hasErrors()) {
     existingOrganization = organizationRepository.getOrganizationByUid(existingOrganizationUid);
     if (existingOrganization != null) {
       existingOrganization.setPartyName(newOrganization.getPartyName());
       existingOrganization.setLastModifiedOn(new Date(System.currentTimeMillis()));
       existingOrganization.setLastModifiedUserUid(apiCaller.getPartyUid());
       organizationRepository.save(existingOrganization);
     }
   }
   return new ActionResponseDTO<Organization>(existingOrganization, errors);
 }
 @Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public CollectionItem addQuestion(String collectionId, String questionId, User user) {
   Collection collection = getCollectionDao().getCollectionByType(collectionId, COLLECTION_TYPES);
   rejectIfNull(collection, GL0056, 404, COLLECTION);
   AssessmentQuestion question = this.getQuestionService().getQuestion(questionId);
   rejectIfNull(question, GL0056, 404, QUESTION);
   AssessmentQuestion copyQuestion = this.getQuestionService().copyQuestion(question, user);
   CollectionItem collectionItem = new CollectionItem();
   getCollectionEventLog()
       .collectionItemEventLog(
           collectionId, collectionItem, user.getPartyUid(), QUESTION, null, ADD);
   collectionItem.setItemType(ADDED);
   collectionItem = createCollectionItem(collectionItem, collection, copyQuestion, user);
   updateCollectionMetaDataSummary(collection.getContentId(), QUESTION, ADD);
   Map<String, Object> metaData = generateQuestionMetaData(copyQuestion, copyQuestion, user);
   createContentMeta(copyQuestion, metaData);
   return collectionItem;
 }
  public void saveOrUpdate(Object model) {
    if (model instanceof Annotation) {
      if (((Annotation) model).getResource() != null) {
        ((Content) model).setOrganization(((Annotation) model).getResource().getOrganization());
        ((Content) model)
            .setVersion(
                ((Content) model).getVersion() == null ? 1 : ((Content) model).getVersion() + 1);
      }

    } else if (model instanceof OrganizationWrapper
        && ((OrganizationWrapper) model).getOrganization() == null) {
      ((OrganizationWrapper) model).setOrganization(getCurrentUserPrimaryOrganization());
    }

    if (model instanceof Content) {
      ((Content) model).setLastModified(new Date(System.currentTimeMillis()));
      ((Content) model)
          .setVersion(
              ((Content) model).getVersion() == null ? 1 : ((Content) model).getVersion() + 1);
    }

    if (model instanceof CollectionItem) {
      ((CollectionItem) model)
          .getCollection()
          .setLastModified(new Date(System.currentTimeMillis()));
      ((CollectionItem) model)
          .getCollection()
          .setVersion(
              ((CollectionItem) model).getCollection().getVersion() == null
                  ? 1
                  : ((CollectionItem) model).getCollection().getVersion() + 1);
    }

    if (model instanceof User) {
      ((User) model).setLastModifiedOn(new Date(System.currentTimeMillis()));
    }

    getSession().saveOrUpdate(model);
  }
 @Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public void moveCollection(String folderId, String collectionId, User user) {
   Collection targetCollection = null;
   if (folderId != null) {
     targetCollection = this.getCollectionDao().getCollectionByType(folderId, FOLDER_TYPE);
     rejectIfNull(targetCollection, GL0056, 404, FOLDER);
   } else {
     targetCollection =
         getCollectionDao()
             .getCollection(user.getPartyUid(), CollectionType.SHElf.getCollectionType());
     if (targetCollection == null) {
       targetCollection = new Collection();
       targetCollection.setCollectionType(CollectionType.SHElf.getCollectionType());
       targetCollection.setTitle(CollectionType.SHElf.getCollectionType());
       super.createCollection(targetCollection, user);
     }
   }
   moveCollection(collectionId, targetCollection, user);
 }
  public void updateCollaborators(
      Resource resource,
      List<User> userList,
      User apiCaller,
      String predicate,
      boolean addToShelf) {

    Set<ContentPermission> contentPermissions = resource.getContentPermissions();
    List<User> newUsers = new ArrayList<User>();
    if (contentPermissions == null) {
      contentPermissions = new HashSet<ContentPermission>();
    }
    if (userList != null && userList.size() > 0) {
      Date date = new Date();
      for (User user : userList) {
        if (!user.getGooruUId().equals(resource.getUser().getGooruUId())) {
          boolean newFlag = true;
          for (ContentPermission contentPermission : contentPermissions) {
            if (contentPermission.getParty().getPartyUid().equals(user.getPartyUid())) {
              newFlag = false;
              break;
            }
          }
          if (newFlag) {
            ContentPermission contentPerm = new ContentPermission();
            contentPerm.setParty(user);
            contentPerm.setContent(resource);
            contentPerm.setPermission(EDIT);
            contentPerm.setValidFrom(date);
            contentPermissions.add(contentPerm);
            if (!newUsers.contains(user)) {
              newUsers.add(user);
            }
            if (addToShelf) {
              this.getShelfService().addCollaboratorShelf(contentPerm);
            }
          }
        }
      }
      if (addToShelf) {
        if (newUsers.size() > 0) {
          sendMailToCollabrators(newUsers, resource, apiCaller);
        }
      }
    }
    Set<ContentPermission> removePermissions = new HashSet<ContentPermission>();
    for (ContentPermission contentPermission : contentPermissions) {
      boolean remove = true;
      if (userList != null) {
        for (User user : userList) {
          if (user.getPartyUid().equals(contentPermission.getParty().getPartyUid())) {
            remove = false;
            break;
          }
        }
      }
      if (remove) {
        removePermissions.add(contentPermission);
      }
    }
    if (removePermissions.size() > 0) {
      this.getShelfService().removeCollaboratorShelf(removePermissions);
      contentPermissions.removeAll(removePermissions);
      this.getBaseRepository().removeAll(removePermissions);
    }

    this.getBaseRepository().save(resource);
  }
  @Override
  @Transactional(
      readOnly = false,
      propagation = Propagation.REQUIRED,
      rollbackFor = Exception.class)
  public ActionResponseDTO<Organization> saveOrganization(
      Organization organizationData, User user, HttpServletRequest request) {
    Errors errors = validateNullFields(organizationData);
    rejectIfMaxLimitExceed(400, organizationData.getPartyName(), GL0014, PARTY_NAME, "400");
    Organization newOrganization = new Organization();
    if (!errors.hasErrors()) {
      newOrganization.setPartyName(organizationData.getPartyName());
      String randomString = getRandomString(5);
      newOrganization.setOrganizationCode(randomString);
      newOrganization.setPartyType(PartyType.ORGANIZATION.getType());
      newOrganization.setCreatedOn(new Date(System.currentTimeMillis()));
      newOrganization.setS3StorageArea(storageRepository.getAvailableStorageArea(1));
      newOrganization.setNfsStorageArea(storageRepository.getAvailableStorageArea(2));
      newOrganization.setUserUid(user.getPartyUid());

      if (organizationData.getStateProvince() != null
          && organizationData.getStateProvince().getStateUid() != null) {
        newOrganization.setStateProvince(
            getCountryRepository().getState(organizationData.getStateProvince().getStateUid()));
      }
      if (organizationData.getType() != null && organizationData.getType().getValue() != null) {
        CustomTableValue type =
            this.getCustomTableRepository()
                .getCustomTableValue(
                    CustomProperties.Table.ORGANIZATION_CATEGORY.getTable(),
                    organizationData.getType().getValue());
        rejectIfNull(type, GL0056, TYPE);
        newOrganization.setType(type);
      }

      if (organizationData.getParentId() != null) {
        newOrganization.setParentOrganization(
            this.getOrganizationById(organizationData.getParentId()));
      }
      organizationRepository.save(newOrganization);
      updateOrgSetting(newOrganization);
      User newUser = new User();
      newUser.setOrganization(newOrganization);
      newUser.setFirstName(FIRST);
      newUser.setLastName(LAST);
      newUser.setPartyUid(ANONYMOUS_ + randomString);
      newUser.setUsername(ANONYMOUS_ + randomString);
      newUser.setEmailId(ANONYMOUS_ + randomString + AT_GMAIL_DOT_COM);
      Application application = new Application();
      application.setTitle(newOrganization.getPartyName());
      application.setUrl(HTTP_URL + newOrganization.getPartyName() + DOT_COM);
      try {
        User newOrgUser = new User();
        newOrgUser =
            userManagementService.createUser(
                newUser, null, null, 1, null, null, null, null, null, null, null, null, request,
                null, null);
        OrganizationSetting newOrganizationSetting = new OrganizationSetting();
        newOrganizationSetting.setOrganization(newOrganization);
        newOrganizationSetting.setKey(ANONYMOUS);
        newOrganizationSetting.setValue(newOrgUser.getPartyUid());
        organizationSettingRepository.save(newOrganizationSetting);
        application.setOrganization(newOrganization);
        applicationService.createApplication(application, newOrgUser);
        accountService.createSessionToken(newOrgUser, application.getKey(), request);

      } catch (Exception e) {
        LOGGER.debug("Error" + e);
      }
    }
    return new ActionResponseDTO<Organization>(newOrganization, errors);
  }
  @Override
  public ActionResponseDTO<CollectionItem> createClasspageItem(
      String assignmentGooruOid,
      String classpageGooruOid,
      CollectionItem collectionItem,
      User user,
      String type)
      throws Exception {
    Classpage classpage = null;
    if (type != null && type.equalsIgnoreCase(CollectionType.USER_CLASSPAGE.getCollectionType())) {
      if (classpageGooruOid != null) {
        classpage = this.getClasspage(classpageGooruOid, null, null);
      } else {
        classpage =
            this.getCollectionRepository()
                .getUserShelfByClasspageGooruUid(
                    user.getGooruUId(), CollectionType.USER_CLASSPAGE.getCollectionType());
      }
      if (classpage == null) {
        classpage = new Classpage();
        classpage.setTitle(MY_CLASSPAGE);
        classpage.setCollectionType(CollectionType.USER_CLASSPAGE.getCollectionType());
        classpage.setClasspageCode(BaseUtil.base48Encode(7));
        classpage.setGooruOid(UUID.randomUUID().toString());
        ContentType contentType =
            (ContentType)
                this.getCollectionRepository().get(ContentType.class, ContentType.RESOURCE);
        classpage.setContentType(contentType);
        ResourceType resourceType =
            (ResourceType)
                this.getCollectionRepository()
                    .get(ResourceType.class, ResourceType.Type.CLASSPAGE.getType());
        classpage.setResourceType(resourceType);
        classpage.setLastModified(new Date(System.currentTimeMillis()));
        classpage.setCreatedOn(new Date(System.currentTimeMillis()));
        classpage.setSharing(Sharing.PRIVATE.getSharing());
        classpage.setUser(user);
        classpage.setOrganization(user.getPrimaryOrganization());
        classpage.setCreator(user);
        classpage.setDistinguish(Short.valueOf(ZERO));
        classpage.setRecordSource(NOT_ADDED);
        classpage.setIsFeatured(0);
        this.getCollectionRepository().save(classpage);
      }
      collectionItem.setItemType(ShelfType.AddedType.SUBSCRIBED.getAddedType());
    } else {
      classpage = this.getClasspage(classpageGooruOid, null, null);
      collectionItem.setItemType(ShelfType.AddedType.ADDED.getAddedType());
    }

    Collection collection =
        this.getCollectionRepository()
            .getCollectionByGooruOid(assignmentGooruOid, classpage.getUser().getGooruUId());
    Errors errors = validateClasspageItem(classpage, collection, collectionItem);
    if (collection != null) {
      if (!errors.hasErrors()) {
        collectionItem.setCollection(classpage);
        collectionItem.setResource(collection);
        int sequence =
            collectionItem.getCollection().getCollectionItems() != null
                ? collectionItem.getCollection().getCollectionItems().size() + 1
                : 1;
        collectionItem.setItemSequence(sequence);
        this.getCollectionRepository().save(collectionItem);
      }
    } else {
      throw new Exception("invalid assignmentId -" + assignmentGooruOid);
    }

    return new ActionResponseDTO<CollectionItem>(collectionItem, errors);
  }
 public boolean hasCollaboratorPermission(Learnguide learnguide, User user) {
   List<User> userList =
       learnguideRepository.findCollaborators(learnguide.getGooruOid(), user.getPartyUid());
   return userList.size() > 0 ? true : false;
 }
 @Override
 @Transactional(
     readOnly = false,
     propagation = Propagation.REQUIRED,
     rollbackFor = Exception.class)
 public void updateCollection(
     String parentId, String collectionId, Collection newCollection, User user) {
   boolean hasUnrestrictedContentAccess =
       this.getOperationAuthorizer().hasUnrestrictedContentAccess(collectionId, user);
   // TO-Do add validation for collection type and collaborator validation
   Collection collection = getCollectionDao().getCollection(collectionId);
   if (newCollection.getSharing() != null
       && (newCollection.getSharing().equalsIgnoreCase(Sharing.PRIVATE.getSharing())
           || newCollection.getSharing().equalsIgnoreCase(Sharing.PUBLIC.getSharing())
           || newCollection.getSharing().equalsIgnoreCase(Sharing.ANYONEWITHLINK.getSharing()))) {
     if (!newCollection.getSharing().equalsIgnoreCase(PUBLIC)) {
       collection.setPublishStatusId(null);
     }
     if (!collection
             .getCollectionType()
             .equalsIgnoreCase(ResourceType.Type.ASSESSMENT_URL.getType())
         && newCollection.getSharing().equalsIgnoreCase(PUBLIC)
         && !userService.isContentAdmin(user)) {
       collection.setPublishStatusId(Constants.PUBLISH_PENDING_STATUS_ID);
       newCollection.setSharing(collection.getSharing());
     }
     if (collection
             .getCollectionType()
             .equalsIgnoreCase(ResourceType.Type.ASSESSMENT_URL.getType())
         || newCollection.getSharing().equalsIgnoreCase(PUBLIC)
             && userService.isContentAdmin(user)) {
       collection.setPublishStatusId(Constants.PUBLISH_REVIEWED_STATUS_ID);
     }
     collection.setSharing(newCollection.getSharing());
   }
   if (newCollection.getSettings() != null) {
     updateCollectionSettings(collection, newCollection);
   }
   if (newCollection.getLanguageObjective() != null) {
     collection.setLanguageObjective(newCollection.getLanguageObjective());
   }
   if (hasUnrestrictedContentAccess) {
     if (newCollection.getCreator() != null && newCollection.getCreator().getPartyUid() != null) {
       User creatorUser = getUserService().findByGooruId(newCollection.getCreator().getPartyUid());
       collection.setCreator(creatorUser);
     }
     if (newCollection.getUser() != null && newCollection.getUser().getPartyUid() != null) {
       User ownerUser = getUserService().findByGooruId(newCollection.getUser().getPartyUid());
       collection.setUser(ownerUser);
     }
     if (newCollection.getNetwork() != null) {
       collection.setNetwork(newCollection.getNetwork());
     }
   }
   if (newCollection.getPosition() != null) {
     CollectionItem parentCollectionItem =
         this.getCollectionDao().getCollectionItemById(collectionId, user);
     if (parentId == null) {
       parentId = parentCollectionItem.getCollection().getGooruOid();
     }
     Collection parentCollection =
         getCollectionDao().getCollectionByUser(parentId, user.getPartyUid());
     this.resetSequence(
         parentCollection,
         parentCollectionItem.getCollectionItemId(),
         newCollection.getPosition(),
         user.getPartyUid(),
         COLLECTION);
   }
   if (newCollection.getMediaFilename() != null) {
     String folderPath = Collection.buildResourceFolder(collection.getContentId());
     this.getGooruImageUtil()
         .imageUpload(newCollection.getMediaFilename(), folderPath, COLLECTION_IMAGE_DIMENSION);
     StringBuilder basePath = new StringBuilder(folderPath);
     basePath.append(File.separator).append(newCollection.getMediaFilename());
     collection.setImagePath(basePath.toString());
   }
   updateCollection(collection, newCollection, user);
   Map<String, Object> data = generateCollectionMetaData(collection, newCollection, user);
   if (data != null && data.size() > 0) {
     ContentMeta contentMeta =
         this.getContentRepository().getContentMeta(collection.getContentId());
     updateContentMeta(contentMeta, data);
   }
 }