/**
   * publish a new event activity
   *
   * @param event
   * @param calendarId
   * @param eventType
   */
  private void publishActivity(CalendarEvent event, String calendarId, String eventType) {
    try {
      Class.forName("org.exoplatform.social.core.space.spi.SpaceService");
    } catch (ClassNotFoundException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("eXo Social components not found!", e);
      }
      return;
    }
    if (calendarId == null
        || calendarId.indexOf(CalendarDataInitialize.SPACE_CALENDAR_ID_SUFFIX) < 0) {
      return;
    }
    try {
      IdentityManager identityM =
          (IdentityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(IdentityManager.class);
      ActivityManager activityM =
          (ActivityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(ActivityManager.class);
      SpaceService spaceService =
          (SpaceService)
              PortalContainer.getInstance().getComponentInstanceOfType(SpaceService.class);

      String spaceGroupId = Utils.getSpaceGroupIdFromCalendarId(calendarId);
      Space space = spaceService.getSpaceByGroupId(spaceGroupId);
      if (space != null) {
        String userId = ConversationState.getCurrent().getIdentity().getUserId();
        Identity spaceIdentity =
            identityM.getOrCreateIdentity(SpaceIdentityProvider.NAME, space.getPrettyName(), false);
        Identity userIdentity =
            identityM.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);
        ExoSocialActivity activity = new ExoSocialActivityImpl();
        activity.setUserId(userIdentity.getId());
        activity.setTitle(event.getSummary());
        activity.setBody(event.getDescription());
        activity.setType("cs-calendar:spaces");
        activity.setTemplateParams(makeActivityParams(event, calendarId, eventType));
        activityM.saveActivityNoReturn(spaceIdentity, activity);
        event.setActivityId(activity.getId());
      }
    } catch (ExoSocialException e) {
      if (LOG.isDebugEnabled()) LOG.error("Can not record Activity for space when event added ", e);
    }
  }
 private void saveToNewDataFormat(ExoSocialActivity activity) {
   try {
     final JSONObject jsonObject = new JSONObject(activity.getTitle());
     final String docActivityTitle =
         "<a href=\"${" + UIDocActivity.DOCLINK + "}\">" + "${" + UIDocActivity.DOCNAME + "}</a>";
     //
     activity.setTitle(docActivityTitle);
     //
     Map<String, String> activityParams = new HashMap<String, String>();
     activityParams.put(UIDocActivity.DOCNAME, jsonObject.getString(UIDocActivity.DOCNAME));
     activityParams.put(UIDocActivity.DOCLINK, jsonObject.getString(UIDocActivity.DOCLINK));
     activityParams.put(UIDocActivity.DOCPATH, jsonObject.getString(UIDocActivity.DOCPATH));
     activityParams.put(UIDocActivity.REPOSITORY, jsonObject.getString(UIDocActivity.REPOSITORY));
     activityParams.put(UIDocActivity.WORKSPACE, jsonObject.getString(UIDocActivity.WORKSPACE));
     activityParams.put(UIDocActivity.MESSAGE, jsonObject.getString(UIDocActivity.MESSAGE));
     activity.setTemplateParams(activityParams);
     //
     ActivityManager activityManager = CommonsUtils.getService(ActivityManager.class);
     //
     activityManager.saveActivityNoReturn(activity);
     activity = activityManager.getActivity(activity.getId());
   } catch (JSONException je) {
     LOG.error("Error with activity's title data");
   } catch (ActivityStorageException ase) {
     LOG.error("Could not save new data format for document activity.", ase);
   } catch (Exception e) {
     LOG.error("Unknown error  to save document activity.", e);
   }
 }
Beispiel #3
0
  public static ExoSocialActivity createActivity(
      IdentityManager identityManager,
      String activityOwnerId,
      Node node,
      String activityMsgBundleKey,
      String activityType,
      boolean isSystemComment,
      String systemComment)
      throws Exception {
    // Populate activity data
    Map<String, String> activityParams =
        populateActivityData(
            node, activityOwnerId, activityMsgBundleKey, isSystemComment, systemComment);

    String title =
        node.hasProperty(NodetypeConstant.EXO_TITLE)
            ? node.getProperty(NodetypeConstant.EXO_TITLE).getString()
            : org.exoplatform.ecm.webui.utils.Utils.getTitle(node);
    ExoSocialActivity activity = new ExoSocialActivityImpl();
    String userId = "";
    if (ConversationState.getCurrent() != null) {
      userId = ConversationState.getCurrent().getIdentity().getUserId();
    } else {
      userId = activityOwnerId;
    }
    Identity identity =
        identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);
    activity.setUserId(identity.getId());
    activity.setType(activityType);
    activity.setUrl(node.getPath());
    activity.setTitle(title);
    activity.setTemplateParams(activityParams);
    return activity;
  }
  /** {@inheritDoc} */
  @Override
  public void spaceAccessEdited(SpaceLifeCycleEvent event) {
    Space space = event.getSpace();

    // Update space's activity
    Identity spaceIdentity =
        identityManager.getOrCreateIdentity(
            SpaceIdentityProvider.NAME, space.getPrettyName(), false);
    String spaceActivityId =
        getStorage()
            .getProfileActivityId(spaceIdentity.getProfile(), Profile.AttachedActivityType.SPACE);
    if (spaceActivityId != null) {
      ExoSocialActivity activity =
          (ExoSocialActivityImpl) activityManager.getActivity(spaceActivityId);
      if (activity != null) {
        if (Space.HIDDEN.equals(space.getVisibility())) {
          activity.isHidden(true);
        }
        if (Space.PRIVATE.equals(space.getVisibility())) {
          activity.isHidden(false);
        }
        activityManager.updateActivity(activity);
      }
    }

    // Update user space activity of all member of space
    String[] members = space.getMembers();
    for (String member : members) {
      Identity identity =
          identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, member, false);
      String userSpaceActivityId =
          getStorage()
              .getProfileActivityId(identity.getProfile(), Profile.AttachedActivityType.RELATION);
      if (userSpaceActivityId != null) {
        ExoSocialActivity activity =
            (ExoSocialActivityImpl) activityManager.getActivity(userSpaceActivityId);
        if (activity != null) {
          int numberOfSpacesOfMember =
              getSpaceStorage().getNumberOfMemberPublicSpaces(identity.getRemoteId());
          Map<String, String> templateParams = activity.getTemplateParams();
          templateParams.put(NUMBER_OF_PUBLIC_SPACE, String.valueOf(numberOfSpacesOfMember));
          templateParams.put(
              BaseActivityProcessorPlugin.TEMPLATE_PARAM_TO_PROCESS, NUMBER_OF_PUBLIC_SPACE);
          activity.setTemplateParams(templateParams);

          if (numberOfSpacesOfMember > 1) {
            activity.setTitle("I now member of " + numberOfSpacesOfMember + " spaces");
            activity.setTitleId(USER_JOINED_PUBLIC_SPACES_TITLE_ID);
          } else {
            activity.setTitle("I now member of " + numberOfSpacesOfMember + " space");
            activity.setTitleId(USER_JOINED_PUBLIC_SPACE_TITLE_ID);
          }
          activityManager.updateActivity(activity);
        }
      }
    }
  }
 private ExoSocialActivity newActivity(
     Identity author, String title, String body, Map<String, String> templateParams) {
   ExoSocialActivity activity = new ExoSocialActivityImpl();
   activity.setTitle(CommonUtils.decodeSpecialCharToHTMLnumber(title));
   activity.setTitleId("add-question");
   activity.setBody(body);
   activity.setType(SPACE_APP_ID);
   activity.setTemplateParams(templateParams);
   activity.setUserId(author.getId());
   return activity;
 }
 private void updateActivity(ExoSocialActivity activity, Question question) {
   Map<String, String> activityTemplateParams =
       updateTemplateParams(
           new HashMap<String, String>(),
           question.getId(),
           ActivityUtils.getQuestionRate(question),
           ActivityUtils.getNbOfAnswers(question),
           ActivityUtils.getNbOfComments(question),
           question.getLanguage(),
           question.getLink(),
           Utils.getQuestionPoint(question));
   activity.setTemplateParams(activityTemplateParams);
   activity.setBody(null);
   activity.setTitle(null);
 }
Beispiel #7
0
  private static void updateMainActivity(
      ActivityManager activityManager, Node contentNode, ExoSocialActivity activity) {
    Map<String, String> activityParams = activity.getTemplateParams();
    String state;
    String nodeTitle;
    String nodeType = null;
    String nodeIconName = null;
    String documentTypeLabel;
    String currentVersion = null;
    TemplateService templateService = WCMCoreUtils.getService(TemplateService.class);
    try {
      nodeType = contentNode.getPrimaryNodeType().getName();
      documentTypeLabel = templateService.getTemplateLabel(nodeType);
    } catch (Exception e) {
      documentTypeLabel = "";
    }
    try {
      nodeTitle = org.exoplatform.ecm.webui.utils.Utils.getTitle(contentNode);
    } catch (Exception e1) {
      nodeTitle = "";
    }
    try {
      state =
          contentNode.hasProperty(CURRENT_STATE_PROP)
              ? contentNode.getProperty(CURRENT_STATE_PROP).getValue().getString()
              : "";
    } catch (Exception e) {
      state = "";
    }
    try {
      currentVersion = contentNode.getBaseVersion().getName();

      // TODO Must improve this hardcode later, need specification
      if (currentVersion.contains("jcr:rootVersion")) currentVersion = "0";
    } catch (Exception e) {
      currentVersion = "";
    }
    activityParams.put(ContentUIActivity.STATE, state);
    activityParams.put(ContentUIActivity.DOCUMENT_TYPE_LABEL, documentTypeLabel);
    activityParams.put(ContentUIActivity.DOCUMENT_TITLE, nodeTitle);
    activityParams.put(ContentUIActivity.DOCUMENT_VERSION, currentVersion);
    String summary = getSummary(contentNode);
    summary = getFirstSummaryLines(summary, MAX_SUMMARY_LINES_COUNT);
    activityParams.put(ContentUIActivity.DOCUMENT_SUMMARY, summary);
    activity.setTemplateParams(activityParams);
    activityManager.updateActivity(activity);
  }
  /**
   * creates a comment associated to updated fields
   *
   * @param userId
   * @param messagesParams
   * @return a comment object
   * @since activity-type
   */
  private ExoSocialActivity createComment(String userId, Map<String, String> messagesParams) {
    ExoSocialActivity newComment = new ExoSocialActivityImpl();
    newComment.isComment(true);
    newComment.setUserId(userId);
    newComment.setType("CALENDAR_ACTIVITY");
    StringBuilder fields = new StringBuilder();
    Map<String, String> data = new LinkedHashMap<String, String>();

    for (String field : messagesParams.keySet()) {
      String value = messagesParams.get(field);
      data.put(field, value); // store field changed and its new value
      fields.append("," + field);
    }
    String fieldsChanged = fields.toString().substring(1); // remove the first ","
    data.put(CALENDAR_FIELDS_CHANGED, fieldsChanged);
    newComment.setTitleId(fieldsChanged);
    newComment.setTemplateParams(data);
    //    newComment.setTitle(title.toString());
    return newComment;
  }
  private ExoSocialActivity saveActivity(
      Map<String, String> activityParams,
      ActivityManager activityManager,
      IdentityManager identityManager,
      Identity ownerIdentity,
      String remoteUser)
      throws ActivityStorageException, RepositoryException {
    Node node =
        getDocNode(
            activityParams.get(UIDocActivity.REPOSITORY),
            activityParams.get(UIDocActivity.WORKSPACE),
            activityParams.get(UIDocActivity.DOCPATH));
    String activity_type = UIDocActivity.ACTIVITY_TYPE;
    if (node.getPrimaryNodeType().getName().equals(NodetypeConstant.NT_FILE)) {
      activity_type = FILE_SPACES;
    }

    Identity userIdentity =
        identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, remoteUser, true);
    String title = activityParams.get(UIDocActivity.MESSAGE);
    if (title == null || title.length() == 0) {
      title = docActivityTitle;
    }
    ExoSocialActivity activity =
        new ExoSocialActivityImpl(userIdentity.getId(), activity_type, title, null);
    activity.setTemplateParams(activityParams);
    activityManager.saveActivityNoReturn(ownerIdentity, activity);

    String activityId = activity.getId();
    if (!StringUtils.isEmpty(activityId)) {
      ActivityTypeUtils.attachActivityId(node, activityId);
      node.save();
    }

    return activityManager.getActivity(activity.getId());
  }
  /**
   * Records an activity for user space based on space lifecyle event and the activity object.
   *
   * @param event the space life-cycle event
   * @param activityMessage the message of activity object
   * @param titleId the title of activity (comment)
   * @param templateParams
   */
  private void recordActivityForUserSpace(
      SpaceLifeCycleEvent event,
      String userSpaceActivityMessage,
      String titleId,
      Map<String, String> templateParams,
      boolean isJoined) {
    Space space = event.getSpace();
    if (space.getVisibility().equals(Space.HIDDEN)) {
      return;
    }
    Identity identity =
        identityManager.getOrCreateIdentity(
            OrganizationIdentityProvider.NAME, event.getTarget(), false);
    String activityId =
        getStorage()
            .getProfileActivityId(identity.getProfile(), Profile.AttachedActivityType.RELATION);

    // not go to create new with these kind of activities
    if (activityId == null) {
      return;
    }

    int numberOfSpacesOfMember =
        getSpaceStorage().getNumberOfMemberPublicSpaces(identity.getRemoteId());

    //
    ExoSocialActivity activity = null;
    if (activityId != null) {
      activity = (ExoSocialActivityImpl) activityManager.getActivity(activityId);
    }

    if (activity == null) {
      return;
    }

    templateParams.put(NUMBER_OF_PUBLIC_SPACE, String.valueOf(numberOfSpacesOfMember));
    templateParams.put(
        BaseActivityProcessorPlugin.TEMPLATE_PARAM_TO_PROCESS, NUMBER_OF_PUBLIC_SPACE);
    activity.setTemplateParams(templateParams);

    if (numberOfSpacesOfMember > 1) {
      activity.setTitle("I now member of " + numberOfSpacesOfMember + " spaces");
      activity.setTitleId(USER_JOINED_PUBLIC_SPACES_TITLE_ID);
    } else {
      activity.setTitle("I now member of " + numberOfSpacesOfMember + " space");
      activity.setTitleId(USER_JOINED_PUBLIC_SPACE_TITLE_ID);
    }

    if (activityId != null) {
      if (isJoined) {
        try {
          // Create comment when user join space
          ExoSocialActivity comment =
              createComment(
                  userSpaceActivityMessage,
                  titleId,
                  event.getSpace().getDisplayName(),
                  USER_ACTIVITIES_FOR_SPACE,
                  identity,
                  new LinkedHashMap<String, String>());
          activityManager.updateActivity(activity);
          activityManager.saveComment(activity, comment);
        } catch (Exception e) {
          LOG.debug("Run in case of activity deleted");
          activityId = null;
        }
      } else { // for Spec then left space have no affect on comments
        //
        activityManager.updateActivity(activity);
      }
    }
  }
Beispiel #11
0
  /**
   * @param node : activity raised from this source
   * @param activityMsgBundleKey
   * @param isSystemComment
   * @param systemComment the new value of System Posted activity, if (isSystemComment)
   *     systemComment can not be set to null, set to empty string instead of.
   * @throws Exception
   */
  public static ExoSocialActivity postFileActivity(
      Node node,
      String activityMsgBundleKey,
      boolean needUpdate,
      boolean isSystemComment,
      String systemComment)
      throws Exception {
    Object isSkipRaiseAct =
        DocumentContext.getCurrent().getAttributes().get(DocumentContext.IS_SKIP_RAISE_ACT);
    if (isSkipRaiseAct != null && Boolean.valueOf(isSkipRaiseAct.toString())) {
      return null;
    }
    if (!isSupportedContent(node)) {
      return null;
    }

    // get services
    ExoContainer container = ExoContainerContext.getCurrentContainer();
    ActivityManager activityManager =
        (ActivityManager) container.getComponentInstanceOfType(ActivityManager.class);
    IdentityManager identityManager =
        (IdentityManager) container.getComponentInstanceOfType(IdentityManager.class);
    ActivityCommonService activityCommonService =
        (ActivityCommonService) container.getComponentInstanceOfType(ActivityCommonService.class);

    SpaceService spaceService = WCMCoreUtils.getService(SpaceService.class);

    // refine to get the valid node
    refineNode(node);

    // get owner
    String activityOwnerId = getActivityOwnerId(node);
    String nodeActivityID = StringUtils.EMPTY;
    ExoSocialActivity exa = null;
    if (node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) {
      try {
        nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString();
        exa = activityManager.getActivity(nodeActivityID);
      } catch (Exception e) {
        LOG.info("No activity is deleted, return no related activity");
      }
    }
    ExoSocialActivity activity = null;
    String commentID;
    boolean commentFlag = false;
    if (node.isNodeType(MIX_COMMENT) && activityCommonService.isEditing(node)) {
      if (node.hasProperty(MIX_COMMENT_ID)) {
        commentID = node.getProperty(MIX_COMMENT_ID).getString();
        if (StringUtils.isNotBlank(commentID)) activity = activityManager.getActivity(commentID);
        commentFlag = (activity != null);
      }
    }
    if (activity == null) {
      activity =
          createActivity(
              identityManager,
              activityOwnerId,
              node,
              activityMsgBundleKey,
              FILE_SPACES,
              isSystemComment,
              systemComment);
    }

    if (exa != null) {
      if (commentFlag) {
        Map<String, String> paramsMap = activity.getTemplateParams();
        String paramMessage = paramsMap.get(ContentUIActivity.MESSAGE);
        String paramContent = paramsMap.get(ContentUIActivity.SYSTEM_COMMENT);
        if (!StringUtils.isEmpty(paramMessage)) {
          paramMessage += ActivityCommonService.VALUE_SEPERATOR + activityMsgBundleKey;
          if (StringUtils.isEmpty(systemComment)) {
            paramContent += ActivityCommonService.VALUE_SEPERATOR + " ";
          } else {
            paramContent += ActivityCommonService.VALUE_SEPERATOR + systemComment;
          }
        } else {
          paramMessage = activityMsgBundleKey;
          paramContent = systemComment;
        }
        paramsMap.put(ContentUIActivity.MESSAGE, paramMessage);
        paramsMap.put(ContentUIActivity.SYSTEM_COMMENT, paramContent);
        activity.setTemplateParams(paramsMap);
        activityManager.updateActivity(activity);
      } else {
        activityManager.saveComment(exa, activity);
        if (activityCommonService.isEditing(node)) {
          commentID = activity.getId();
          if (node.canAddMixin(MIX_COMMENT)) node.addMixin(MIX_COMMENT);
          if (node.isNodeType(MIX_COMMENT)) node.setProperty(MIX_COMMENT_ID, commentID);
        }
      }
      return activity;
    } else {
      String spaceName = getSpaceName(node);
      if (spaceName != null
          && spaceName.length() > 0
          && spaceService.getSpaceByPrettyName(spaceName) != null) {
        // post activity to space stream
        Identity spaceIdentity =
            identityManager.getOrCreateIdentity(SpaceIdentityProvider.NAME, spaceName, true);
        activityManager.saveActivityNoReturn(spaceIdentity, activity);
      } else if (activityOwnerId != null && activityOwnerId.length() > 0) {
        // post activity to user status stream
        Identity ownerIdentity =
            identityManager.getOrCreateIdentity(
                OrganizationIdentityProvider.NAME, activityOwnerId, true);
        activityManager.saveActivityNoReturn(ownerIdentity, activity);
      } else {
        return null;
      }
      String activityId = activity.getId();
      if (!StringUtils.isEmpty(activityId)) {
        ActivityTypeUtils.attachActivityId(node, activityId);
      }

      if (node.isNodeType(ActivityTypeUtils.EXO_ACTIVITY_INFO)) {
        try {
          nodeActivityID = node.getProperty(ActivityTypeUtils.EXO_ACTIVITY_ID).getString();
          exa = activityManager.getActivity(nodeActivityID);
        } catch (Exception e) {
          LOG.info("No activity is deleted, return no related activity");
        }
        if (exa != null && !commentFlag && isSystemComment) {
          activityManager.saveComment(exa, activity);
          if (activityCommonService.isEditing(node)) {
            commentID = activity.getId();
            if (node.canAddMixin(MIX_COMMENT)) node.addMixin(MIX_COMMENT);
            if (node.isNodeType(MIX_COMMENT)) node.setProperty(MIX_COMMENT_ID, commentID);
          }
        }
      }

      return activity;
    }
  }
  /**
   * adds comment to existing event activity
   *
   * @param event
   * @param calendarId
   * @param eventType
   * @param messagesParams
   */
  private void updateToActivity(
      CalendarEvent event,
      String calendarId,
      String eventType,
      Map<String, String> messagesParams) {
    try {
      Class.forName("org.exoplatform.social.core.space.spi.SpaceService");
    } catch (ClassNotFoundException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("eXo Social components not found!", e);
      }
      return;
    }
    if (calendarId == null
        || calendarId.indexOf(CalendarDataInitialize.SPACE_CALENDAR_ID_SUFFIX) < 0) {
      return;
    }
    try {
      IdentityManager identityM =
          (IdentityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(IdentityManager.class);
      ActivityManager activityM =
          (ActivityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(ActivityManager.class);
      SpaceService spaceService =
          (SpaceService)
              PortalContainer.getInstance().getComponentInstanceOfType(SpaceService.class);

      String spaceGroupId = Utils.getSpaceGroupIdFromCalendarId(calendarId);
      Space space = spaceService.getSpaceByGroupId(spaceGroupId);
      if (space != null) {
        String userId = ConversationState.getCurrent().getIdentity().getUserId();
        Identity spaceIdentity =
            identityM.getOrCreateIdentity(SpaceIdentityProvider.NAME, space.getPrettyName(), false);
        Identity userIdentity =
            identityM.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);

        ExoSocialActivity activity = null;

        if (event.getActivityId() != null) {
          activity = activityM.getActivity(event.getActivityId());
        }

        /*
         * if activity is still null, that means:
         * - activity was deleted
         * - or this event is a public event from plf 3.5, it has no activityId
         * In this case, we create new activity and add comments about the changes to the activity
         */
        if (activity == null) {

          // create activity
          ExoSocialActivity newActivity = new ExoSocialActivityImpl();
          newActivity.setUserId(userIdentity.getId());
          newActivity.setTitle(event.getSummary());
          newActivity.setBody(event.getDescription());
          newActivity.setType("cs-calendar:spaces");
          newActivity.setTemplateParams(makeActivityParams(event, calendarId, eventType));
          activityM.saveActivityNoReturn(spaceIdentity, newActivity);

          // add comments
          ExoSocialActivity newComment = createComment(userIdentity.getId(), messagesParams);
          activityM.saveComment(newActivity, newComment);

          // update activity id for event
          event.setActivityId(newActivity.getId());
          LOG.info(
              String.format(
                  "[CALENDAR] successfully re-created activity for event: %s", event.getSummary()));
        } else {
          activity.setTitle(event.getSummary());
          activity.setBody(event.getDescription());
          activity.setTemplateParams(makeActivityParams(event, calendarId, eventType));
          activityM.updateActivity(activity);
          ExoSocialActivity newComment = createComment(userIdentity.getId(), messagesParams);
          activityM.saveComment(activity, newComment);
          LOG.info(
              String.format(
                  "[CALENDAR] successfully added comment to activity of event: %s",
                  event.getSummary()));
        }
      }
    } catch (ExoSocialException e) {
      if (LOG.isDebugEnabled())
        LOG.error("Can not update Activity for space when event modified ", e);
    }
  }
 private void updateCommentTemplateParms(ExoSocialActivity comment, String link) {
   Map<String, String> commentTemplateParams = comment.getTemplateParams();
   if (commentTemplateParams == null) commentTemplateParams = new HashMap<String, String>();
   commentTemplateParams.put(LINK_KEY, link);
   comment.setTemplateParams(commentTemplateParams);
 }
  @Override
  public void saveQuestion(Question question, boolean isNew) {
    try {
      ExoContainer exoContainer = ExoContainerContext.getCurrentContainer();
      IdentityManager identityM =
          (IdentityManager) exoContainer.getComponentInstanceOfType(IdentityManager.class);
      ActivityManager activityM =
          (ActivityManager) exoContainer.getComponentInstanceOfType(ActivityManager.class);
      FAQService faqS = (FAQService) exoContainer.getComponentInstanceOfType(FAQService.class);
      Identity userIdentity =
          identityM.getOrCreateIdentity(
              OrganizationIdentityProvider.NAME, question.getAuthor(), false);
      Map<String, String> templateParams =
          updateTemplateParams(
              new HashMap<String, String>(),
              question.getId(),
              ActivityUtils.getQuestionRate(question),
              ActivityUtils.getNbOfAnswers(question),
              ActivityUtils.getNbOfComments(question),
              question.getLanguage(),
              question.getLink(),
              Utils.getQuestionPoint(question));
      String activityId = faqS.getActivityIdForQuestion(question.getId());

      String questionDetail = ActivityUtils.processContent(question.getDetail());
      // in case deleted activity, if isUpdate, we will re-create new activity and add a comment
      // associated
      boolean isUpdate = false;
      // UserHelper.checkValueUser(values)
      if (activityId != null) {
        isUpdate = true;
        try {
          ExoSocialActivity activity = activityM.getActivity(activityId);
          if (UserHelper.getUserByUserId(question.getAuthor()) == null) {
            userIdentity = identityM.getIdentity(activity.getPosterId(), false);
          }
          activity.setTitle(CommonUtils.decodeSpecialCharToHTMLnumber(question.getQuestion()));
          activity.setBody(questionDetail);
          activity.setTemplateParams(templateParams);
          activityM.updateActivity(activity);

          ExoSocialActivity comment = createCommentWhenUpdateQuestion(userIdentity, question);
          if (!"".equals(comment.getTitle())) {
            activityM.saveComment(activity, comment);
          }
        } catch (Exception e) {
          LOG.debug("Run in case of activity deleted and reupdate");
          activityId = null;
        }
      }
      if (activityId == null) {
        Identity streamOwner = null;
        String catId =
            (String)
                faqS.readQuestionProperty(
                    question.getId(), FAQNodeTypes.EXO_CATEGORY_ID, String.class);
        Identity spaceIdentity = getSpaceIdentity(catId);
        if (spaceIdentity != null) {
          // publish the activity in the space stream.
          streamOwner = spaceIdentity;
          templateParams.put(SPACE_GROUP_ID, ActivityUtils.getSpaceGroupId(catId));
        }
        List<String> categoryIds = faqS.getCategoryPath(catId);
        Collections.reverse(categoryIds);
        if (streamOwner == null) {
          streamOwner = userIdentity;
        }
        ExoSocialActivity activity =
            newActivity(userIdentity, question.getQuestion(), questionDetail, templateParams);
        activityM.saveActivityNoReturn(streamOwner, activity);
        faqS.saveActivityIdForQuestion(question.getId(), activity.getId());

        if (isUpdate) {
          ExoSocialActivity comment = createCommentWhenUpdateQuestion(userIdentity, question);
          if (!"".equals(comment.getTitle())) {
            activityM.saveComment(activity, comment);
          }
        }
      }
    } catch (Exception e) { // FQAService
      LOG.error("Can not record Activity for space when add new question ", e);
    }
  }
 @Override
 public void saveComment(String questionId, Comment cm, String language) {
   try {
     ExoContainer exoContainer = ExoContainerContext.getCurrentContainer();
     IdentityManager identityM =
         (IdentityManager) exoContainer.getComponentInstanceOfType(IdentityManager.class);
     ActivityManager activityM =
         (ActivityManager) exoContainer.getComponentInstanceOfType(ActivityManager.class);
     FAQService faqS = (FAQService) exoContainer.getComponentInstanceOfType(FAQService.class);
     Question question = faqS.getQuestionById(questionId);
     String message = ActivityUtils.processContent(cm.getComments());
     Identity userIdentity =
         identityM.getOrCreateIdentity(
             OrganizationIdentityProvider.NAME, cm.getCommentBy(), false);
     String activityId = faqS.getActivityIdForQuestion(questionId);
     if (activityId != null) {
       try {
         ExoSocialActivity activity = activityM.getActivity(activityId);
         ExoSocialActivityImpl comment = new ExoSocialActivityImpl();
         String commentActivityId = faqS.getActivityIdForComment(questionId, cm.getId(), language);
         Map<String, String> commentTemplateParams = new HashMap<String, String>();
         commentTemplateParams.put(LINK_KEY, cm.getId());
         if (commentActivityId != null) { // try to update activity's comment
           ExoSocialActivityImpl oldComment =
               (ExoSocialActivityImpl) activityM.getActivity(commentActivityId);
           if (oldComment != null) {
             comment = oldComment;
             comment.setTitle(message);
             comment.setTitleId("update-comment");
             activityM.updateActivity(comment);
           } else {
             commentActivityId = null;
           }
         }
         if (commentActivityId == null) { // create new activity's comment
           comment.setTemplateParams(commentTemplateParams);
           comment.setTitle(message);
           comment.setTitleId("add-comment");
           comment.setUserId(userIdentity.getId());
           updateActivity(activity, question);
           activityM.updateActivity(activity);
           activityM.saveComment(activity, comment);
           faqS.saveActivityIdForComment(questionId, cm.getId(), language, comment.getId());
         }
       } catch (Exception e) {
         LOG.debug("Run in case of activity deleted and reupdate");
         activityId = null;
       }
     }
     if (activityId == null) { // Create new activity for the question and add new comment
       saveQuestion(question, false);
       String newActivityId = faqS.getActivityIdForQuestion(questionId);
       ExoSocialActivity activity = activityM.getActivity(newActivityId);
       ExoSocialActivity comment = new ExoSocialActivityImpl();
       comment.setUserId(userIdentity.getId());
       Map<String, String> commentTemplateParams = new HashMap<String, String>();
       commentTemplateParams.put(LINK_KEY, cm.getId());
       comment.setTitle(message);
       comment.setTemplateParams(commentTemplateParams);
       activityM.saveComment(activity, comment);
     }
   } catch (Exception e) { // FQAService
     LOG.error("Can not record Activity for space when post comment ", e);
   }
 }