diff --git a/kudos-services/pom.xml b/kudos-services/pom.xml index 10297b111..5e5b6ee62 100644 --- a/kudos-services/pom.xml +++ b/kudos-services/pom.xml @@ -41,57 +41,19 @@ test-jar test + + org.springframework.boot + spring-boot-starter-test + test + + + com.vaadin.external.google + android-json + + + kudos-services - - - io.openapitools.swagger - swagger-maven-plugin - - true - - org.exoplatform.kudos.rest - - - - ${rest.api.doc.title} - ${rest.api.doc.version} - ${rest.api.doc.description} - - https://www.gnu.org/licenses/lgpl-3.0.en.html - LGPL - - - - - - - com.jcabi - jcabi-maven-plugin - - - org.apache.maven.plugins - maven-surefire-plugin - - - classpath:/conf/configuration.properties - hsqldb - org.apache.commons.logging.impl.SimpleLog - info - debug - warn - org.exoplatform.services.naming.SimpleContextFactory - org.exoplatform.services.log.impl.SimpleExoLogConfigurator - hsqldb - ${project.build.directory} - ${project.build.directory} - ${project.build.directory} - ${project.build.directory} - target/files - - - - diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/activity/KudosActivityTypePlugin.java b/kudos-services/src/main/java/io/meeds/kudos/activity/KudosActivityTypePlugin.java similarity index 57% rename from kudos-services/src/main/java/org/exoplatform/kudos/activity/KudosActivityTypePlugin.java rename to kudos-services/src/main/java/io/meeds/kudos/activity/KudosActivityTypePlugin.java index e9e44a46f..95878cccb 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/activity/KudosActivityTypePlugin.java +++ b/kudos-services/src/main/java/io/meeds/kudos/activity/KudosActivityTypePlugin.java @@ -1,8 +1,8 @@ -/** +/* * This file is part of the Meeds project (https://meeds.io/). - * - * Copyright (C) 2020 - 2023 Meeds Association contact@meeds.io - * + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either @@ -11,29 +11,46 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.activity; +package io.meeds.kudos.activity; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; +import org.exoplatform.container.xml.ValueParam; import org.exoplatform.social.core.ActivityTypePlugin; import org.exoplatform.social.core.activity.model.ExoSocialActivity; +import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.utils.MentionUtils; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; +import io.meeds.kudos.service.utils.Utils; + +import jakarta.annotation.PostConstruct; + +@Component public class KudosActivityTypePlugin extends ActivityTypePlugin { - private KudosService kudosService; + @Autowired + private ActivityManager activityManager; - public KudosActivityTypePlugin(KudosService kudosService, - InitParams params) { - super(params); - this.kudosService = kudosService; + @Autowired + private KudosService kudosService; + + public KudosActivityTypePlugin() { + super(initParams()); + } + + @PostConstruct + public void init() { + activityManager.addActivityTypePlugin(this); } @Override @@ -43,8 +60,8 @@ public boolean isEnableNotification(ExoSocialActivity activity, String username) } else { Kudos kudos = this.kudosService.getKudosByActivityId(Long.parseLong(activity.getId().replace("comment", ""))); return kudos != null - && !StringUtils.equals(kudos.getReceiverId(), username) - && !StringUtils.equals(kudos.getSenderId(), username); + && !StringUtils.equals(kudos.getReceiverId(), username) + && !StringUtils.equals(kudos.getSenderId(), username); } } @@ -54,4 +71,17 @@ public String getActivityTitle(ExoSocialActivity activity) { return kudos == null ? activity.getTitle() : MentionUtils.substituteUsernames(kudos.getMessage()); } + private static InitParams initParams() { + InitParams initParams = new InitParams(); + ValueParam param = new ValueParam(); + param.setName("type"); + param.setValue(Utils.KUDOS_ACTIVITY_COMMENT_TYPE); + initParams.addParameter(param); + param = new ValueParam(); + param.setName("enableNotification"); + param.setValue("true"); + initParams.addParameter(param); + return initParams; + } + } diff --git a/kudos-services/src/main/java/io/meeds/kudos/activity/processor/ActivityKudosProcessor.java b/kudos-services/src/main/java/io/meeds/kudos/activity/processor/ActivityKudosProcessor.java new file mode 100644 index 000000000..55701345e --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/activity/processor/ActivityKudosProcessor.java @@ -0,0 +1,100 @@ +/* + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.activity.processor; + +import java.util.HashMap; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import org.exoplatform.container.xml.InitParams; +import org.exoplatform.container.xml.ValueParam; +import org.exoplatform.portal.config.UserPortalConfigService; +import org.exoplatform.social.core.BaseActivityProcessorPlugin; +import org.exoplatform.social.core.activity.model.ExoSocialActivity; +import org.exoplatform.social.core.manager.ActivityManager; +import org.exoplatform.social.core.utils.MentionUtils; + +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; + +@Component +public class ActivityKudosProcessor extends BaseActivityProcessorPlugin { + + @Autowired + private ActivityManager activityManager; + + @Autowired + private UserPortalConfigService userPortalConfigService; + + @Autowired + private KudosService kudosService; + + private String defaultPortal; + + public ActivityKudosProcessor() { + super(initParams()); + } + + @Override + public String getName() { + return "ActivityKudosProcessor"; + } + + @PostConstruct + public void init() { + defaultPortal = userPortalConfigService.getMetaPortal(); + activityManager.addProcessor(this); + } + + @Override + public void processActivity(ExoSocialActivity activity) { + if (activity.isComment()) { + return; + } + if (activity.getLinkedProcessedEntities() == null) { + activity.setLinkedProcessedEntities(new HashMap<>()); + } + @SuppressWarnings("unchecked") + List linkedKudosList = (List) activity.getLinkedProcessedEntities().get("kudosList"); + if (linkedKudosList == null) { + linkedKudosList = kudosService.getKudosListOfActivity(activity.getId()); + activity.getLinkedProcessedEntities().put("kudosList", linkedKudosList); + } + + if (linkedKudosList != null) { + for (Kudos kudos : linkedKudosList) { + kudos.setMessage(MentionUtils.substituteUsernames(defaultPortal, kudos.getMessage())); + } + } + } + + private static InitParams initParams() { + InitParams initParams = new InitParams(); + ValueParam param = new ValueParam(); + param.setName("priority"); + param.setValue("20"); + initParams.addParameter(param); + return initParams; + } + +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/dao/KudosDAO.java b/kudos-services/src/main/java/io/meeds/kudos/dao/KudosDAO.java new file mode 100644 index 000000000..38f5eb1c3 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/dao/KudosDAO.java @@ -0,0 +1,96 @@ +/* + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.dao; + +import java.util.List; + +import org.springframework.data.domain.Limit; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import io.meeds.kudos.entity.KudosEntity; +import io.meeds.kudos.entity.KudosReceiverResult; + +public interface KudosDAO extends JpaRepository { + + List findByCreatedDateBetweenOrderByCreatedDateDesc(long startDateInSeconds, + long endDateInSeconds, + Limit limit); + + List findByCreatedDateBetweenAndEntityTypeOrderByCreatedDateDesc(long startDateInSeconds, + long endDateInSeconds, + int entityType, + Limit limit); + + List findByEntityTypeAndEntityIdOrderByCreatedDateDesc(int entityType, long entityId, Limit limit); + + List findByCreatedDateBetweenAndReceiverIdAndIsReceiverUserOrderByCreatedDateDesc(long startDateInSeconds, + long endDateInSeconds, + long receiverId, + boolean isReceiverUser, + Limit limit); + + List findByCreatedDateBetweenAndSenderIdOrderByCreatedDateDesc(long startDateInSeconds, + long endDateInSeconds, + long senderId, + Limit limit); + + KudosEntity findByActivityId(Long activityId); + + @Query(""" + SELECT k FROM Kudos k + WHERE + k.activityId = ?1 + OR + (k.entityType in (?2) AND (k.parentEntityId = ?1 OR k.entityId in ?1)) + """) + List findKudosListOfActivity(Long activityId, List entityTypes); + + long countByEntityTypeAndEntityId(int entityType, long entityId); + + long countByEntityTypeAndEntityIdAndSenderId(int entityType, long entityId, long senderId); + + long countByCreatedDateBetweenAndReceiverIdAndIsReceiverUser(long startDateInSeconds, + long endDateInSeconds, + long receiverId, + boolean isReceiverUser); + + @Query(""" + SELECT COUNT(k.id) FROM Kudos k + WHERE + k.activityId = ?1 + OR + (k.entityType in (?2) AND (k.parentEntityId = ?1 OR k.entityId in ?1)) + """) + long countKudosListOfActivity(Long activityId, List entityTypes); + + long countByCreatedDateBetweenAndSenderId(long startDateInSeconds, long endDateInSeconds, long senderId); + + @Query(""" + SELECT new io.meeds.kudos.entity.KudosReceiverResult(k.receiverId, COUNT(k)) from Kudos k + WHERE k.createdDate >= ?1 + AND k.createdDate < ?2 + AND k.receiverId IN ?3 + GROUP BY k.receiverId + """) + List countByCreatedDateBetweenAndReceiverIdIn(long startDateInSeconds, + long endDateInSeconds, + List receiversId); + +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/entity/KudosEntity.java b/kudos-services/src/main/java/io/meeds/kudos/entity/KudosEntity.java new file mode 100644 index 000000000..9ed43232b --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/entity/KudosEntity.java @@ -0,0 +1,147 @@ +/* + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.entity; + +import java.io.Serializable; + +import jakarta.persistence.*; + +import org.hibernate.annotations.DynamicUpdate; + +@Entity(name = "Kudos") +@DynamicUpdate +@Table(name = "ADDONS_KUDOS") +public class KudosEntity implements Serializable { + + private static final long serialVersionUID = -8272292325540761902L; + + @Id + @SequenceGenerator(name = "SEQ_ADDONS_KUDOS_ID", sequenceName = "SEQ_ADDONS_KUDOS_ID", allocationSize = 1) + @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_ADDONS_KUDOS_ID") + @Column(name = "KUDOS_ID") + private Long id; + + @Column(name = "SENDER_ID", nullable = false) + public long senderId; + + @Column(name = "RECEIVER_ID", nullable = false) + public long receiverId; + + @Column(name = "IS_RECEIVER_USER", nullable = false) + public boolean isReceiverUser; + + @Column(name = "PARENT_ENTITY_ID", nullable = true) + public Long parentEntityId; + + @Column(name = "ENTITY_ID", nullable = false) + public long entityId; + + @Column(name = "ENTITY_TYPE", nullable = false) + public int entityType; + + @Column(name = "ACTIVITY_ID") + public Long activityId; + + @Column(name = "MESSAGE", nullable = true) + public String message; + + @Column(name = "CREATED_DATE", nullable = false) + public long createdDate; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public long getSenderId() { + return senderId; + } + + public void setSenderId(long senderId) { + this.senderId = senderId; + } + + public long getReceiverId() { + return receiverId; + } + + public void setReceiverId(long receiverId) { + this.receiverId = receiverId; + } + + public boolean isReceiverUser() { + return isReceiverUser; + } + + public void setReceiverUser(boolean isReceiverUser) { + this.isReceiverUser = isReceiverUser; + } + + public long getEntityId() { + return entityId; + } + + public void setEntityId(long entityId) { + this.entityId = entityId; + } + + public int getEntityType() { + return entityType; + } + + public void setEntityType(int entityType) { + this.entityType = entityType; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(long createdDate) { + this.createdDate = createdDate; + } + + public Long getParentEntityId() { + return parentEntityId; + } + + public void setParentEntityId(Long parentEntityId) { + this.parentEntityId = parentEntityId; + } + + public long getActivityId() { + return activityId == null ? 0 : activityId; + } + + public void setActivityId(long activityId) { + this.activityId = activityId; + } + +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/entity/KudosReceiverResult.java b/kudos-services/src/main/java/io/meeds/kudos/entity/KudosReceiverResult.java new file mode 100644 index 000000000..8283b8782 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/entity/KudosReceiverResult.java @@ -0,0 +1,34 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.entity; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class KudosReceiverResult { + + public long receiverId; + + public long count; + +} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/listener/GamificationIntegrationListener.java b/kudos-services/src/main/java/io/meeds/kudos/listener/GamificationIntegrationListener.java similarity index 75% rename from kudos-services/src/main/java/org/exoplatform/kudos/listener/GamificationIntegrationListener.java rename to kudos-services/src/main/java/io/meeds/kudos/listener/GamificationIntegrationListener.java index c39f34534..cf799dbe0 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/listener/GamificationIntegrationListener.java +++ b/kudos-services/src/main/java/io/meeds/kudos/listener/GamificationIntegrationListener.java @@ -1,7 +1,7 @@ -/** +/* * This file is part of the Meeds project (https://meeds.io/). * - * Copyright (C) 2020 - 2023 Meeds Association contact@meeds.io + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public @@ -11,45 +11,58 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.listener; +package io.meeds.kudos.listener; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_CANCEL_EVENT; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_GENERIC_EVENT; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_OBJECT_TYPE; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_RECEIVE_KUDOS_EVENT_NAME; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_SEND_KUDOS_EVENT_NAME; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_ACTIVITY_EVENT; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_CANCEL_ACTIVITY_EVENT; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_CANCEL_EVENT; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_GENERIC_EVENT; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_OBJECT_TYPE; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_RECEIVE_KUDOS_EVENT_NAME; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_SEND_KUDOS_EVENT_NAME; +import static io.meeds.kudos.service.utils.Utils.KUDOS_ACTIVITY_EVENT; +import static io.meeds.kudos.service.utils.Utils.KUDOS_CANCEL_ACTIVITY_EVENT; import java.util.HashMap; import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + import org.exoplatform.commons.api.persistence.ExoTransactional; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; import org.exoplatform.services.listener.Asynchronous; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.listener.ListenerService; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; + /** * A listener to add comment or activity */ @Asynchronous +@Component +@Profile("gamification") public class GamificationIntegrationListener extends Listener { - private ListenerService listenerService; + @Autowired + private ListenerService listenerService; - public GamificationIntegrationListener(ListenerService listenerService) { - this.listenerService = listenerService; + @PostConstruct + public void init() { + listenerService.addListener("exo.kudos.activity", this); + listenerService.addListener("kudos.cancel.activity", this); } - @Override @ExoTransactional + @Override public void onEvent(Event event) throws Exception { Kudos kudos = event.getData(); String eventName = event.getEventName(); diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosActivityListener.java b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosActivityListener.java similarity index 58% rename from kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosActivityListener.java rename to kudos-services/src/main/java/io/meeds/kudos/listener/KudosActivityListener.java index e63398910..9396a6b3b 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosActivityListener.java +++ b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosActivityListener.java @@ -1,12 +1,32 @@ -package org.exoplatform.kudos.listener; +/* + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.listener; + +import static io.meeds.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE; +import java.util.List; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; import org.exoplatform.commons.exception.ObjectNotFoundException; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.activity.ActivityLifeCycleEvent; @@ -14,42 +34,43 @@ import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.manager.ActivityManager; -import java.util.List; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; /** * A listener to propagate comment or activity modification to Kudos stored * message */ +@Component public class KudosActivityListener extends ActivityListenerPlugin { private static final Log LOG = ExoLogger.getLogger(KudosActivityListener.class); - private ActivityManager activityManager; + @Autowired + private ActivityManager activityManager; - private KudosService kudosService; + @Autowired + private KudosService kudosService; - public KudosActivityListener(KudosService kudosService, ActivityManager activityManager) { - this.kudosService = kudosService; - this.activityManager = activityManager; - } - - @Override - public void saveActivity(ActivityLifeCycleEvent activityLifeCycleEvent) { - // NOT needed + @PostConstruct + public void init() { + activityManager.addActivityEventListener(this); } @Override public void updateActivity(ActivityLifeCycleEvent activityLifeCycleEvent) { ExoSocialActivity activity = activityLifeCycleEvent.getSource(); if (activity != null && StringUtils.equals(activity.getType(), KUDOS_ACTIVITY_COMMENT_TYPE)) { - long activityId = org.exoplatform.kudos.service.utils.Utils.getActivityId(activity.getId()); + long activityId = io.meeds.kudos.service.utils.Utils.getActivityId(activity.getId()); Kudos kudos = kudosService.getKudosByActivityId(activityId); if (kudos != null) { String newMessage = activity.getTitle(); kudos.setMessage(newMessage); kudosService.updateKudos(kudos); - org.exoplatform.kudos.service.utils.Utils.computeKudosActivityProperties(activity, kudos); + io.meeds.kudos.service.utils.Utils.computeKudosActivityProperties(activity, kudos); this.activityManager.updateActivity(activity, false); } } @@ -64,11 +85,6 @@ public void deleteActivity(ActivityLifeCycleEvent activityLifeCycleEvent) { } } - @Override - public void saveComment(ActivityLifeCycleEvent activityLifeCycleEvent) { - // NOT needed - } - @Override public void deleteComment(ActivityLifeCycleEvent activityLifeCycleEvent) { // Same as activity processing @@ -80,16 +96,6 @@ public void updateComment(ActivityLifeCycleEvent activityLifeCycleEvent) { updateActivity(activityLifeCycleEvent); } - @Override - public void likeActivity(ActivityLifeCycleEvent activityLifeCycleEvent) { - // NOT needed - } - - @Override - public void likeComment(ActivityLifeCycleEvent activityLifeCycleEvent) { - // NOT needed - } - private void deleteLinkedKudos(List linkedKudosList) { linkedKudosList.forEach(kudos -> { try { diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosCanceledListener.java b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosCanceledListener.java similarity index 63% rename from kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosCanceledListener.java rename to kudos-services/src/main/java/io/meeds/kudos/listener/KudosCanceledListener.java index 81ea664f1..cdee060a4 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosCanceledListener.java +++ b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosCanceledListener.java @@ -1,42 +1,56 @@ /** * This file is part of the Meeds project (https://meeds.io/). * - * Copyright (C) 2020 - 2023 Meeds Association contact@meeds.io + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.listener; +package io.meeds.kudos.listener; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; +import org.exoplatform.services.listener.ListenerService; import org.exoplatform.social.core.manager.ActivityManager; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; + +@Component public class KudosCanceledListener extends Listener { - private PortalContainer container; + @Autowired + private ActivityManager activityManager; + + @Autowired + private ListenerService listenerService; - public KudosCanceledListener(PortalContainer container) { - this.container = container; + @PostConstruct + public void init() { + listenerService.addListener("kudos.cancel.activity", this); } @Override public void onEvent(Event event) throws Exception { Kudos kudos = event.getData(); if (kudos != null && kudos.getActivityId() > 0) { - container.getComponentInstanceOfType(ActivityManager.class).deleteActivity(String.valueOf(kudos.getActivityId())); + activityManager.deleteActivity(String.valueOf(kudos.getActivityId())); } } diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosSentActivityGeneratorListener.java b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosSentActivityGeneratorListener.java similarity index 70% rename from kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosSentActivityGeneratorListener.java rename to kudos-services/src/main/java/io/meeds/kudos/listener/KudosSentActivityGeneratorListener.java index 1fd30d791..12e786fdc 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosSentActivityGeneratorListener.java +++ b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosSentActivityGeneratorListener.java @@ -1,13 +1,33 @@ -package org.exoplatform.kudos.listener; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.listener; -import static org.exoplatform.kudos.service.utils.Utils.SPACE_ACCOUNT_TYPE; +import static io.meeds.kudos.service.utils.Utils.SPACE_ACCOUNT_TYPE; import org.apache.commons.lang3.StringUtils; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.service.KudosService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; +import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.activity.model.ExoSocialActivity; @@ -20,19 +40,31 @@ import org.exoplatform.social.core.storage.cache.CachedActivityStorage; import org.exoplatform.social.notification.Utils; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosEntityType; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; + /** * A listener to add comment or activity */ +@Component public class KudosSentActivityGeneratorListener extends Listener { private static final Log LOG = ExoLogger.getLogger(KudosSentActivityGeneratorListener.class); + @Autowired private ActivityStorage activityStorage; + @Autowired private ActivityManager activityManager; - public KudosSentActivityGeneratorListener(ActivityManager activityManager, ActivityStorage activityStorage) { - this.activityManager = activityManager; - this.activityStorage = activityStorage; + @Autowired + private ListenerService listenerService; + + @PostConstruct + public void init() { + listenerService.addListener("exo.kudos.sent", this); } @Override @@ -64,7 +96,7 @@ public void onEvent(Event event) throws Exception { // NOSO } ExoSocialActivity activityComment = createActivity(kudos, parentCommentId); activityManager.saveComment(activity, activityComment); - long commentId = org.exoplatform.kudos.service.utils.Utils.getActivityId(activityComment.getId()); + long commentId = io.meeds.kudos.service.utils.Utils.getActivityId(activityComment.getId()); kudos.setActivityId(commentId); kudosService.updateKudosGeneratedActivityId(kudos.getTechnicalId(), kudos.getActivityId()); @@ -91,7 +123,7 @@ public void onEvent(Event event) throws Exception { // NOSO } else { activityManager.saveActivityNoReturn(owner, activity); kudosService.updateKudosGeneratedActivityId(kudos.getTechnicalId(), - org.exoplatform.kudos.service.utils.Utils.getActivityId(activity.getId())); + io.meeds.kudos.service.utils.Utils.getActivityId(activity.getId())); clearActivityCached(activity.getId()); } } @@ -100,11 +132,11 @@ public void onEvent(Event event) throws Exception { // NOSO private ExoSocialActivity createActivity(Kudos kudos, String parentCommentId) { ExoSocialActivityImpl activity = new ExoSocialActivityImpl(); activity.setParentCommentId(parentCommentId); - activity.setType(org.exoplatform.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE); + activity.setType(io.meeds.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE); activity.setTitle(kudos.getMessage()); activity.setBody("Kudos to " + kudos.getReceiverFullName()); activity.setUserId(kudos.getSenderIdentityId()); - org.exoplatform.kudos.service.utils.Utils.computeKudosActivityProperties(activity, kudos); + io.meeds.kudos.service.utils.Utils.computeKudosActivityProperties(activity, kudos); return activity; } diff --git a/kudos-services/src/main/java/io/meeds/kudos/listener/KudosSentNotificationListener.java b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosSentNotificationListener.java new file mode 100644 index 000000000..2c566b3e0 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/listener/KudosSentNotificationListener.java @@ -0,0 +1,69 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.listener; + +import static io.meeds.kudos.service.utils.Utils.KUDOS_DETAILS_PARAMETER; +import static io.meeds.kudos.service.utils.Utils.KUDOS_RECEIVER_NOTIFICATION_ID; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import org.exoplatform.commons.api.notification.NotificationContext; +import org.exoplatform.commons.api.notification.model.PluginKey; +import org.exoplatform.commons.notification.impl.NotificationContextImpl; +import org.exoplatform.services.listener.Event; +import org.exoplatform.services.listener.Listener; +import org.exoplatform.services.listener.ListenerService; +import org.exoplatform.services.log.ExoLogger; +import org.exoplatform.services.log.Log; + +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; + +/** + * A listener to send notification after sending a new Kudos + */ +@Component +public class KudosSentNotificationListener extends Listener { + + private static final Log LOG = ExoLogger.getLogger(KudosSentNotificationListener.class); + + @Autowired + private ListenerService listenerService; + + @PostConstruct + public void init() { + listenerService.addListener("exo.kudos.sent", this); + } + + @Override + public void onEvent(Event event) throws Exception { + Kudos kudos = event.getData(); + try { + NotificationContext ctx = NotificationContextImpl.cloneInstance(); + ctx.append(KUDOS_DETAILS_PARAMETER, kudos); + ctx.getNotificationExecutor().with(ctx.makeCommand(PluginKey.key(KUDOS_RECEIVER_NOTIFICATION_ID))).execute(ctx); + } catch (Exception e) { + LOG.warn("Error sending notification for Kudos with id " + kudos.getTechnicalId(), e); + } + } +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/listener/ProfileUpdateListener.java b/kudos-services/src/main/java/io/meeds/kudos/listener/ProfileUpdateListener.java new file mode 100644 index 000000000..0e64338d1 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/listener/ProfileUpdateListener.java @@ -0,0 +1,88 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.listener; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import org.exoplatform.social.core.manager.IdentityManager; +import org.exoplatform.social.core.profile.ProfileLifeCycleEvent; +import org.exoplatform.social.core.profile.ProfileListenerPlugin; +import org.exoplatform.social.core.storage.api.ActivityStorage; +import org.exoplatform.social.core.storage.cache.CachedActivityStorage; + +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; + +@Component +@AllArgsConstructor +@NoArgsConstructor +public class ProfileUpdateListener extends ProfileListenerPlugin { + + @Autowired + private ActivityStorage activityStorage; + + @Autowired + private KudosService kudosService; + + @Autowired + private IdentityManager identityManager; + + @PostConstruct + public void init() { + identityManager.registerProfileListener(this); + } + + @Override + public void avatarUpdated(ProfileLifeCycleEvent event) { + clearUserActivitiesCache(event); + } + + @Override + public void contactSectionUpdated(ProfileLifeCycleEvent event) { + clearUserActivitiesCache(event); + } + + private void clearUserActivitiesCache(ProfileLifeCycleEvent event) { + String userId = event.getProfile().getIdentity().getId(); + this.clearUserActivitiesCache(userId); + } + + private void clearUserActivitiesCache(String userId) { + long count = kudosService.countKudosByPeriodAndReceiver(Long.parseLong(userId), 0, System.currentTimeMillis()); + if (count > 0) { + List kudosList = kudosService.getKudosByPeriodAndReceiver(Long.parseLong(userId), + 0, + System.currentTimeMillis(), + (int) count); + if (kudosList == null || kudosList.isEmpty()) + return; + kudosList.stream() + .forEach(kudos -> ((CachedActivityStorage) activityStorage).clearActivityCached(String.valueOf(kudos.getActivityId()))); + } + } + +} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/listener/analytics/KudosSentListener.java b/kudos-services/src/main/java/io/meeds/kudos/listener/analytics/KudosSentListener.java similarity index 78% rename from kudos-services/src/main/java/org/exoplatform/kudos/listener/analytics/KudosSentListener.java rename to kudos-services/src/main/java/io/meeds/kudos/listener/analytics/KudosSentListener.java index 245e32efa..6ef145bf8 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/listener/analytics/KudosSentListener.java +++ b/kudos-services/src/main/java/io/meeds/kudos/listener/analytics/KudosSentListener.java @@ -1,34 +1,36 @@ -/* +/** * This file is part of the Meeds project (https://meeds.io/). * - * Copyright (C) 2022 Meeds Association contact@meeds.io + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.listener.analytics; +package io.meeds.kudos.listener.analytics; import static io.meeds.analytics.utils.AnalyticsUtils.addSpaceStatistics; import static io.meeds.analytics.utils.AnalyticsUtils.getIdentity; import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; import org.exoplatform.services.listener.Asynchronous; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; +import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.social.core.activity.model.ActivityStream; @@ -44,29 +46,35 @@ import io.meeds.analytics.model.StatisticData; import io.meeds.analytics.utils.AnalyticsUtils; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +import jakarta.annotation.PostConstruct; @Asynchronous +@Component +@Profile("analytics") public class KudosSentListener extends Listener { private static final Log LOG = ExoLogger.getLogger(KudosSentListener.class); - private PortalContainer container; - + @Autowired private ActivityManager activityManager; + @Autowired private SpaceService spaceService; - public KudosSentListener() { - this.container = PortalContainer.getInstance(); + @Autowired + private ListenerService listenerService; + + @PostConstruct + public void init() { + listenerService.addListener("exo.kudos.activity", this); } @Override - public void onEvent(Event event) throws Exception { + public void onEvent(Event event) throws Exception { // NOSONAR Kudos kudos = event.getData(); - addEventStatistic(kudos); - } - - private void addEventStatistic(Kudos kudos) { long activityId = kudos.getActivityId(); long streamIdentityId = 0; boolean receiverChanged = false; @@ -78,12 +86,12 @@ private void addEventStatistic(Kudos kudos) { StatisticData statisticData = new StatisticData(); if (activityId > 0) { - ExoSocialActivity activity = getActivityManager().getActivity(RDBMSActivityStorageImpl.COMMENT_PREFIX + activityId); + ExoSocialActivity activity = activityManager.getActivity(RDBMSActivityStorageImpl.COMMENT_PREFIX + activityId); if (activity == null) { - activity = getActivityManager().getActivity(String.valueOf(activityId)); + activity = activityManager.getActivity(String.valueOf(activityId)); } if (activity != null) { - ExoSocialActivity parentActivity = getActivityManager().getParentActivity(activity); + ExoSocialActivity parentActivity = activityManager.getParentActivity(activity); if (parentActivity != null) { activity = parentActivity; } @@ -115,14 +123,14 @@ private void addEventStatistic(Kudos kudos) { if (streamIdentity != null) { streamIdentityId = Long.parseLong(streamIdentity.getId()); if (StringUtils.equals(streamIdentity.getProviderId(), SpaceIdentityProvider.NAME)) { - Space space = getSpaceService().getSpaceByPrettyName(streamIdentity.getRemoteId()); + Space space = spaceService.getSpaceByPrettyName(streamIdentity.getRemoteId()); addSpaceStatistics(statisticData, space); } } } // kudos sent for a user in a chosen audience if (kudos.getSpacePrettyName() != null) { - Space space = getSpaceService().getSpaceByPrettyName(kudos.getSpacePrettyName()); + Space space = spaceService.getSpaceByPrettyName(kudos.getSpacePrettyName()); Identity spaceIdentity = getIdentity(SpaceIdentityProvider.NAME, kudos.getSpacePrettyName()); if (spaceIdentity != null) { streamIdentityId = Long.parseLong(spaceIdentity.getId()); @@ -150,17 +158,4 @@ private void addEventStatistic(Kudos kudos) { AnalyticsUtils.addStatisticData(statisticData); } - public SpaceService getSpaceService() { - if (spaceService == null) { - spaceService = this.container.getComponentInstanceOfType(SpaceService.class); - } - return spaceService; - } - - public ActivityManager getActivityManager() { - if (activityManager == null) { - activityManager = this.container.getComponentInstanceOfType(ActivityManager.class); - } - return activityManager; - } } diff --git a/kudos-services/src/main/java/io/meeds/kudos/model/AccountSettings.java b/kudos-services/src/main/java/io/meeds/kudos/model/AccountSettings.java new file mode 100644 index 000000000..6822882f8 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/model/AccountSettings.java @@ -0,0 +1,33 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; + +import lombok.*; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class AccountSettings { + + private boolean disabled; + + private long remainingKudos; + +} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/model/GlobalSettings.java b/kudos-services/src/main/java/io/meeds/kudos/model/GlobalSettings.java similarity index 77% rename from kudos-services/src/main/java/org/exoplatform/kudos/model/GlobalSettings.java rename to kudos-services/src/main/java/io/meeds/kudos/model/GlobalSettings.java index 331a7ec06..e72341f14 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/model/GlobalSettings.java +++ b/kudos-services/src/main/java/io/meeds/kudos/model/GlobalSettings.java @@ -1,4 +1,23 @@ -package org.exoplatform.kudos.model; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; import java.time.LocalDateTime; @@ -65,8 +84,6 @@ public static final GlobalSettings parseStringToObject(String jsonString) { try { JSONObject jsonObject = new JSONObject(jsonString); GlobalSettings globalSettings = new GlobalSettings(); - globalSettings.setAccessPermission(jsonObject.has(ACCESS_PERMISSION_PARAM) ? jsonObject.getString(ACCESS_PERMISSION_PARAM) - : null); globalSettings.setKudosPerPeriod(jsonObject.has(KUDOS_PER_PERIOD_PARAM) ? jsonObject.getLong(KUDOS_PER_PERIOD_PARAM) : 0); globalSettings.setKudosPeriodType(jsonObject.has(KUDOS_PERIOD_TYPE_PARAM) ? KudosPeriodType.valueOf(jsonObject.getString(KUDOS_PERIOD_TYPE_PARAM) .toUpperCase()) diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/model/Kudos.java b/kudos-services/src/main/java/io/meeds/kudos/model/Kudos.java similarity index 56% rename from kudos-services/src/main/java/org/exoplatform/kudos/model/Kudos.java rename to kudos-services/src/main/java/io/meeds/kudos/model/Kudos.java index 7f82aab79..8d9457e6f 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/model/Kudos.java +++ b/kudos-services/src/main/java/io/meeds/kudos/model/Kudos.java @@ -1,4 +1,23 @@ -package org.exoplatform.kudos.model; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; import java.io.Serializable; diff --git a/kudos-services/src/main/java/io/meeds/kudos/model/KudosEntityType.java b/kudos-services/src/main/java/io/meeds/kudos/model/KudosEntityType.java new file mode 100644 index 000000000..ab29ed30f --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/model/KudosEntityType.java @@ -0,0 +1,24 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; + +public enum KudosEntityType { + ACTIVITY, COMMENT, USER_PROFILE, USER_TIPTIP, SPACE_PROFILE, SPACE_TIPTIP, NONE +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/model/KudosList.java b/kudos-services/src/main/java/io/meeds/kudos/model/KudosList.java new file mode 100644 index 000000000..5ca62e60d --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/model/KudosList.java @@ -0,0 +1,38 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; + +import java.io.Serializable; +import java.util.List; + +import lombok.Data; + +@Data +public class KudosList implements Serializable { + + private static final long serialVersionUID = 5173858331264945555L; + + private List kudos; + + private long limit; + + private long size; + +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/model/KudosPeriod.java b/kudos-services/src/main/java/io/meeds/kudos/model/KudosPeriod.java new file mode 100644 index 000000000..94a4aef8d --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/model/KudosPeriod.java @@ -0,0 +1,52 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; + +import org.json.JSONException; +import org.json.JSONObject; + +import lombok.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class KudosPeriod { + + private long startDateInSeconds; + + private long endDateInSeconds; + + public JSONObject toJSONObject() { + JSONObject jsonObject = new JSONObject(); + try { + jsonObject.put("startDateInSeconds", startDateInSeconds); + jsonObject.put("endDateInSeconds", endDateInSeconds); + } catch (JSONException e) { + throw new IllegalStateException("Error while converting Object to JSON", e); + } + return jsonObject; + } + + @Override + public String toString() { + return toJSONObject().toString(); + } + +} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosPeriodType.java b/kudos-services/src/main/java/io/meeds/kudos/model/KudosPeriodType.java similarity index 69% rename from kudos-services/src/main/java/org/exoplatform/kudos/model/KudosPeriodType.java rename to kudos-services/src/main/java/io/meeds/kudos/model/KudosPeriodType.java index 724d34d4b..b03dffffc 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosPeriodType.java +++ b/kudos-services/src/main/java/io/meeds/kudos/model/KudosPeriodType.java @@ -1,6 +1,25 @@ -package org.exoplatform.kudos.model; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; -import static org.exoplatform.kudos.service.utils.Utils.timeToSeconds; +import static io.meeds.kudos.service.utils.Utils.timeToSeconds; import java.time.*; diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/exception/KudosAlreadyLinkedException.java b/kudos-services/src/main/java/io/meeds/kudos/model/exception/KudosAlreadyLinkedException.java similarity index 91% rename from kudos-services/src/main/java/org/exoplatform/kudos/exception/KudosAlreadyLinkedException.java rename to kudos-services/src/main/java/io/meeds/kudos/model/exception/KudosAlreadyLinkedException.java index d9ec9e753..19294e49b 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/exception/KudosAlreadyLinkedException.java +++ b/kudos-services/src/main/java/io/meeds/kudos/model/exception/KudosAlreadyLinkedException.java @@ -1,6 +1,8 @@ /* * This file is part of the Meeds project (https://meeds.io/). - * Copyright (C) 2020 - 2023 Meeds Association contact@meeds.io + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either @@ -9,11 +11,12 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.exception; +package io.meeds.kudos.model.exception; public class KudosAlreadyLinkedException extends Exception { private static final long serialVersionUID = -91701909117712293L; diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/notification/builder/KudosTemplateBuilder.java b/kudos-services/src/main/java/io/meeds/kudos/notification/builder/KudosTemplateBuilder.java similarity index 89% rename from kudos-services/src/main/java/org/exoplatform/kudos/notification/builder/KudosTemplateBuilder.java rename to kudos-services/src/main/java/io/meeds/kudos/notification/builder/KudosTemplateBuilder.java index ee36c062e..7be3b721f 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/notification/builder/KudosTemplateBuilder.java +++ b/kudos-services/src/main/java/io/meeds/kudos/notification/builder/KudosTemplateBuilder.java @@ -1,6 +1,25 @@ -package org.exoplatform.kudos.notification.builder; - -import static org.exoplatform.kudos.service.utils.Utils.*; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.notification.builder; + +import static io.meeds.kudos.service.utils.Utils.*; import java.io.Writer; import java.util.Calendar; diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/notification/plugin/KudosActivityChildPlugin.java b/kudos-services/src/main/java/io/meeds/kudos/notification/plugin/KudosActivityChildPlugin.java similarity index 76% rename from kudos-services/src/main/java/org/exoplatform/kudos/notification/plugin/KudosActivityChildPlugin.java rename to kudos-services/src/main/java/io/meeds/kudos/notification/plugin/KudosActivityChildPlugin.java index 277bbf673..c593c578d 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/notification/plugin/KudosActivityChildPlugin.java +++ b/kudos-services/src/main/java/io/meeds/kudos/notification/plugin/KudosActivityChildPlugin.java @@ -1,23 +1,25 @@ /** * This file is part of the Meeds project (https://meeds.io/). - * - * Copyright (C) 2020 - 2023 Meeds Association contact@meeds.io - * + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.notification.plugin; +package io.meeds.kudos.notification.plugin; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE; +import static io.meeds.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE; import java.util.Locale; @@ -26,19 +28,20 @@ import org.exoplatform.commons.api.notification.plugin.AbstractNotificationChildPlugin; import org.exoplatform.commons.api.notification.service.template.TemplateContext; import org.exoplatform.commons.notification.template.TemplateUtils; +import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; import org.exoplatform.social.core.utils.MentionUtils; import org.exoplatform.social.notification.plugin.SocialNotificationUtils; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + public class KudosActivityChildPlugin extends AbstractNotificationChildPlugin { - private KudosService kudosService; + protected KudosService kudosService; - public KudosActivityChildPlugin(KudosService kudosService, InitParams initParams) { + public KudosActivityChildPlugin(InitParams initParams) { super(initParams); - this.kudosService = kudosService; } @Override @@ -49,7 +52,7 @@ public String makeContent(NotificationContext ctx) { } String activityId = notification.getValueOwnerParameter(SocialNotificationUtils.ACTIVITY_ID.getKey()); - Kudos kudos = kudosService.getKudosByActivityId(Long.parseLong(activityId.replace("comment", ""))); + Kudos kudos = getKudosService().getKudosByActivityId(Long.parseLong(activityId.replace("comment", ""))); if (kudos == null) { return ""; } @@ -70,4 +73,10 @@ public boolean isValid(NotificationContext ctx) { return false; } + public KudosService getKudosService() { + if (kudosService == null) { + kudosService = ExoContainerContext.getService(KudosService.class); + } + return kudosService; + } } diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/notification/plugin/KudosReceiverNotificationPlugin.java b/kudos-services/src/main/java/io/meeds/kudos/notification/plugin/KudosReceiverNotificationPlugin.java similarity index 77% rename from kudos-services/src/main/java/org/exoplatform/kudos/notification/plugin/KudosReceiverNotificationPlugin.java rename to kudos-services/src/main/java/io/meeds/kudos/notification/plugin/KudosReceiverNotificationPlugin.java index c0c85d973..66568a6d6 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/notification/plugin/KudosReceiverNotificationPlugin.java +++ b/kudos-services/src/main/java/io/meeds/kudos/notification/plugin/KudosReceiverNotificationPlugin.java @@ -1,22 +1,25 @@ -/* - * Copyright (C) 2003-2018 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.notification.plugin; +package io.meeds.kudos.notification.plugin; -import static org.exoplatform.kudos.service.utils.Utils.*; +import static io.meeds.kudos.service.utils.Utils.*; import java.util.List; @@ -25,12 +28,13 @@ import org.exoplatform.commons.api.notification.plugin.BaseNotificationPlugin; import org.exoplatform.container.ExoContainerContext; import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.model.Kudos; import org.exoplatform.social.core.activity.model.ExoSocialActivity; import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.utils.MentionUtils; import org.exoplatform.social.notification.plugin.SocialNotificationUtils; +import io.meeds.kudos.model.Kudos; + public class KudosReceiverNotificationPlugin extends BaseNotificationPlugin { public KudosReceiverNotificationPlugin(InitParams initParams) { diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/notification/provider/MailTemplateProvider.java b/kudos-services/src/main/java/io/meeds/kudos/notification/provider/MailTemplateProvider.java similarity index 55% rename from kudos-services/src/main/java/org/exoplatform/kudos/notification/provider/MailTemplateProvider.java rename to kudos-services/src/main/java/io/meeds/kudos/notification/provider/MailTemplateProvider.java index cf5ab7fd2..1339a3ed0 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/notification/provider/MailTemplateProvider.java +++ b/kudos-services/src/main/java/io/meeds/kudos/notification/provider/MailTemplateProvider.java @@ -1,31 +1,35 @@ -/* - * Copyright (C) 2003-2018 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.notification.provider; +package io.meeds.kudos.notification.provider; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_RECEIVER_NOTIFICATION_ID; +import static io.meeds.kudos.service.utils.Utils.KUDOS_RECEIVER_NOTIFICATION_ID; import org.exoplatform.commons.api.notification.annotation.TemplateConfig; import org.exoplatform.commons.api.notification.annotation.TemplateConfigs; import org.exoplatform.commons.api.notification.channel.template.TemplateProvider; import org.exoplatform.commons.api.notification.model.PluginKey; import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.notification.builder.KudosTemplateBuilder; import org.exoplatform.social.common.xmlprocessor.XMLProcessor; +import io.meeds.kudos.notification.builder.KudosTemplateBuilder; + @TemplateConfigs(templates = { @TemplateConfig(pluginId = KUDOS_RECEIVER_NOTIFICATION_ID, template = "war:/conf/kudos/templates/notification/mail/KudosReceiverMailPlugin.gtmpl") }) public class MailTemplateProvider extends TemplateProvider { diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/notification/provider/MobilePushTemplateProvider.java b/kudos-services/src/main/java/io/meeds/kudos/notification/provider/MobilePushTemplateProvider.java similarity index 55% rename from kudos-services/src/main/java/org/exoplatform/kudos/notification/provider/MobilePushTemplateProvider.java rename to kudos-services/src/main/java/io/meeds/kudos/notification/provider/MobilePushTemplateProvider.java index e2c43f8be..649cc3e2a 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/notification/provider/MobilePushTemplateProvider.java +++ b/kudos-services/src/main/java/io/meeds/kudos/notification/provider/MobilePushTemplateProvider.java @@ -1,31 +1,35 @@ -/* - * Copyright (C) 2003-2018 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.notification.provider; +package io.meeds.kudos.notification.provider; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_RECEIVER_NOTIFICATION_ID; +import static io.meeds.kudos.service.utils.Utils.KUDOS_RECEIVER_NOTIFICATION_ID; import org.exoplatform.commons.api.notification.annotation.TemplateConfig; import org.exoplatform.commons.api.notification.annotation.TemplateConfigs; import org.exoplatform.commons.api.notification.channel.template.TemplateProvider; import org.exoplatform.commons.api.notification.model.PluginKey; import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.notification.builder.KudosTemplateBuilder; import org.exoplatform.social.common.xmlprocessor.XMLProcessor; +import io.meeds.kudos.notification.builder.KudosTemplateBuilder; + @TemplateConfigs(templates = { @TemplateConfig(pluginId = KUDOS_RECEIVER_NOTIFICATION_ID, template = "war:/conf/kudos/templates/notification/push/KudosReceiverPushPlugin.gtmpl") }) public class MobilePushTemplateProvider extends TemplateProvider { diff --git a/kudos-services/src/main/java/io/meeds/kudos/rest/KudosAccountREST.java b/kudos-services/src/main/java/io/meeds/kudos/rest/KudosAccountREST.java new file mode 100644 index 000000000..03337ea35 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/rest/KudosAccountREST.java @@ -0,0 +1,62 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.rest; + +import static io.meeds.kudos.service.utils.Utils.getCurrentUserId; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.annotation.Secured; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.meeds.kudos.model.AccountSettings; +import io.meeds.kudos.service.KudosService; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("account") +@Tag(name = "/kudos/rest/account", description = "Retrieve Kudos settings for users and spaces") +public class KudosAccountREST { + + @Autowired + private KudosService kudosService; + + @GetMapping("settings") + @Secured("users") + @Operation(summary = "Retrieves user/space settings for kudos", method = "GET", description = "returns account settings object") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public AccountSettings getSettings() { + AccountSettings accountDetail = kudosService.getAccountSettings(getCurrentUserId()); + if (accountDetail == null) { + return new AccountSettings(); + } else { + return accountDetail; + } + } + +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/rest/KudosREST.java b/kudos-services/src/main/java/io/meeds/kudos/rest/KudosREST.java new file mode 100644 index 000000000..4779c2dc5 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/rest/KudosREST.java @@ -0,0 +1,442 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.rest; + +import static io.meeds.kudos.service.utils.Utils.getCurrentUserId; +import static io.meeds.kudos.service.utils.Utils.timeFromSeconds; + +import java.util.List; +import java.util.Locale; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.annotation.Secured; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import org.exoplatform.commons.exception.ObjectNotFoundException; +import org.exoplatform.portal.application.localization.LocalizationFilter; +import org.exoplatform.services.security.ConversationState; +import org.exoplatform.social.core.identity.model.Identity; +import org.exoplatform.social.core.manager.IdentityManager; +import org.exoplatform.social.core.utils.MentionUtils; + +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosList; +import io.meeds.kudos.model.KudosPeriod; +import io.meeds.kudos.model.KudosPeriodType; +import io.meeds.kudos.model.exception.KudosAlreadyLinkedException; +import io.meeds.kudos.service.KudosService; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.parameters.RequestBody; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("kudos") +@Tag(name = "/kudos/rest/kudos", description = "Manages Kudos") // NOSONAR +public class KudosREST { + + @Autowired + private KudosService kudosService; + + @Autowired + private IdentityManager identityManager; + + @GetMapping + @Secured("administrators") + @Operation( + summary = "Get Kudos list created in a period contained a selected date in seconds", + method = "GET", + description = "Get Kudos list created in a period contained a selected date in seconds and returns list of Kudos") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public List getKudosByPeriodOfDate( + @Parameter(description = "Timestamp in seconds of date in the middle of selected period. If not defined, current time will be used.") + @RequestParam(name = "dateInSeconds", required = false, defaultValue = "0") + long dateInSeconds, + @Parameter(description = "Limit of results to return") + @RequestParam(name = "limit", required = false, defaultValue = "10") + int limit) { + if (dateInSeconds <= 0) { + dateInSeconds = System.currentTimeMillis() / 1000; + } + List allKudosByPeriod = kudosService.getKudosByPeriodOfDate(dateInSeconds, getLimit(limit)); + translateRoleMentions(allKudosByPeriod.toArray(new Kudos[0])); + return allKudosByPeriod; + } + + @GetMapping("byEntity") + @Secured("users") + @Operation(summary = "Get Kudos list by entity type and id", method = "GET", + description = "Get Kudos list by entity type and id and returns list of Kudos") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public List getEntityKudos( + @Parameter(description = "kudos entity type (for example activity, comment...)", + required = true) + @RequestParam("entityType") + String entityType, + @Parameter(description = "kudos entity id", required = true) + @RequestParam("entityId") + String entityId, + @Parameter(description = "Limit of results to return") + @RequestParam(name = "limit", required = false, defaultValue = "10") + int limit) { + List allKudosByEntity = kudosService.getKudosByEntity(entityType, entityId, getLimit(limit)); + translateRoleMentions(allKudosByEntity.toArray(new Kudos[0])); + return allKudosByEntity; + } + + @GetMapping("byActivity/{activityId}") + @Secured("users") + @Operation(summary = "Get Kudos by its generated comment or activity id", method = "GET", + description = "Get Kudos by its generated comment or activity id") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "401", description = "Unauthorized operation"), + @ApiResponse(responseCode = "404", description = "Entity Not found"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public Kudos getKudosByActivityId( + @Parameter(description = "kudos activity or comment identifier", required = true) + @PathVariable("activityId") + String activityId) { + try { + Kudos kudos = kudosService.getKudosByActivityId(getActivityId(activityId), getCurrentIdentity()); + translateRoleMentions(kudos); + return kudos; + } catch (IllegalAccessException e) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + } + + @GetMapping("byActivity/{activityId}/all") + @Secured("users") + @Operation( + summary = "Get Kudos List attached to a parent activity, whether the activity itself or in a comment", + method = "GET", + description = "Get Kudos List attached to a parent activity, whether the activity itself or in a comment") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "401", description = "Unauthorized operation"), + @ApiResponse(responseCode = "404", description = "Entity Not found"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public List getKudosListOfActivity( + @Parameter(description = "kudos parent activity identifier", required = true) + @PathVariable("activityId") + String activityId) { + org.exoplatform.services.security.Identity currentUser = getCurrentIdentity(); + try { + List kudosList = kudosService.getKudosListOfActivity(activityId, currentUser); + translateRoleMentions(kudosList.toArray(new Kudos[0])); + return kudosList; + } catch (IllegalAccessException e) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + } + + @GetMapping("byEntity/sent/count") + @Secured("users") + @Operation( + summary = "Get Kudos count by entity and current user as sender", + method = "GET", + description = "Get Kudos count by entity and current user as sender") + @ApiResponses( + value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public long countKudosByEntityAndSender( + @Parameter( + description = "kudos entity type (for example activity, comment...)", + required = true) + @RequestParam("entityType") + String entityType, + @Parameter(description = "kudos entity id", required = true) + @RequestParam("entityId") + String entityId) { + return kudosService.countKudosByEntityAndSender(entityType, entityId, getCurrentIdentityId()); + } + + @GetMapping("byDates") + @Secured("administrators") + @Operation( + summary = "Get Kudos list created between start and end dates in seconds", + method = "GET", + description = "Get Kudos list created between start and end dates in seconds") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public List getKudosByDates( + @RequestParam("startDateInSeconds") + long startDateInSeconds, + @RequestParam("endDateInSeconds") + long endDateInSeconds, + @Parameter(description = "Limit of results to return") + @RequestParam(name = "limit", required = false, defaultValue = "10") + int limit) { + List allKudosByPeriod = kudosService.getKudosByPeriod(startDateInSeconds, endDateInSeconds, getLimit(limit)); + translateRoleMentions(allKudosByPeriod.toArray(new Kudos[0])); + return allKudosByPeriod; + } + + @GetMapping("{identityId}/received") + @Secured("users") + @Operation( + summary = "Retrieve the list of received Kudos by a user or space in a selected period", + method = "GET", + description = "Retrieve the list of received Kudos by a user or space in a selected period") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "500", description = "Internal server error") + }) + public KudosList getReceivedKudosByPeriod( + @Parameter(description = "User or space identity technical id", required = true) + @PathVariable("identityId") + long identityId, + @Parameter(description = "Date in the middle of a period defined using a timestamp in seconds", + required = true) + @RequestParam(name = "dateInSeconds", required = false, defaultValue = "0") + long dateInSeconds, + @Parameter(description = "Period type, can be: WEEK, MONTH, QUARTER, SEMESTER and YEAR. Default is the same as configured period", + required = false) + @RequestParam(name = "periodType", required = false) + String periodType, + @Parameter(description = "Limit of kudos to retrieve, if equal to 0, no kudos will be retrieved", + required = false) + @RequestParam(name = "limit", required = false, defaultValue = "10") + int limit, + @Parameter(description = "Whether return size of received kudos, default = false") + @RequestParam(name = "returnSize", required = false, defaultValue = "false") + boolean returnSize) { + KudosPeriodType kudosPeriodType = getKudosPeriodType(periodType); + KudosPeriod period = kudosPeriodType.getPeriodOfTime(timeFromSeconds(dateInSeconds)); + KudosList kudosList = new KudosList(); + if (returnSize) { + long size = kudosService.countKudosByPeriodAndReceiver(identityId, + period.getStartDateInSeconds(), + period.getEndDateInSeconds()); + kudosList.setSize(size); + if (size == 0 || limit == 0) { + return kudosList; + } + } + List kudos = kudosService.getKudosByPeriodAndReceiver(identityId, + period.getStartDateInSeconds(), + period.getEndDateInSeconds(), + getLimit(limit)); + translateRoleMentions(kudos.toArray(new Kudos[0])); + kudosList.setKudos(kudos); + return kudosList; + } + + @GetMapping("{identityId}/sent") + @Secured("users") + @Operation( + summary = "Retrieve the list of sent Kudos for a user in a selected period", + method = "GET", + description = "Retrieve the list of sent Kudos for a user in a selected period") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public KudosList getSentKudosByPeriod( + @Parameter(description = "User or space identity technical id", required = true) + @PathVariable("identityId") + long identityId, + @Parameter(description = "Date in the middle of a period defined using a timestamp in seconds") + @RequestParam(name = "dateInSeconds", required = false, defaultValue = "0") + long dateInSeconds, + @Parameter(description = "Period type, can be: WEEK, MONTH, QUARTER, SEMESTER and YEAR. Default is the same as configured period") + @RequestParam(name = "periodType", required = false) + String periodType, + @Parameter(description = "Limit of kudos to retrieve, if equal to 0, no kudos will be retrieved") + @RequestParam(name = "limit", required = false, defaultValue = "10") + int limit, + @Parameter(description = "Whether return size of sent kudos, default = false") + @RequestParam(name = "returnSize", required = false, defaultValue = "false") + boolean returnSize) { + KudosPeriodType kudosPeriodType = getKudosPeriodType(periodType); + KudosPeriod period = kudosPeriodType.getPeriodOfTime(timeFromSeconds(dateInSeconds)); + KudosList kudosList = new KudosList(); + if (returnSize) { + long size = kudosService.countKudosByPeriodAndSender(identityId, + period.getStartDateInSeconds(), + period.getEndDateInSeconds()); + kudosList.setSize(size); + if (size == 0 || limit == 0) { + return kudosList; + } + } + + List kudos = kudosService.getKudosByPeriodAndSender(identityId, + period.getStartDateInSeconds(), + period.getEndDateInSeconds(), + getLimit(limit)); + translateRoleMentions(kudos.toArray(new Kudos[0])); + kudosList.setKudos(kudos); + return kudosList; + } + + @PostMapping + @Secured("users") + @Operation( + summary = "Creates new Kudos", + method = "POST", + description = "Creates new Kudos and returns an empty response") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public Kudos createKudos( + @RequestBody(description = "Kudos object to create", required = true) + @org.springframework.web.bind.annotation.RequestBody + Kudos kudos) { + if (StringUtils.isBlank(kudos.getReceiverId()) || StringUtils.isBlank(kudos.getReceiverType())) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ReceiverId and ReceiverType are mandatory"); + } + if (StringUtils.isBlank(kudos.getEntityId()) || StringUtils.isBlank(kudos.getEntityType())) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, + "Bad request sent to server with empty 'attached entity id or type'"); + } + try { + kudos.setSenderId(getCurrentUserId()); + Kudos kudosSent = kudosService.createKudos(kudos, getCurrentUserId()); + translateRoleMentions(kudosSent); + return kudosSent; + } catch (IllegalAccessException e) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } + } + + @DeleteMapping("{kudosId}") + @Secured("users") + @Operation(summary = "Cancels a sent kudos", method = "DELETE", description = "Cancels a sent kudos") + @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "404", description = "Object not found"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "401", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error"), }) + public void deleteKudos( + @Parameter(description = "Kudos technical identifier", required = true) + @PathVariable("kudosId") + long kudosId) { + String currentUser = getCurrentUserId(); + try { + kudosService.deleteKudosById(kudosId, currentUser); + } catch (IllegalAccessException e) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN); + } catch (ObjectNotFoundException e) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND); + } catch (KudosAlreadyLinkedException e) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "KudosAlreadyLinked"); + } + } + + @GetMapping("period") + @Secured("users") + @Operation( + summary = "Get Kudos period of time by computing it using period type and a selected date", + method = "GET", + description = "Get Kudos period of time by computing it using period type and a selected date") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "400", description = "Invalid query input"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public KudosPeriod getPeriodDates( + @Parameter(description = "Period type, can be: WEEK, MONTH, QUARTER, SEMESTER and YEAR. Default is the same as configured period") + @RequestParam("periodType") + String periodType, + @Parameter(description = "Date in the middle of a period defined using a timestamp in seconds") + @RequestParam("dateInSeconds") + long dateInSeconds) { + KudosPeriodType kudosPeriodType = getKudosPeriodType(periodType); + return kudosPeriodType.getPeriodOfTime(timeFromSeconds(dateInSeconds)); + } + + private int getLimit(int limit) { + if (limit <= 0) { + limit = 10; + } + return limit; + } + + private Long getActivityId(String commentId) { + return (commentId == null || commentId.trim().isEmpty()) ? null : Long.valueOf(commentId.replace("comment", "")); + } + + private void translateRoleMentions(Kudos... kudosList) { + if (ArrayUtils.isEmpty(kudosList)) { + return; + } + Locale userLocale = LocalizationFilter.getCurrentLocale(); + for (Kudos kudos : kudosList) { + if (kudos != null) { + kudos.setMessage(MentionUtils.substituteUsernames(kudos.getMessage(), userLocale)); + } + } + } + + private org.exoplatform.services.security.Identity getCurrentIdentity() { + return ConversationState.getCurrent().getIdentity(); + } + + private String getCurrentIdentityId() { + Identity identity = identityManager.getOrCreateUserIdentity(getCurrentUserId()); + return identity.getId(); + } + + private KudosPeriodType getKudosPeriodType(String periodType) { + if (StringUtils.isBlank(periodType)) { + return kudosService.getDefaultKudosPeriodType(); + } else { + try { + return KudosPeriodType.valueOf(periodType.toUpperCase()); + } catch (Exception e) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "periodType '" + periodType + "' is not valid"); + } + } + } + +} diff --git a/kudos-services/src/main/java/io/meeds/kudos/rest/KudosSettingsREST.java b/kudos-services/src/main/java/io/meeds/kudos/rest/KudosSettingsREST.java new file mode 100644 index 000000000..f4c569730 --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/rest/KudosSettingsREST.java @@ -0,0 +1,73 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.rest; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.annotation.Secured; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.meeds.kudos.model.GlobalSettings; +import io.meeds.kudos.service.KudosService; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("settings") +@Tag(name = "/kudos/rest/settings", description = "Manages Kudos global settings") +public class KudosSettingsREST { + + @Autowired + private KudosService kudosService; + + @GetMapping + @Secured("users") + @Operation(summary = "Get Kudos global settings", method = "GET", description = "Get Kudos global settings") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Request fulfilled"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public GlobalSettings getSettings() { + return kudosService.getGlobalSettings(); + } + + @PostMapping + @Secured("administrators") + @Operation( + summary = "Saves Kudos global settings", + method = "POST", + description = "Saves Kudos global settings and returns an empty response") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "Request fulfilled"), + @ApiResponse(responseCode = "403", description = "Unauthorized operation"), + @ApiResponse(responseCode = "500", description = "Internal server error") }) + public void saveSettings( + @RequestBody + GlobalSettings settings) { + kudosService.saveGlobalSettings(settings); + } + +} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/service/KudosService.java b/kudos-services/src/main/java/io/meeds/kudos/service/KudosService.java similarity index 81% rename from kudos-services/src/main/java/org/exoplatform/kudos/service/KudosService.java rename to kudos-services/src/main/java/io/meeds/kudos/service/KudosService.java index fd77875f6..05c9560ad 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/service/KudosService.java +++ b/kudos-services/src/main/java/io/meeds/kudos/service/KudosService.java @@ -1,38 +1,54 @@ -/* - * Copyright (C) 2003-2018 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.service; - -import static org.exoplatform.kudos.service.utils.Utils.*; +package io.meeds.kudos.service; + +import static io.meeds.kudos.service.utils.Utils.KUDOS_ACTIVITY_EVENT; +import static io.meeds.kudos.service.utils.Utils.KUDOS_CANCEL_ACTIVITY_EVENT; +import static io.meeds.kudos.service.utils.Utils.KUDOS_CONTEXT; +import static io.meeds.kudos.service.utils.Utils.KUDOS_SCOPE; +import static io.meeds.kudos.service.utils.Utils.KUDOS_SENT_EVENT; +import static io.meeds.kudos.service.utils.Utils.SETTINGS_KEY_NAME; +import static io.meeds.kudos.service.utils.Utils.USER_ACCOUNT_TYPE; +import static io.meeds.kudos.service.utils.Utils.getActivityId; +import static io.meeds.kudos.service.utils.Utils.getCurrentPeriod; +import static io.meeds.kudos.service.utils.Utils.getPeriodOfTime; +import static io.meeds.kudos.service.utils.Utils.getPeriodType; +import static io.meeds.kudos.service.utils.Utils.getSpace; +import static io.meeds.kudos.service.utils.Utils.timeFromSeconds; +import static io.meeds.kudos.service.utils.Utils.timeToSeconds; import java.io.Serializable; import java.time.LocalDateTime; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; import org.apache.commons.lang3.StringUtils; -import org.exoplatform.commons.exception.ObjectNotFoundException; -import org.exoplatform.kudos.exception.KudosAlreadyLinkedException; -import org.picocontainer.Startable; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; import org.exoplatform.commons.api.settings.SettingService; import org.exoplatform.commons.api.settings.SettingValue; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.model.*; -import org.exoplatform.kudos.storage.KudosStorage; +import org.exoplatform.commons.exception.ObjectNotFoundException; import org.exoplatform.services.listener.ListenerService; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; @@ -44,12 +60,24 @@ import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.manager.IdentityManager; import org.exoplatform.social.core.space.model.Space; -import org.exoplatform.social.core.space.spi.SpaceService; + +import io.meeds.kudos.model.AccountSettings; +import io.meeds.kudos.model.GlobalSettings; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosEntityType; +import io.meeds.kudos.model.KudosPeriod; +import io.meeds.kudos.model.KudosPeriodType; +import io.meeds.kudos.model.exception.KudosAlreadyLinkedException; +import io.meeds.kudos.storage.KudosStorage; + +import jakarta.annotation.PostConstruct; +import lombok.SneakyThrows; /** * A service to manage kudos */ -public class KudosService implements Startable { +@Service +public class KudosService { private static final Log LOG = ExoLogger.getLogger(KudosService.class); @@ -57,73 +85,49 @@ public class KudosService implements Startable { private static final String CLUSTER_NODE_ID = UUID.randomUUID().toString(); + @Autowired private ActivityManager activityManager; + @Autowired private IdentityManager identityManager; - private SpaceService spaceService; - + @Autowired private ListenerService listenerService; + @Autowired private KudosStorage kudosStorage; + @Autowired private SettingService settingService; - private PortalContainer container; - + @Autowired(required = false) private RPCService rpcService; private GlobalSettings globalSettings; + @Value("${kudos.defaultAccessPermission:}") // NOSONAR + private String defaultAccessPermission; + + @Value("${kudos.defaultKudosPerPeriod:3}") + private long defaultKudosPerPeriod; + /** * The generic command used to replicate changes over the cluster */ private RemoteCommand reloadSettingsCommand; - public KudosService(KudosStorage kudosStorage, // NOSONAR : Needed for - // dependency injection - SettingService settingService, - ActivityManager activityManager, - SpaceService spaceService, - IdentityManager identityManager, - ListenerService listenerService, - PortalContainer container, - InitParams params) { - this.kudosStorage = kudosStorage; - this.identityManager = identityManager; - this.activityManager = activityManager; - this.spaceService = spaceService; - this.settingService = settingService; - this.listenerService = listenerService; - this.container = container; - - if (params != null) { - this.globalSettings = new GlobalSettings(); - if (params.containsKey(DEFAULT_ACCESS_PERMISSION)) { - String defaultAccessPermission = params.getValueParam(DEFAULT_ACCESS_PERMISSION).getValue(); - globalSettings.setAccessPermission(defaultAccessPermission); - } - if (params.containsKey(DEFAULT_KUDOS_PER_PERIOD)) { - String defaultKudosPerPeriod = params.getValueParam(DEFAULT_KUDOS_PER_PERIOD).getValue(); - globalSettings.setKudosPerPeriod(Long.parseLong(defaultKudosPerPeriod)); - } - } - } - - @Override - public void start() { + @PostConstruct + public void init() { GlobalSettings loadedGlobalSettings = loadGlobalSettings(); - if (loadedGlobalSettings != null) { + if (loadedGlobalSettings == null) { + this.globalSettings = new GlobalSettings(); + this.globalSettings.setKudosPerPeriod(defaultKudosPerPeriod); + } else { this.globalSettings = loadedGlobalSettings; } installClusterListener(); } - @Override - public void stop() { - // Nothing to shutdown - } - /** * @return {@link GlobalSettings} of Kudos module */ @@ -151,12 +155,6 @@ public void saveGlobalSettings(GlobalSettings settings) { */ public AccountSettings getAccountSettings(String username) { AccountSettings accountSettings = new AccountSettings(); - - if (!isAuthorizedOnKudosModule(username)) { - accountSettings.setDisabled(true); - return accountSettings; - } - Identity senderIdentity = (Identity) checkStatusAndGetReceiver(OrganizationIdentityProvider.NAME, username); long senderIdentityId = Long.parseLong(senderIdentity.getId()); long sentKudos = kudosStorage.countKudosByPeriodAndSender(getCurrentKudosPeriod(), senderIdentityId); @@ -170,12 +168,13 @@ public AccountSettings getAccountSettings(String username) { * @param kudos {@link Kudos} to create * @param currentUser username of current user * @return created {@link Kudos} - * @throws Exception when receiver or sender aren't allowed. + * @throws IllegalAccessException when receiver or sender aren't allowed. */ - public Kudos createKudos(Kudos kudos, String currentUser) throws Exception { + @SneakyThrows + public Kudos createKudos(Kudos kudos, String currentUser) throws IllegalAccessException { if (!StringUtils.equals(currentUser, kudos.getSenderId())) { - throw new IllegalAccessException("User with id '" + currentUser + "' is not authorized to send kudos on behalf of " - + kudos.getSenderId()); + throw new IllegalAccessException("User with id '" + currentUser + "' is not authorized to send kudos on behalf of " + + kudos.getSenderId()); } if (StringUtils.equals(currentUser, kudos.getReceiverId())) { throw new IllegalAccessException("User with username '" + currentUser + "' is not authorized to send kudos to himseld!"); @@ -215,11 +214,12 @@ public Kudos createKudos(Kudos kudos, String currentUser) throws Exception { * * @param kudosId Kudos technical identifier to delete * @param username User name deleting kudos - * @throws Exception when user is not authorized to delete the - * kudos or when the kudos identified by its technical - * identifier is not found + * @throws IllegalAccessException when user is not authorized to delete the kudos + * @throws ObjectNotFoundException when the kudos identified by its technical identifier is not found + * @throws KudosAlreadyLinkedException when the kudos is already linked to kudos entities */ - public void deleteKudosById(long kudosId, String username) throws Exception { + @SneakyThrows + public void deleteKudosById(long kudosId, String username) throws IllegalAccessException, ObjectNotFoundException, KudosAlreadyLinkedException { if (username == null) { throw new IllegalArgumentException("Username is mandatory"); } @@ -298,8 +298,8 @@ public Kudos getKudosByActivityId(Long activityId, return null; } if (!activityManager.isActivityViewable(activity, currentUser)) { - throw new IllegalAccessException("User " + currentUser.getUserId() + " isn't allowed to access kudos of activity with id " - + activityId); + throw new IllegalAccessException("User " + currentUser.getUserId() + " isn't allowed to access kudos of activity with id " + + activityId); } return kudos; } @@ -503,8 +503,8 @@ public List getKudosListOfActivity(String activityId, return Collections.emptyList(); } if (!activityManager.isActivityViewable(activity, currentUser)) { - throw new IllegalAccessException("User " + currentUser.getUserId() + " isn't allowed to access kudos of activity with id " - + activityId); + throw new IllegalAccessException("User " + currentUser.getUserId() + " isn't allowed to access kudos of activity with id " + + activityId); } return getKudosListOfActivity(activityId); } @@ -520,26 +520,6 @@ public List getKudosListOfActivity(String activityId) { return kudosStorage.getKudosListOfActivity(getActivityId(activityId)); } - /** - * Check if user is authorized to send/receive Kudos - * - * @param username username to check - * @return true if authorised else return false - */ - public boolean isAuthorizedOnKudosModule(String username) { - if (StringUtils.isBlank(username)) { - return false; - } - String accessPermission = getAccessPermission(); - if (StringUtils.isBlank(accessPermission)) { - return true; - } - Space space = getSpace(accessPermission); - - // Disable kudos for users not member of the permitted space members - return spaceService.isSuperManager(username) || (space != null && spaceService.isMember(space, username)); - } - public KudosPeriodType getDefaultKudosPeriodType() { return getPeriodType(getGlobalSettings()); } @@ -562,11 +542,6 @@ private Object checkStatusAndGetReceiver(String type, String id) { if (identity == null || !identity.isEnable() || identity.isDeleted()) { throw new IllegalStateException("User with identity id '" + id + "' doesn't have a valid and enabled social identity"); } - if (!isAuthorizedOnKudosModule(id)) { - throw new IllegalStateException("User with identity id '" + id - + "' isn't member of authorized group to send/receive kudos: " - + getAccessPermission()); - } return identity; } else { Space space = getSpace(id); @@ -582,11 +557,6 @@ private long getAllowedKudosPerPeriod() { return storedGlobalSettings == null ? 0 : storedGlobalSettings.getKudosPerPeriod(); } - private String getAccessPermission() { - GlobalSettings storedGlobalSettings = getGlobalSettings(); - return storedGlobalSettings == null ? null : storedGlobalSettings.getAccessPermission(); - } - private GlobalSettings loadGlobalSettings() { SettingValue globalSettingsValue = settingService.get(KUDOS_CONTEXT, KUDOS_SCOPE, SETTINGS_KEY_NAME); if (globalSettingsValue == null || StringUtils.isBlank(globalSettingsValue.getValue().toString())) { @@ -597,13 +567,12 @@ private GlobalSettings loadGlobalSettings() { } private void installClusterListener() { - RPCService clusterRpcService = getRpcService(); - if (clusterRpcService != null) { + if (rpcService != null) { // Clear global settings in current node // to force reload it from store // if another cluster node had changed // the settings - this.reloadSettingsCommand = clusterRpcService.registerCommand(new RemoteCommand() { + this.reloadSettingsCommand = rpcService.registerCommand(new RemoteCommand() { public String getId() { return CLUSTER_GLOBAL_SETTINGS_UPDATED; } @@ -621,17 +590,11 @@ public Serializable execute(Serializable[] args) throws Throwable { private void clearCacheClusterWide() { if (this.reloadSettingsCommand != null) { try { - getRpcService().executeCommandOnAllNodes(this.reloadSettingsCommand, false, CLUSTER_NODE_ID); + rpcService.executeCommandOnAllNodes(this.reloadSettingsCommand, false, CLUSTER_NODE_ID); } catch (Exception e) { LOG.warn("An error occurred while clearing global settings cache on other nodes", e); } } } - private RPCService getRpcService() { - if (rpcService == null) { - rpcService = container.getComponentInstanceOfType(RPCService.class); - } - return rpcService; - } } diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/service/utils/Utils.java b/kudos-services/src/main/java/io/meeds/kudos/service/utils/Utils.java similarity index 90% rename from kudos-services/src/main/java/org/exoplatform/kudos/service/utils/Utils.java rename to kudos-services/src/main/java/io/meeds/kudos/service/utils/Utils.java index 53f26a8de..76b567127 100644 --- a/kudos-services/src/main/java/org/exoplatform/kudos/service/utils/Utils.java +++ b/kudos-services/src/main/java/io/meeds/kudos/service/utils/Utils.java @@ -1,4 +1,23 @@ -package org.exoplatform.kudos.service.utils; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.service.utils; import static org.exoplatform.social.core.manager.ActivityManagerImpl.REMOVABLE; @@ -17,12 +36,6 @@ import org.exoplatform.commons.api.settings.data.Context; import org.exoplatform.commons.api.settings.data.Scope; import org.exoplatform.commons.utils.CommonsUtils; -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.model.GlobalSettings; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.model.KudosPeriod; -import org.exoplatform.kudos.model.KudosPeriodType; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.exoplatform.services.security.ConversationState; @@ -39,6 +52,13 @@ import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.social.core.utils.MentionUtils; +import io.meeds.kudos.entity.KudosEntity; +import io.meeds.kudos.model.GlobalSettings; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosEntityType; +import io.meeds.kudos.model.KudosPeriod; +import io.meeds.kudos.model.KudosPeriodType; + public class Utils { private static final Log LOG = ExoLogger.getLogger(Utils.class); @@ -220,8 +240,11 @@ public static KudosEntity toEntity(Kudos kudos) { return kudosEntity; } - public static LocalDateTime timeFromSeconds(long createdDate) { - return LocalDateTime.ofInstant(Instant.ofEpochSecond(createdDate), TimeZone.getDefault().toZoneId()); + public static LocalDateTime timeFromSeconds(long dateInSeconds) { + if (dateInSeconds <= 0) { + dateInSeconds = System.currentTimeMillis() / 1000; + } + return LocalDateTime.ofInstant(Instant.ofEpochSecond(dateInSeconds), TimeZone.getDefault().toZoneId()); } public static long timeToSeconds(LocalDateTime time) { diff --git a/kudos-services/src/main/java/io/meeds/kudos/storage/KudosStorage.java b/kudos-services/src/main/java/io/meeds/kudos/storage/KudosStorage.java new file mode 100644 index 000000000..0b390c0af --- /dev/null +++ b/kudos-services/src/main/java/io/meeds/kudos/storage/KudosStorage.java @@ -0,0 +1,258 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.storage; + +import static io.meeds.kudos.service.utils.Utils.USER_ACCOUNT_TYPE; +import static io.meeds.kudos.service.utils.Utils.fromEntity; +import static io.meeds.kudos.service.utils.Utils.getSpace; +import static io.meeds.kudos.service.utils.Utils.toEntity; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Limit; +import org.springframework.stereotype.Component; + +import org.exoplatform.commons.utils.CommonsUtils; +import org.exoplatform.services.log.ExoLogger; +import org.exoplatform.services.log.Log; +import org.exoplatform.social.core.identity.model.Identity; +import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; +import org.exoplatform.social.core.identity.provider.SpaceIdentityProvider; +import org.exoplatform.social.core.manager.IdentityManager; +import org.exoplatform.social.core.space.model.Space; + +import io.meeds.kudos.dao.KudosDAO; +import io.meeds.kudos.entity.KudosEntity; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosEntityType; +import io.meeds.kudos.model.KudosPeriod; +import io.meeds.kudos.service.utils.Utils; + +@Component +public class KudosStorage { + + private static final Log LOG = ExoLogger.getLogger(KudosStorage.class); + + @Autowired + private KudosDAO kudosDAO; + + @Autowired + private IdentityManager identityManager; + + public Kudos getKudoById(long id) { + KudosEntity kudosEntity = kudosDAO.findById(id).orElse(null); + if (kudosEntity == null) { + LOG.warn("Can't find Kudos with id {}", id); + return null; + } else { + return fromEntity(kudosEntity); + } + } + + public Kudos createKudos(Kudos kudos) { + KudosEntity kudosEntity = toEntity(kudos); + kudosEntity.setId(null); + kudosEntity = kudosDAO.save(kudosEntity); + return fromEntity(kudosEntity); + } + + public void deleteKudosById(long kudosId) { + kudosDAO.deleteById(kudosId); + } + + public void saveKudosActivityId(long kudosId, long activityId) { + KudosEntity kudosEntity = kudosDAO.findById(kudosId).orElse(null); + if (kudosEntity == null) { + throw new IllegalStateException("Can't find Kudos with id " + kudosId); + } else { + kudosEntity.setActivityId(activityId); + kudosDAO.save(kudosEntity); + } + } + + public List getKudosByPeriod(KudosPeriod kudosPeriod, int limit) { + List kudosList = new ArrayList<>(); + List kudosEntities = kudosDAO.findByCreatedDateBetweenOrderByCreatedDateDesc(kudosPeriod.getStartDateInSeconds(), + kudosPeriod.getEndDateInSeconds(), + Limit.of(limit)); + if (kudosEntities != null) { + for (KudosEntity kudosEntity : kudosEntities) { + if (kudosEntity != null) { + kudosList.add(fromEntity(kudosEntity)); + } + } + } + return kudosList; + } + + public List getKudosByEntity(String entityType, String entityId, int limit) { + List kudosList = new ArrayList<>(); + List kudosEntities = + kudosDAO.findByEntityTypeAndEntityIdOrderByCreatedDateDesc(KudosEntityType.valueOf(entityType) + .ordinal(), + Long.parseLong(entityId), + Limit.of(limit)); + if (kudosEntities != null) { + for (KudosEntity kudosEntity : kudosEntities) { + if (kudosEntity != null) { + kudosList.add(fromEntity(kudosEntity)); + } + } + } + return kudosList; + } + + public long countKudosByEntity(String entityType, String entityId) { + return kudosDAO.countByEntityTypeAndEntityId(KudosEntityType.valueOf(entityType).ordinal(), Long.parseLong(entityId)); + } + + public long countKudosByEntityAndSender(String entityType, String entityId, String senderIdentityId) { + return kudosDAO.countByEntityTypeAndEntityIdAndSenderId(KudosEntityType.valueOf(entityType).ordinal(), + Long.parseLong(entityId), + Long.parseLong(senderIdentityId)); + } + + public long countKudosByPeriodAndReceiver(KudosPeriod kudosPeriod, String receiverType, String receiverId) { + boolean isReceiverUser = USER_ACCOUNT_TYPE.equals(receiverType) || OrganizationIdentityProvider.NAME.equals(receiverType); + Identity identity = getIdentityManager().getOrCreateIdentity( + isReceiverUser ? OrganizationIdentityProvider.NAME : + SpaceIdentityProvider.NAME, + receiverId); + return kudosDAO.countByCreatedDateBetweenAndReceiverIdAndIsReceiverUser(kudosPeriod.getStartDateInSeconds(), + kudosPeriod.getEndDateInSeconds(), + Long.parseLong(identity.getId()), + isReceiverUser); + } + + public Map countKudosByPeriodAndReceivers(KudosPeriod kudosPeriod, List receiversId) { + return kudosDAO.countByCreatedDateBetweenAndReceiverIdIn(kudosPeriod.getStartDateInSeconds(), + kudosPeriod.getEndDateInSeconds(), + receiversId) + .stream() + .collect(Collectors.toMap(r -> r.getReceiverId(), r -> r.getCount())); + } + + public List getKudosByPeriodAndReceiver(KudosPeriod kudosPeriod, String receiverType, String receiverId, int limit) { + boolean isReceiverUser = USER_ACCOUNT_TYPE.equals(receiverType) || OrganizationIdentityProvider.NAME.equals(receiverType); + long identityId = getIdentityId(receiverId, isReceiverUser); + if (identityId <= 0) { + return Collections.emptyList(); + } + List kudosEntities = + kudosDAO.findByCreatedDateBetweenAndReceiverIdAndIsReceiverUserOrderByCreatedDateDesc(kudosPeriod.getStartDateInSeconds(), + kudosPeriod.getEndDateInSeconds(), + identityId, + isReceiverUser, + Limit.of(limit)); + if (kudosEntities != null) { + List kudosList = new ArrayList<>(); + for (KudosEntity kudosEntity : kudosEntities) { + if (kudosEntity != null) { + kudosList.add(fromEntity(kudosEntity)); + } + } + return kudosList; + } + return Collections.emptyList(); + } + + public List getKudosByPeriodAndSender(KudosPeriod kudosPeriod, long senderIdentityId, int limit) { + List kudosList = new ArrayList<>(); + List kudosEntities = + kudosDAO.findByCreatedDateBetweenAndSenderIdOrderByCreatedDateDesc(kudosPeriod.getStartDateInSeconds(), + kudosPeriod.getEndDateInSeconds(), + senderIdentityId, + Limit.of(limit)); + if (kudosEntities != null) { + for (KudosEntity kudosEntity : kudosEntities) { + if (kudosEntity != null) { + kudosList.add(fromEntity(kudosEntity)); + } + } + } + return kudosList; + } + + public long countKudosByPeriodAndSender(KudosPeriod kudosPeriod, long senderIdentityId) { + return kudosDAO.countByCreatedDateBetweenAndSenderId(kudosPeriod.getStartDateInSeconds(), + kudosPeriod.getEndDateInSeconds(), + senderIdentityId); + } + + private long getIdentityId(String remoteId, boolean isReceiverUser) { + long identityId = 0; + if (isReceiverUser) { + Identity identity = getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, remoteId); + if (identity == null) { + return 0; + } + identityId = Long.parseLong(identity.getId()); + } else { + Space space = getSpace(remoteId); + if (space == null) { + return 0; + } + identityId = Long.parseLong(space.getId()); + } + return identityId; + } + + private IdentityManager getIdentityManager() { + if (identityManager == null) { + identityManager = CommonsUtils.getService(IdentityManager.class); + } + return identityManager; + } + + public Kudos getKudosByActivityId(Long activityId) { + KudosEntity kudosEntity = kudosDAO.findByActivityId(activityId); + return fromEntity(kudosEntity); + } + + public List getKudosListOfActivity(Long activityId) { + List kudosEntities = kudosDAO.findKudosListOfActivity(activityId, + Arrays.asList(KudosEntityType.ACTIVITY.ordinal(), + KudosEntityType.COMMENT.ordinal())); + return CollectionUtils.isEmpty(kudosEntities) ? Collections.emptyList() : + kudosEntities.stream() + .map(Utils::fromEntity) + .toList(); + } + + public long countKudosOfActivity(Long activityId) { + return kudosDAO.countKudosListOfActivity(activityId, + Arrays.asList(KudosEntityType.ACTIVITY.ordinal(), + KudosEntityType.COMMENT.ordinal())); + } + + public Kudos updateKudos(Kudos kudos) { + KudosEntity kudosEntity = toEntity(kudos); + kudosEntity = kudosDAO.save(kudosEntity); + return fromEntity(kudosEntity); + } + +} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/activity/processor/ActivityKudosProcessor.java b/kudos-services/src/main/java/org/exoplatform/kudos/activity/processor/ActivityKudosProcessor.java deleted file mode 100644 index e25f03541..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/activity/processor/ActivityKudosProcessor.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.exoplatform.kudos.activity.processor; - -import java.util.HashMap; -import java.util.List; - -import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.portal.config.UserPortalConfigService; -import org.exoplatform.social.core.BaseActivityProcessorPlugin; -import org.exoplatform.social.core.activity.model.ExoSocialActivity; -import org.exoplatform.social.core.utils.MentionUtils; - -public class ActivityKudosProcessor extends BaseActivityProcessorPlugin { - - private KudosService kudosService; - - private String defaultPortal; - - public ActivityKudosProcessor(KudosService kudosService, - UserPortalConfigService userPortalConfigService, - InitParams initParams) { - super(initParams); - this.kudosService = kudosService; - this.defaultPortal = userPortalConfigService.getMetaPortal(); - } - - @Override - public void processActivity(ExoSocialActivity activity) { - if (activity.isComment()) { - return; - } - if (activity.getLinkedProcessedEntities() == null) { - activity.setLinkedProcessedEntities(new HashMap<>()); - } - @SuppressWarnings("unchecked") - List linkedKudosList = (List) activity.getLinkedProcessedEntities().get("kudosList"); - if (linkedKudosList == null) { - linkedKudosList = kudosService.getKudosListOfActivity(activity.getId()); - activity.getLinkedProcessedEntities().put("kudosList", linkedKudosList); - } - - if (linkedKudosList != null) { - for (Kudos kudos : linkedKudosList) { - kudos.setMessage(MentionUtils.substituteUsernames(defaultPortal, kudos.getMessage())); - } - } - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/dao/KudosDAO.java b/kudos-services/src/main/java/org/exoplatform/kudos/dao/KudosDAO.java deleted file mode 100644 index 208864c22..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/dao/KudosDAO.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.exoplatform.kudos.dao; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import jakarta.persistence.NoResultException; -import jakarta.persistence.Tuple; -import jakarta.persistence.TypedQuery; - -import org.exoplatform.commons.persistence.impl.GenericDAOJPAImpl; -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.model.KudosPeriod; - -public class KudosDAO extends GenericDAOJPAImpl { - - private static final String ACTIVITY_ID = "activityId"; - - private static final String ENTITY_TYPE = "entityType"; - - private static final String ENTITY_ID = "entityId"; - - private static final String SENDER_ID = "senderId"; - - public List getKudosByPeriod(KudosPeriod kudosPeriod, int limit) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.getKudosByPeriod", KudosEntity.class); - setPeriodParameters(query, kudosPeriod); - query.setMaxResults(limit); - return query.getResultList(); - } - - public List getKudosByPeriodAndEntityType(KudosPeriod kudosPeriod, int entityType, int limit) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.getKudosByPeriodAndEntityType", - KudosEntity.class); - setPeriodParameters(query, kudosPeriod); - query.setParameter(ENTITY_TYPE, entityType); - query.setMaxResults(limit); - return query.getResultList(); - } - - public List getKudosByEntity(int entityType, long entityId, int limit) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.getKudosByEntity", KudosEntity.class); - query.setParameter(ENTITY_ID, entityId); - query.setParameter(ENTITY_TYPE, entityType); - query.setMaxResults(limit); - return query.getResultList(); - } - - public List getKudosByPeriodAndReceiver(KudosPeriod kudosPeriod, - long receiverId, - boolean isReceiverUser, - int limit) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.getKudosByPeriodAndReceiver", KudosEntity.class); - setPeriodParameters(query, kudosPeriod); - query.setParameter("receiverId", receiverId); - query.setParameter("isReceiverUser", isReceiverUser); - query.setMaxResults(limit); - return query.getResultList(); - } - - public long countKudosByEntity(int entityType, long entityId) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.countKudosByEntity", Long.class); - query.setParameter(ENTITY_ID, entityId); - query.setParameter(ENTITY_TYPE, entityType); - Long count = query.getSingleResult(); - return count == null ? 0 : count; - } - - public long countKudosByEntityAndSender(int entityType, long entityId, long senderId) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.countKudosByEntityAndSender", Long.class); - query.setParameter(ENTITY_ID, entityId); - query.setParameter(ENTITY_TYPE, entityType); - query.setParameter(SENDER_ID, senderId); - Long count = query.getSingleResult(); - return count == null ? 0 : count; - } - - public long countKudosByPeriodAndReceiver(KudosPeriod kudosPeriod, long receiverId, boolean isReceiverUser) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.countKudosByPeriodAndReceiver", Long.class); - setPeriodParameters(query, kudosPeriod); - query.setParameter("receiverId", receiverId); - query.setParameter("isReceiverUser", isReceiverUser); - Long count = query.getSingleResult(); - return count == null ? 0 : count; - } - - public Map countKudosByPeriodAndReceivers(KudosPeriod kudosPeriod, List receiversId) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.countKudosByPeriodAndReceivers", Tuple.class); - setPeriodParameters(query, kudosPeriod); - query.setParameter("receiversId", receiversId); - return query.getResultList().stream().collect(Collectors.toMap(tuple -> (Long) tuple.get(0), tuple -> (Long) tuple.get(1))); - } - - public List getKudosByPeriodAndSender(KudosPeriod kudosPeriod, long senderId, int limit) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.getKudosByPeriodAndSender", KudosEntity.class); - setPeriodParameters(query, kudosPeriod); - query.setParameter(SENDER_ID, senderId); - query.setMaxResults(limit); - return query.getResultList(); - } - - public KudosEntity getKudosByActivityId(Long activityId) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.getKudosByActivityId", KudosEntity.class); - query.setParameter(ACTIVITY_ID,activityId); - try { - return query.getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - - public List getKudosListOfActivity(Long activityId) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.getKudosListOfActivity", KudosEntity.class); - query.setParameter(ACTIVITY_ID, activityId); - query.setParameter("activityTypes", Arrays.asList(KudosEntityType.ACTIVITY.ordinal(), KudosEntityType.COMMENT.ordinal())); - return query.getResultList(); - } - - public long countKudosOfActivity(Long activityId) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.countKudosOfActivity", Long.class); - query.setParameter(ACTIVITY_ID, activityId); - query.setParameter("activityTypes", Arrays.asList(KudosEntityType.ACTIVITY.ordinal(), KudosEntityType.COMMENT.ordinal())); - Long count = query.getSingleResult(); - return count == null ? 0 : count; - } - - public long countKudosByPeriodAndSender(KudosPeriod kudosPeriod, long senderId) { - TypedQuery query = getEntityManager().createNamedQuery("Kudos.countKudosByPeriodAndSender", Long.class); - setPeriodParameters(query, kudosPeriod); - query.setParameter(SENDER_ID, senderId); - Long count = query.getSingleResult(); - return count == null ? 0 : count; - } - - private void setPeriodParameters(TypedQuery query, KudosPeriod kudosPeriod) { - query.setParameter("startDate", kudosPeriod.getStartDateInSeconds()); - query.setParameter("endDate", kudosPeriod.getEndDateInSeconds()); - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/entity/KudosEntity.java b/kudos-services/src/main/java/org/exoplatform/kudos/entity/KudosEntity.java deleted file mode 100644 index 42736ee60..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/entity/KudosEntity.java +++ /dev/null @@ -1,177 +0,0 @@ -package org.exoplatform.kudos.entity; - -import java.io.Serializable; - -import jakarta.persistence.*; - -import org.hibernate.annotations.DynamicUpdate; - -import org.exoplatform.commons.api.persistence.ExoEntity; - -@Entity(name = "Kudos") -@ExoEntity -@DynamicUpdate -@Table(name = "ADDONS_KUDOS") -@NamedQueries({ - @NamedQuery(name = "Kudos.getKudosByActivityId", query = "select k from Kudos k" + " WHERE k.activityId = :activityId"), - @NamedQuery(name = "Kudos.getKudosByPeriod", query = "select k from Kudos k" + " WHERE k.createdDate > :startDate" - + " AND k.createdDate < :endDate" - + " ORDER BY k.createdDate DESC"), - @NamedQuery(name = "Kudos.getKudosByPeriodAndEntityType", query = "select k from Kudos k" - + " where k.entityType = :entityType" + " AND k.createdDate > :startDate" + " AND k.createdDate < :endDate" - + " ORDER BY k.createdDate DESC"), - @NamedQuery(name = "Kudos.getKudosByEntity", query = "select k from Kudos k" + " WHERE k.entityType = :entityType" - + " AND k.entityId = :entityId" - + " ORDER BY k.createdDate DESC"), - @NamedQuery(name = "Kudos.countKudosByEntityAndSender", query = "select count(k) from Kudos k" + " WHERE k.entityType = :entityType" - + " AND k.entityId = :entityId" + " AND k.senderId = :senderId"), - @NamedQuery(name = "Kudos.countKudosByEntity", query = "select count(k) from Kudos k" + " WHERE k.entityType = :entityType" - + " AND k.entityId = :entityId"), - @NamedQuery( - name = "Kudos.getKudosListOfActivity", - query = "select k from Kudos k" - + " WHERE" - + " k.activityId = :activityId" - + " OR " - + " (k.entityType in (:activityTypes) AND (k.parentEntityId = :activityId OR k.entityId in :activityId) )" - ), - @NamedQuery( - name = "Kudos.countKudosOfActivity", - query = "select count(k) from Kudos k" - + " WHERE" - + " k.activityId = :activityId" - + " OR" - + " (k.entityType in (:activityTypes) AND (k.parentEntityId = :activityId OR k.entityId in :activityId))" - ), - @NamedQuery(name = "Kudos.getKudosByPeriodAndSender", query = "select k from Kudos k" + " WHERE k.senderId = :senderId" - + " AND k.createdDate > :startDate" + " AND k.createdDate < :endDate" - + " ORDER BY k.createdDate DESC"), - @NamedQuery(name = "Kudos.countKudosByPeriodAndSender", query = "select count(k) from Kudos k" - + " WHERE k.senderId = :senderId" + " AND k.createdDate > :startDate" + " AND k.createdDate < :endDate"), - @NamedQuery(name = "Kudos.getKudosByPeriodAndReceiver", query = "select k from Kudos k" + " WHERE k.receiverId = :receiverId" - + " AND k.isReceiverUser = :isReceiverUser" + " AND k.createdDate > :startDate" + " AND k.createdDate < :endDate" - + " ORDER BY k.createdDate DESC"), - @NamedQuery(name = "Kudos.countKudosByPeriodAndReceiver", query = "select count(k) from Kudos k" - + " WHERE k.receiverId = :receiverId" - + " AND k.isReceiverUser = :isReceiverUser" + " AND k.createdDate > :startDate" + " AND k.createdDate < :endDate"), - @NamedQuery(name = "Kudos.countKudosByPeriodAndReceivers", query = "select k.receiverId,count(k) from Kudos k" - + " WHERE k.receiverId IN :receiversId" + " AND k.createdDate >= :startDate" - + " AND k.createdDate < :endDate GROUP BY k.receiverId") }) -public class KudosEntity implements Serializable { - - private static final long serialVersionUID = -8272292325540761902L; - - @Id - @SequenceGenerator(name = "SEQ_ADDONS_KUDOS_ID", sequenceName = "SEQ_ADDONS_KUDOS_ID", allocationSize = 1) - @GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_ADDONS_KUDOS_ID") - @Column(name = "KUDOS_ID") - private Long id; - - @Column(name = "SENDER_ID", nullable = false) - public long senderId; - - @Column(name = "RECEIVER_ID", nullable = false) - public long receiverId; - - @Column(name = "IS_RECEIVER_USER", nullable = false) - public boolean isReceiverUser; - - @Column(name = "PARENT_ENTITY_ID", nullable = true) - public Long parentEntityId; - - @Column(name = "ENTITY_ID", nullable = false) - public long entityId; - - @Column(name = "ENTITY_TYPE", nullable = false) - public int entityType; - - @Column(name = "ACTIVITY_ID") - public Long activityId; - - @Column(name = "MESSAGE", nullable = true) - public String message; - - @Column(name = "CREATED_DATE", nullable = false) - public long createdDate; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public long getSenderId() { - return senderId; - } - - public void setSenderId(long senderId) { - this.senderId = senderId; - } - - public long getReceiverId() { - return receiverId; - } - - public void setReceiverId(long receiverId) { - this.receiverId = receiverId; - } - - public boolean isReceiverUser() { - return isReceiverUser; - } - - public void setReceiverUser(boolean isReceiverUser) { - this.isReceiverUser = isReceiverUser; - } - - public long getEntityId() { - return entityId; - } - - public void setEntityId(long entityId) { - this.entityId = entityId; - } - - public int getEntityType() { - return entityType; - } - - public void setEntityType(int entityType) { - this.entityType = entityType; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public long getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(long createdDate) { - this.createdDate = createdDate; - } - - public Long getParentEntityId() { - return parentEntityId; - } - - public void setParentEntityId(Long parentEntityId) { - this.parentEntityId = parentEntityId; - } - - public long getActivityId() { - return activityId == null ? 0 : activityId; - } - - public void setActivityId(long activityId) { - this.activityId = activityId; - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosSentNotificationListener.java b/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosSentNotificationListener.java deleted file mode 100644 index f14525d5f..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/listener/KudosSentNotificationListener.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.exoplatform.kudos.listener; - -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_DETAILS_PARAMETER; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_RECEIVER_NOTIFICATION_ID; - -import org.exoplatform.commons.api.notification.NotificationContext; -import org.exoplatform.commons.api.notification.model.PluginKey; -import org.exoplatform.commons.notification.impl.NotificationContextImpl; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.services.listener.Event; -import org.exoplatform.services.listener.Listener; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; - -/** - * A listener to send notification after sending a new Kudos - */ -public class KudosSentNotificationListener extends Listener { - private static final Log LOG = ExoLogger.getLogger(KudosSentNotificationListener.class); - - @Override - public void onEvent(Event event) throws Exception { - Kudos kudos = event.getData(); - try { - NotificationContext ctx = NotificationContextImpl.cloneInstance(); - ctx.append(KUDOS_DETAILS_PARAMETER, kudos); - ctx.getNotificationExecutor().with(ctx.makeCommand(PluginKey.key(KUDOS_RECEIVER_NOTIFICATION_ID))).execute(ctx); - } catch (Exception e) { - LOG.warn("Error sending notification for Kudos with id " + kudos.getTechnicalId(), e); - } - } -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/listener/ProfileUpdateListener.java b/kudos-services/src/main/java/org/exoplatform/kudos/listener/ProfileUpdateListener.java deleted file mode 100644 index 98e5e00e1..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/listener/ProfileUpdateListener.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.exoplatform.kudos.listener; - -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.social.core.profile.ProfileLifeCycleEvent; -import org.exoplatform.social.core.profile.ProfileListenerPlugin; -import org.exoplatform.social.core.storage.api.ActivityStorage; -import org.exoplatform.social.core.storage.cache.CachedActivityStorage; - -import java.util.List; - -public class ProfileUpdateListener extends ProfileListenerPlugin { - - private ActivityStorage activityStorage; - - private KudosService kudosService; - - public ProfileUpdateListener(KudosService kudosService, ActivityStorage activityStorage) { - this.kudosService = kudosService; - this.activityStorage = activityStorage; - } - - @Override - public void avatarUpdated(ProfileLifeCycleEvent event) { - String userId = event.getProfile().getIdentity().getId(); - this.clearUserActivitiesCache(userId); - } - - @Override - public void bannerUpdated(ProfileLifeCycleEvent event) { - // NOSONAR - } - - @Override - public void contactSectionUpdated(ProfileLifeCycleEvent event) { - String userId = event.getProfile().getIdentity().getId(); - this.clearUserActivitiesCache(userId); - } - - @Override - public void experienceSectionUpdated(ProfileLifeCycleEvent event) { - // NOSONAR - } - - @Override - public void createProfile(ProfileLifeCycleEvent event) { - // NOSONAR - } - - private void clearUserActivitiesCache(String userId) { - long count = kudosService.countKudosByPeriodAndReceiver(Long.parseLong(userId), 0, System.currentTimeMillis()); - List kudosList = kudosService.getKudosByPeriodAndReceiver(Long.parseLong(userId), - 0, - System.currentTimeMillis(), - (int) count); - if (kudosList == null || kudosList.isEmpty()) - return; - kudosList.stream() - .forEach(kudos -> ((CachedActivityStorage) activityStorage).clearActivityCached(String.valueOf(kudos.getActivityId()))); - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/model/AccountSettings.java b/kudos-services/src/main/java/org/exoplatform/kudos/model/AccountSettings.java deleted file mode 100644 index 99cc903f5..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/model/AccountSettings.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.exoplatform.kudos.model; - -import lombok.*; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class AccountSettings { - - private boolean disabled; - - private long remainingKudos; - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosEntityType.java b/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosEntityType.java deleted file mode 100644 index a6167296a..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosEntityType.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.exoplatform.kudos.model; - -public enum KudosEntityType { - ACTIVITY, COMMENT, USER_PROFILE, USER_TIPTIP, SPACE_PROFILE, SPACE_TIPTIP, NONE -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosList.java b/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosList.java deleted file mode 100644 index 1d882139f..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosList.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.exoplatform.kudos.model; - -import java.io.Serializable; -import java.util.List; - -import lombok.Data; - -@Data -public class KudosList implements Serializable { - - private static final long serialVersionUID = 5173858331264945555L; - - private List kudos; - - private long limit; - - private long size; - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosPeriod.java b/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosPeriod.java deleted file mode 100644 index 559c66a94..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/model/KudosPeriod.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.exoplatform.kudos.model; - -import org.json.JSONException; -import org.json.JSONObject; - -import lombok.*; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class KudosPeriod { - - private long startDateInSeconds; - - private long endDateInSeconds; - - public JSONObject toJSONObject() { - JSONObject jsonObject = new JSONObject(); - try { - jsonObject.put("startDateInSeconds", startDateInSeconds); - jsonObject.put("endDateInSeconds", endDateInSeconds); - } catch (JSONException e) { - throw new IllegalStateException("Error while converting Object to JSON", e); - } - return jsonObject; - } - - @Override - public String toString() { - return toJSONObject().toString(); - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosAccountREST.java b/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosAccountREST.java deleted file mode 100644 index ea3c8bd8e..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosAccountREST.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2003-2018 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package org.exoplatform.kudos.rest; - -import static org.exoplatform.kudos.service.utils.Utils.getCurrentUserId; - -import javax.annotation.security.RolesAllowed; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.apache.commons.lang3.StringUtils; - -import org.exoplatform.kudos.model.AccountSettings; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.rest.resource.ResourceContainer; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; - -@Path("/kudos/api/account") -@Tag(name = "/kudos/api/account", description = "Retrieve Kudos settings for users and spaces") -@RolesAllowed("users") -public class KudosAccountREST implements ResourceContainer { - private static final Log LOG = ExoLogger.getLogger(KudosAccountREST.class); - - private KudosService kudosService;// NOSONAR - - public KudosAccountREST(KudosService kudosService) { - this.kudosService = kudosService; - } - - @Path("settings") - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation(summary = "Retrieves user/space settings for kudos", method = "GET", description = "returns account settings object") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getSettings() { - try { - AccountSettings accountDetail = kudosService.getAccountSettings(getCurrentUserId()); - if (accountDetail == null) { - accountDetail = new AccountSettings(); - } - return Response.ok(accountDetail).build(); - } catch (Exception e) { - LOG.warn("Error getting kudos settings", e); - return Response.serverError().build(); - } - } - - @Path("isAuthorized") - @GET - @RolesAllowed("users") - @Operation(summary = "Checks if username is authorized to use Kudos", method = "GET", description = "Checks if username is authorized to use Kudos and returns empty response") - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response isAuthorized(@Parameter(description = "User login", required = true) @QueryParam("username") String username) { - if (StringUtils.isBlank(username)) { - LOG.warn("Bad request sent to server with empty 'username'"); - return Response.status(400).build(); - } - try { - if (kudosService.isAuthorizedOnKudosModule(username)) { - return Response.ok().build(); - } else { - return Response.status(403).build(); - } - } catch (Exception e) { - LOG.warn("Error getting kudos authorization for user {}", username, e); - return Response.serverError().build(); - } - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosREST.java b/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosREST.java deleted file mode 100644 index d98b64957..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosREST.java +++ /dev/null @@ -1,545 +0,0 @@ -/* - * Copyright (C) 2003-2018 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package org.exoplatform.kudos.rest; - -import static org.exoplatform.kudos.service.utils.Utils.getCurrentUserId; -import static org.exoplatform.kudos.service.utils.Utils.timeFromSeconds; - -import java.util.List; -import java.util.Locale; - -import javax.annotation.security.RolesAllowed; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.parameters.RequestBody; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; - -import org.exoplatform.commons.exception.ObjectNotFoundException; -import org.exoplatform.kudos.exception.KudosAlreadyLinkedException; -import org.exoplatform.kudos.model.*; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.portal.application.localization.LocalizationFilter; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.rest.resource.ResourceContainer; -import org.exoplatform.services.security.ConversationState; -import org.exoplatform.social.core.identity.model.Identity; -import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; -import org.exoplatform.social.core.manager.IdentityManager; -import org.exoplatform.social.core.utils.MentionUtils; - - -@Path("/kudos/api/kudos") -@Tag(name = "/kudos/api/kudos", description = "Manages Kudos") // NOSONAR -@RolesAllowed("users") -public class KudosREST implements ResourceContainer { - - private static final Log LOG = ExoLogger.getLogger(KudosREST.class); - - private KudosService kudosService; - - private IdentityManager identityManager; - - public KudosREST(IdentityManager identityManager, KudosService kudosService) { - this.identityManager = identityManager; - this.kudosService = kudosService; - } - - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("administrators") - @Operation( - summary = "Get Kudos list created in a period contained a selected date in seconds", - method = "GET", - description = "Get Kudos list created in a period contained a selected date in seconds and returns list of Kudos") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getKudosByPeriodOfDate(@Parameter(description = "Timestamp in seconds of date in the middle of selected period. If not defined, current time will be used.") @QueryParam("dateInSeconds") long dateInSeconds, - @Parameter(description = "Limit of results to return") @QueryParam("limit") int limit) { - if (dateInSeconds == 0) { - dateInSeconds = System.currentTimeMillis() / 1000; - } - try { - List allKudosByPeriod = kudosService.getKudosByPeriodOfDate(dateInSeconds, getLimit(limit)); - translateRoleMentions(allKudosByPeriod.toArray(new Kudos[0])); - return Response.ok(allKudosByPeriod).build(); - } catch (Exception e) { - LOG.warn("Error getting kudos list of period with date {}", dateInSeconds, e); - return Response.serverError().build(); - } - } - - @Path("byEntity") - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation(summary = "Get Kudos list by entity type and id", method = "GET", description = "Get Kudos list by entity type and id and returns list of Kudos") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getEntityKudos(@Parameter(description = "kudos entity type (for example activity, comment...)", required = true) @QueryParam("entityType") String entityType, - @Parameter(description = "kudos entity id", required = true) @QueryParam("entityId") String entityId, - @Parameter(description = "Limit of results to return") @QueryParam("limit") int limit) { - if (StringUtils.isBlank(entityType) || StringUtils.isBlank(entityId)) { - LOG.warn("Bad request sent to server with empty 'attached entity id or type'"); - return Response.status(400).build(); - } - try { - List allKudosByEntity = kudosService.getKudosByEntity(entityType, entityId, getLimit(limit)); - translateRoleMentions(allKudosByEntity.toArray(new Kudos[0])); - return Response.ok(allKudosByEntity).build(); - } catch (Exception e) { - LOG.warn("Error getting kudos entity of entity {}/{}", entityType, entityId, e); - return Response.serverError().build(); - } - } - - @Path("byActivity/{activityId}") - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation(summary = "Get Kudos by its generated comment or activity id", method = "GET", description = "Get Kudos by its generated comment or activity id") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "401", description = "Unauthorized operation"), - @ApiResponse(responseCode = "404", description = "Entity Not found"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getKudosByActivityId( - @Parameter(description = "kudos activity or comment identifier", required = true) - @PathParam("activityId") - String activityId) { - if (StringUtils.isBlank(activityId)) { - LOG.warn("Bad request sent to server with empty 'attached activityId'"); - return Response.status(Status.BAD_REQUEST).build(); - } - org.exoplatform.services.security.Identity currentUser = ConversationState.getCurrent().getIdentity(); - try { - Kudos kudos = kudosService.getKudosByActivityId(getActivityId(activityId), currentUser); - translateRoleMentions(kudos); - return Response.ok(kudos).build(); - } catch (IllegalAccessException e) { - LOG.error("Access denied to user {} to access Kudos of activity by id {}", currentUser.getUserId(), activityId); - return Response.status(Status.NOT_FOUND).build(); - } catch (Exception e) { - LOG.warn("Error getting kudos by activity Id {}", activityId, e); - return Response.serverError().build(); - } - } - - @Path("byActivity/{activityId}/all") - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation( - summary = "Get Kudos List attached to a parent activity, whether the activity itself or in a comment", - method = "GET", - description = "Get Kudos List attached to a parent activity, whether the activity itself or in a comment") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "401", description = "Unauthorized operation"), - @ApiResponse(responseCode = "404", description = "Entity Not found"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getKudosListOfActivity(@Parameter(description = "kudos parent activity identifier", required = true) - @PathParam("activityId") - String activityId) { - if (StringUtils.isBlank(activityId)) { - LOG.warn("Bad request sent to server with empty 'activityId'"); - return Response.status(Status.BAD_REQUEST).build(); - } - org.exoplatform.services.security.Identity currentUser = ConversationState.getCurrent().getIdentity(); - try { - List kudosList = kudosService.getKudosListOfActivity(activityId, currentUser); - translateRoleMentions(kudosList.toArray(new Kudos[0])); - return Response.ok(kudosList).build(); - } catch (IllegalAccessException e) { - LOG.error("Access denied to user {} to access Kudos of parent activity by id {}", currentUser.getUserId(), activityId); - return Response.status(Status.NOT_FOUND).build(); - } catch (Exception e) { - LOG.warn("Error getting kudos by parent activity Id {}", activityId, e); - return Response.serverError().build(); - } - } - - @Path("byEntity/sent/count") - @GET - @Produces(MediaType.TEXT_PLAIN) - @RolesAllowed("users") - @Operation( - summary = "Get Kudos count by entity and current user as sender", - method = "GET", - description = "Get Kudos count by entity and current user as sender" - ) - @ApiResponses( - value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") } - ) - public Response countKudosByEntityAndSender( - @Parameter( - description = "kudos entity type (for example activity, comment...)", - required = true - ) - @QueryParam("entityType") - String entityType, - @Parameter(description = "kudos entity id", required = true) - @QueryParam("entityId") - String entityId) { - if (StringUtils.isBlank(entityType) || StringUtils.isBlank(entityId)) { - LOG.warn("Bad request sent to server with empty 'attached entity id or type'"); - return Response.status(400).build(); - } - String currentUsername = getCurrentUserId(); - Identity identity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, currentUsername); - if (identity == null) { - return Response.status(400).entity("Can't find current user identity").build(); - } - try { - long count = kudosService.countKudosByEntityAndSender(entityType, entityId, identity.getId()); - return Response.ok(String.valueOf(count)).build(); - } catch (Exception e) { - LOG.warn("Error getting kudos entity of entity {}/{}", entityType, entityId, e); - return Response.serverError().build(); - } - } - - @GET - @Path("byDates") - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("administrators") - @Operation( - summary = "Get Kudos list created between start and end dates in seconds", - method = "GET", - description = "Get Kudos list created between start and end dates in seconds") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getKudosByDates(@QueryParam("startDateInSeconds") long startDateInSeconds, - @QueryParam("endDateInSeconds") long endDateInSeconds, - @Parameter(description = "Limit of results to return") @QueryParam("limit") int limit) { - if (startDateInSeconds == 0 || endDateInSeconds == 0) { - LOG.warn("Bad request sent to server with empty 'start or end' dates parameter"); - return Response.status(400).build(); - } - try { - List allKudosByPeriod = kudosService.getKudosByPeriod(startDateInSeconds, endDateInSeconds, getLimit(limit)); - translateRoleMentions(allKudosByPeriod.toArray(new Kudos[0])); - return Response.ok(allKudosByPeriod).build(); - } catch (Exception e) { - LOG.warn("Error getting kudos list of period: from {} to {}", startDateInSeconds, endDateInSeconds, e); - return Response.serverError().build(); - } - } - - @GET - @Path("{identityId}/received") - @RolesAllowed("users") - @Produces(MediaType.APPLICATION_JSON) - @Operation( - summary = "Retrieve the list of received Kudos by a user or space in a selected period", - method = "GET", - description = "Retrieve the list of received Kudos by a user or space in a selected period") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "500", description = "Internal server error") - }) - public Response getReceivedKudosByPeriod(@Parameter(description = "User or space identity technical id", required = true) @PathParam("identityId") long identityId, - @Parameter(description = "Date in the middle of a period defined using a timestamp in seconds", required = true) @QueryParam("dateInSeconds") long dateInSeconds, - @Parameter(description = "Period type, can be: WEEK, MONTH, QUARTER, SEMESTER and YEAR. Default is the same as configured period", required = true) @QueryParam("periodType") String periodType, - @Parameter(description = "Limit of kudos to retrieve, if equal to 0, no kudos will be retrieved", required = true) @QueryParam("limit") int limit, - @Parameter(description = "Whether return size of received kudos, default = false") @QueryParam("returnSize") boolean returnSize) { - if (identityId <= 0) { - return Response.status(400).entity("identityId is mandatory").build(); - } - if (dateInSeconds < 0) { - return Response.status(400).entity("dateInSeconds parameter should be a positive number").build(); - } - if (limit < 0) { - return Response.status(400).entity("limit parameter should be a positive number").build(); - } - if (!returnSize && limit == 0) { - return Response.status(400) - .entity("you should whether use 'limit' to get a list of kudos or 'returnSize' to return the size") - .build(); - } - - Identity identity = identityManager.getIdentity(String.valueOf(identityId)); - if (identity == null) { - return Response.status(400).entity("Can't find identity with id " + identityId).build(); - } - - if (dateInSeconds == 0) { - dateInSeconds = System.currentTimeMillis() / 1000; - } - - KudosPeriodType kudosPeriodType = null; - if (StringUtils.isBlank(periodType)) { - kudosPeriodType = kudosService.getDefaultKudosPeriodType(); - } else { - try { - kudosPeriodType = KudosPeriodType.valueOf(periodType.toUpperCase()); - } catch (Exception e) { - return Response.status(400).entity("periodType '" + periodType + "' is not valid").build(); - } - } - - KudosPeriod period = kudosPeriodType.getPeriodOfTime(timeFromSeconds(dateInSeconds)); - KudosList kudosList = new KudosList(); - if (returnSize) { - long size = kudosService.countKudosByPeriodAndReceiver(identityId, - period.getStartDateInSeconds(), - period.getEndDateInSeconds()); - kudosList.setSize(size); - if (size == 0 || limit == 0) { - return Response.ok(kudosList).build(); - } - } - List kudos = kudosService.getKudosByPeriodAndReceiver(identityId, - period.getStartDateInSeconds(), - period.getEndDateInSeconds(), - getLimit(limit)); - translateRoleMentions(kudos.toArray(new Kudos[0])); - kudosList.setKudos(kudos); - return Response.ok(kudosList).build(); - } - - @Path("{identityId}/sent") - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation( - summary = "Retrieve the list of sent Kudos for a user in a selected period", - method = "GET", - description = "Retrieve the list of sent Kudos for a user in a selected period") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getSentKudosByPeriod(@Parameter(description = "User or space identity technical id", required = true) @PathParam("identityId") long identityId, - @Parameter(description = "Date in the middle of a period defined using a timestamp in seconds") @QueryParam("dateInSeconds") long dateInSeconds, - @Parameter(description = "Period type, can be: WEEK, MONTH, QUARTER, SEMESTER and YEAR. Default is the same as configured period") @QueryParam("periodType") String periodType, - @Parameter(description = "Limit of kudos to retrieve, if equal to 0, no kudos will be retrieved") @QueryParam("limit") int limit, - @Parameter(description = "Whether return size of sent kudos, default = false") @QueryParam("returnSize") boolean returnSize) { - if (identityId <= 0) { - return Response.status(400).entity("identityId is mandatory").build(); - } - if (dateInSeconds < 0) { - return Response.status(400).entity("dateInSeconds parameter should be a positive number").build(); - } - if (limit < 0) { - return Response.status(400).entity("limit parameter should be a positive number").build(); - } - if (!returnSize && limit == 0) { - return Response.status(400) - .entity("you should whether use 'limit' to get a list of kudos or 'returnSize' to return the size") - .build(); - } - - Identity identity = identityManager.getIdentity(String.valueOf(identityId)); - if (identity == null) { - return Response.status(400).entity("Can't find identity with id " + identityId).build(); - } - - if (dateInSeconds == 0) { - dateInSeconds = System.currentTimeMillis() / 1000; - } - - KudosPeriodType kudosPeriodType = null; - if (StringUtils.isBlank(periodType)) { - kudosPeriodType = kudosService.getDefaultKudosPeriodType(); - } else { - try { - kudosPeriodType = KudosPeriodType.valueOf(periodType.toUpperCase()); - } catch (Exception e) { - return Response.status(400).entity("periodType '" + periodType + "' is not valid").build(); - } - } - - KudosPeriod period = kudosPeriodType.getPeriodOfTime(timeFromSeconds(dateInSeconds)); - KudosList kudosList = new KudosList(); - if (returnSize) { - long size = kudosService.countKudosByPeriodAndSender(identityId, - period.getStartDateInSeconds(), - period.getEndDateInSeconds()); - kudosList.setSize(size); - if (size == 0 || limit == 0) { - return Response.ok(kudosList).build(); - } - } - - List kudos = kudosService.getKudosByPeriodAndSender(identityId, - period.getStartDateInSeconds(), - period.getEndDateInSeconds(), - getLimit(limit)); - translateRoleMentions(kudos.toArray(new Kudos[0])); - kudosList.setKudos(kudos); - return Response.ok(kudosList).build(); - } - - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation( - summary = "Creates new Kudos", - method = "POST", - description = "Creates new Kudos and returns an empty response" - ) - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response createKudos(@RequestBody(description = "Kudos object to create", required = true) Kudos kudos) { - if (kudos == null) { - LOG.warn("Bad request sent to server with empty kudos"); - return Response.status(400).build(); - } - if (StringUtils.isBlank(kudos.getReceiverId()) || StringUtils.isBlank(kudos.getReceiverType())) { - LOG.warn("Bad request sent to server with empty 'receiver id or type'"); - return Response.status(400).build(); - } - if (StringUtils.isNotBlank(kudos.getSenderId())) { - LOG.warn("Bad request sent to server with a preset 'sender'"); - return Response.status(400).build(); - } - if (StringUtils.isBlank(kudos.getEntityId()) || StringUtils.isBlank(kudos.getEntityType())) { - LOG.warn("Bad request sent to server with empty 'attached entity id or type'"); - return Response.status(400).build(); - } - try { - kudos.setSenderId(getCurrentUserId()); - Kudos kudosSent = kudosService.createKudos(kudos, getCurrentUserId()); - translateRoleMentions(kudosSent); - return Response.ok(kudosSent).build(); - } catch (Exception e) { - LOG.warn("Error saving kudos: {}", kudos, e); - return Response.serverError().build(); - } - } - - @DELETE - @Path("{kudosId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation(summary = "Cancels a sent kudos", method = "DELETE", description = "Cancels a sent kudos") - @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "404", description = "Object not found"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "401", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error"), }) - public Response deleteKudos(@Parameter(description = "Kudos technical identifier", required = true) - @PathParam("kudosId") long kudosId) { - - String currentUser = getCurrentUserId(); - - try { - kudosService.deleteKudosById(kudosId, currentUser); - return Response.noContent().build(); - } catch (IllegalAccessException e) { - LOG.debug("User '{}' doesn't have enough privileges to delete kudos with id {}", currentUser, kudosId, e); - return Response.status(Response.Status.UNAUTHORIZED).entity(e.getMessage()).build(); - } catch (ObjectNotFoundException e) { - LOG.debug("User '{}' attempts to delete a not existing kudos '{}'", currentUser, e); - return Response.status(Response.Status.NOT_FOUND).entity("kudos not found").build(); - } catch (KudosAlreadyLinkedException e) { - LOG.debug("User '{}' attempts to delete a kudos '{}' already linked to kudos entities", currentUser, e); - return Response.status(Response.Status.UNAUTHORIZED).entity("KudosAlreadyLinked").build(); - } catch (Exception e) { - LOG.warn("Error canceling kudos: {}", e); - return Response.serverError().build(); - } - } - - @Path("period") - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation( - summary = "Get Kudos period of time by computing it using period type and a selected date", - method = "GET", - description = "Get Kudos period of time by computing it using period type and a selected date") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getPeriodDates(@Parameter(description = "Period type, can be: WEEK, MONTH, QUARTER, SEMESTER and YEAR. Default is the same as configured period") @QueryParam("periodType") String periodType, - @Parameter(description = "Date in the middle of a period defined using a timestamp in seconds") @QueryParam("dateInSeconds") long dateInSeconds) { - if (dateInSeconds == 0) { - LOG.warn("Bad request sent to server with empty 'dateInSeconds' parameter"); - return Response.status(400).build(); - } - if (StringUtils.isBlank(periodType)) { - LOG.warn("Bad request sent to server with empty 'periodType' parameter"); - return Response.status(400).build(); - } - try { - KudosPeriodType kudosPeriodType = KudosPeriodType.valueOf(periodType); - KudosPeriod kudosPeriod = kudosPeriodType.getPeriodOfTime(timeFromSeconds(dateInSeconds)); - return Response.ok(kudosPeriod.toString()).build(); - } catch (Exception e) { - LOG.warn("Error getting period dates of type {} and date {}", periodType, dateInSeconds, e); - return Response.serverError().build(); - } - } - - private int getLimit(int limit) { - if (limit <= 0) { - limit = 1000; - } - return limit; - } - - private Long getActivityId(String commentId) { - return (commentId == null || commentId.trim().isEmpty()) ? null : Long.valueOf(commentId.replace("comment", "")); - } - - private void translateRoleMentions(Kudos ...kudosList) { - if (ArrayUtils.isEmpty(kudosList)) { - return; - } - Locale userLocale = LocalizationFilter.getCurrentLocale(); - for (Kudos kudos : kudosList) { - if (kudos != null) { - kudos.setMessage(MentionUtils.substituteUsernames(kudos.getMessage(), userLocale)); - } - } - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosSettingsREST.java b/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosSettingsREST.java deleted file mode 100644 index f1ef21395..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/rest/KudosSettingsREST.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2003-2018 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ -package org.exoplatform.kudos.rest; - -import javax.annotation.security.RolesAllowed; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; -import org.exoplatform.kudos.model.GlobalSettings; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.services.rest.resource.ResourceContainer; - - -@Path("/kudos/api/settings") -@Tag(name = "/kudos/api/settings", description = "Manages Kudos global settings") -@RolesAllowed("users") -public class KudosSettingsREST implements ResourceContainer { - private static final Log LOG = ExoLogger.getLogger(KudosSettingsREST.class); - - private KudosService kudosService; - - public KudosSettingsREST(KudosService kudosService) { - this.kudosService = kudosService; - } - - @GET - @Produces(MediaType.APPLICATION_JSON) - @RolesAllowed("users") - @Operation(summary = "Get Kudos global settings", method = "GET", description = "Get Kudos global settings") - @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Request fulfilled"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response getSettings() { - return Response.ok(kudosService.getGlobalSettings().toString()).build(); - } - - @Path("save") - @POST - @Consumes(MediaType.APPLICATION_JSON) - @RolesAllowed("administrators") - @Operation( - summary = "Saves Kudos global settings", - method = "POST", - description = "Saves Kudos global settings and returns an empty response") - @ApiResponses(value = { - @ApiResponse(responseCode = "204", description = "Request fulfilled"), - @ApiResponse(responseCode = "400", description = "Invalid query input"), - @ApiResponse(responseCode = "403", description = "Unauthorized operation"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) - public Response saveSettings(GlobalSettings settings) { - if (settings == null) { - LOG.warn("Bad request sent to server with empty 'settings' parameter"); - return Response.status(400).build(); - } - try { - kudosService.saveGlobalSettings(settings); - return Response.noContent().build(); - } catch (Exception e) { - LOG.warn("Error saving kudos settings: {}", settings, e); - return Response.serverError().build(); - } - } - -} diff --git a/kudos-services/src/main/java/org/exoplatform/kudos/storage/KudosStorage.java b/kudos-services/src/main/java/org/exoplatform/kudos/storage/KudosStorage.java deleted file mode 100644 index 76f66728a..000000000 --- a/kudos-services/src/main/java/org/exoplatform/kudos/storage/KudosStorage.java +++ /dev/null @@ -1,233 +0,0 @@ -package org.exoplatform.kudos.storage; - -import static org.exoplatform.kudos.service.utils.Utils.USER_ACCOUNT_TYPE; -import static org.exoplatform.kudos.service.utils.Utils.fromEntity; -import static org.exoplatform.kudos.service.utils.Utils.getSpace; -import static org.exoplatform.kudos.service.utils.Utils.toEntity; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections.CollectionUtils; -import org.picocontainer.Startable; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import org.exoplatform.commons.utils.CommonsUtils; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.kudos.dao.KudosDAO; -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.model.KudosPeriod; -import org.exoplatform.kudos.service.utils.Utils; -import org.exoplatform.services.log.ExoLogger; -import org.exoplatform.services.log.Log; -import org.exoplatform.social.core.identity.model.Identity; -import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; -import org.exoplatform.social.core.identity.provider.SpaceIdentityProvider; -import org.exoplatform.social.core.manager.IdentityManager; -import org.exoplatform.social.core.space.model.Space; - -@Service // FIXME Should be @Repository instead, but Kept with @Service to expose it - // into Kernel Container -public class KudosStorage implements Startable { - - private static final Log LOG = ExoLogger.getLogger(KudosStorage.class); - - @Autowired - private KudosDAO kudosDAO; - - @Autowired - private IdentityManager identityManager; - - /** - * @deprecated kept to be able to use this service as Kernel Service in Unit - * Tests To delete once the Unit Tests migrated - * with Spring and JUnit 5 - */ - @Override - @Deprecated(forRemoval = true, since = "1.6.0") - public void start() { - PortalContainer container = PortalContainer.getInstance(); - this.kudosDAO = container.getComponentInstanceOfType(KudosDAO.class); - this.identityManager = container.getComponentInstanceOfType(IdentityManager.class); - } - - public Kudos getKudoById(long id) { - KudosEntity kudosEntity = kudosDAO.find(id); - if (kudosEntity == null) { - LOG.warn("Can't find Kudos with id {}", id); - return null; - } else { - return fromEntity(kudosEntity); - } - } - - public Kudos createKudos(Kudos kudos) { - KudosEntity kudosEntity = toEntity(kudos); - kudosEntity.setId(null); - kudosEntity = kudosDAO.create(kudosEntity); - return fromEntity(kudosEntity); - } - - public void deleteKudosById(long kudosId) { - KudosEntity kudosEntity = this.kudosDAO.find(kudosId); - if (kudosEntity == null) { - return; - } - kudosDAO.delete(kudosEntity); - } - - public void saveKudosActivityId(long kudosId, long activityId) { - KudosEntity kudosEntity = kudosDAO.find(kudosId); - if (kudosEntity == null) { - throw new IllegalStateException("Can't find Kudos with id " + kudosId); - } else { - kudosEntity.setActivityId(activityId); - kudosDAO.update(kudosEntity); - } - } - - public List getKudosByPeriod(KudosPeriod kudosPeriod, int limit) { - List kudosList = new ArrayList<>(); - List kudosEntities = kudosDAO.getKudosByPeriod(kudosPeriod, limit); - if (kudosEntities != null) { - for (KudosEntity kudosEntity : kudosEntities) { - if (kudosEntity != null) { - kudosList.add(fromEntity(kudosEntity)); - } - } - } - return kudosList; - } - - public List getKudosByEntity(String entityType, String entityId, int limit) { - List kudosList = new ArrayList<>(); - List kudosEntities = kudosDAO.getKudosByEntity(KudosEntityType.valueOf(entityType).ordinal(), - Long.parseLong(entityId), - limit); - if (kudosEntities != null) { - for (KudosEntity kudosEntity : kudosEntities) { - if (kudosEntity != null) { - kudosList.add(fromEntity(kudosEntity)); - } - } - } - return kudosList; - } - - public long countKudosByEntity(String entityType, String entityId) { - return kudosDAO.countKudosByEntity(KudosEntityType.valueOf(entityType).ordinal(), Long.parseLong(entityId)); - } - - public long countKudosByEntityAndSender(String entityType, String entityId, String senderIdentityId) { - return kudosDAO.countKudosByEntityAndSender(KudosEntityType.valueOf(entityType).ordinal(), - Long.parseLong(entityId), - Long.parseLong(senderIdentityId)); - } - - public long countKudosByPeriodAndReceiver(KudosPeriod kudosPeriod, String receiverType, String receiverId) { - boolean isReceiverUser = USER_ACCOUNT_TYPE.equals(receiverType) || OrganizationIdentityProvider.NAME.equals(receiverType); - Identity identity = getIdentityManager().getOrCreateIdentity(isReceiverUser ? OrganizationIdentityProvider.NAME - : SpaceIdentityProvider.NAME, - receiverId); - return kudosDAO.countKudosByPeriodAndReceiver(kudosPeriod, - Long.parseLong(identity.getId()), - isReceiverUser); - } - - public Map countKudosByPeriodAndReceivers(KudosPeriod kudosPeriod, List receiversId) { - return kudosDAO.countKudosByPeriodAndReceivers(kudosPeriod, receiversId); - } - - public List getKudosByPeriodAndReceiver(KudosPeriod kudosPeriod, String receiverType, String receiverId, int limit) { - boolean isReceiverUser = USER_ACCOUNT_TYPE.equals(receiverType) || OrganizationIdentityProvider.NAME.equals(receiverType); - long identityId = getIdentityId(receiverId, isReceiverUser); - if (identityId <= 0) { - return Collections.emptyList(); - } - List kudosEntities = kudosDAO.getKudosByPeriodAndReceiver(kudosPeriod, - identityId, - isReceiverUser, - limit); - if (kudosEntities != null) { - List kudosList = new ArrayList<>(); - for (KudosEntity kudosEntity : kudosEntities) { - if (kudosEntity != null) { - kudosList.add(fromEntity(kudosEntity)); - } - } - return kudosList; - } - return Collections.emptyList(); - } - - public List getKudosByPeriodAndSender(KudosPeriod kudosPeriod, long senderIdentityId, int limit) { - List kudosList = new ArrayList<>(); - List kudosEntities = kudosDAO.getKudosByPeriodAndSender(kudosPeriod, senderIdentityId, limit); - if (kudosEntities != null) { - for (KudosEntity kudosEntity : kudosEntities) { - if (kudosEntity != null) { - kudosList.add(fromEntity(kudosEntity)); - } - } - } - return kudosList; - } - - public long countKudosByPeriodAndSender(KudosPeriod kudosPeriod, long senderIdentityId) { - return kudosDAO.countKudosByPeriodAndSender(kudosPeriod, senderIdentityId); - } - - private long getIdentityId(String remoteId, boolean isReceiverUser) { - long identityId = 0; - if (isReceiverUser) { - Identity identity = getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, remoteId); - if (identity == null) { - return 0; - } - identityId = Long.parseLong(identity.getId()); - } else { - Space space = getSpace(remoteId); - if (space == null) { - return 0; - } - identityId = Long.parseLong(space.getId()); - } - return identityId; - } - - private IdentityManager getIdentityManager() { - if (identityManager == null) { - identityManager = CommonsUtils.getService(IdentityManager.class); - } - return identityManager; - } - - public Kudos getKudosByActivityId(Long activityId) { - KudosEntity kudosEntity = kudosDAO.getKudosByActivityId(activityId); - return fromEntity(kudosEntity); - } - - public List getKudosListOfActivity(Long activityId) { - List kudosEntities = kudosDAO.getKudosListOfActivity(activityId); - return CollectionUtils.isEmpty(kudosEntities) ? Collections.emptyList() - : kudosEntities.stream() - .map(Utils::fromEntity) - .toList(); - } - - public long countKudosOfActivity(Long activityId) { - return kudosDAO.countKudosOfActivity(activityId); - } - - public Kudos updateKudos(Kudos kudos) { - KudosEntity kudosEntity = toEntity(kudos); - kudosEntity = kudosDAO.update(kudosEntity); - return fromEntity(kudosEntity); - } - -} diff --git a/kudos-services/src/main/resources/conf/portal/configuration.xml b/kudos-services/src/main/resources/conf/portal/configuration.xml deleted file mode 100644 index ec44ef043..000000000 --- a/kudos-services/src/main/resources/conf/portal/configuration.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - org.exoplatform.kudos.dao.KudosDAO - - - - org.exoplatform.kudos.service.KudosService - - - defaultAccessPermission - Default access permissions for Kudos Feature - ${exo.kudos.defaultAccessPermission:} - - - defaultKudosPerPeriod - Default number of kudos per user per period of time - ${exo.kudos.defaultKudosPerPeriod:3} - - - - - - org.exoplatform.kudos.rest.KudosAccountREST - - - - org.exoplatform.kudos.rest.KudosREST - - - - org.exoplatform.kudos.rest.KudosSettingsREST - - - - org.exoplatform.commons.api.persistence.DataInitializer - - KudosRDBMSChangeLogsPlugin - addChangeLogsPlugin - org.exoplatform.commons.persistence.impl.ChangeLogsPlugin - - - changelogs - Change logs of Kudos RDBMS - db/changelog/kudos-rdbms.db.changelog-master.xml - - - - - - - org.exoplatform.social.core.manager.ActivityManager - - KudosActivityListener - addActivityEventListener - org.exoplatform.kudos.listener.KudosActivityListener - update kudos activity listener - - - - - org.exoplatform.services.listener.ListenerService - - exo.kudos.sent - addListener - org.exoplatform.kudos.listener.analytics.KudosSentListener - - - - - org.exoplatform.social.core.manager.IdentityManager - - ProfileUpdateListener - addProfileListener - org.exoplatform.kudos.listener.ProfileUpdateListener - - - \ No newline at end of file diff --git a/kudos-services/src/main/resources/jpa-entities.idx b/kudos-services/src/main/resources/jpa-entities.idx new file mode 100644 index 000000000..d9d614114 --- /dev/null +++ b/kudos-services/src/main/resources/jpa-entities.idx @@ -0,0 +1,2 @@ +io.meeds.appcenter.entity.ApplicationEntity +io.meeds.appcenter.entity.FavoriteApplicationEntity diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/BaseKudosTest.java b/kudos-services/src/test/java/io/meeds/kudos/BaseKudosTest.java similarity index 51% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/BaseKudosTest.java rename to kudos-services/src/test/java/io/meeds/kudos/BaseKudosTest.java index 024176402..147c489ea 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/BaseKudosTest.java +++ b/kudos-services/src/test/java/io/meeds/kudos/BaseKudosTest.java @@ -1,79 +1,108 @@ -package org.exoplatform.kudos.test; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.time.LocalDate; import java.time.ZoneId; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.exoplatform.component.test.AbstractKernelTest; import org.exoplatform.component.test.ConfigurationUnit; import org.exoplatform.component.test.ConfiguredBy; import org.exoplatform.component.test.ContainerScope; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.kudos.dao.KudosDAO; -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.service.utils.Utils; +import io.meeds.kernel.test.AbstractSpringTest; +import io.meeds.kernel.test.KernelExtension; +import io.meeds.kudos.dao.KudosDAO; +import io.meeds.kudos.entity.KudosEntity; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosEntityType; +import io.meeds.kudos.service.utils.Utils; +import io.meeds.spring.AvailableIntegration; + +@ExtendWith({ SpringExtension.class, KernelExtension.class }) +@SpringBootApplication(scanBasePackages = { + BaseKudosTest.MODULE_NAME, + AvailableIntegration.KERNEL_TEST_MODULE, + AvailableIntegration.JPA_MODULE, + AvailableIntegration.LIQUIBASE_MODULE, + AvailableIntegration.WEB_MODULE, +}) +@EnableJpaRepositories(basePackages = BaseKudosTest.MODULE_NAME) +@TestPropertySource(properties = { + "spring.liquibase.change-log=" + BaseKudosTest.CHANGELOG_PATH, + "spring.profiles.active=gamification", +}) @ConfiguredBy({ @ConfigurationUnit(scope = ContainerScope.ROOT, path = "conf/configuration.xml"), @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/configuration.xml"), - @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/kudos-test-configuration.xml"), + @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/kudos-test-configuration.xml"), }) -public abstract class BaseKudosTest extends AbstractKernelTest { +public abstract class BaseKudosTest extends AbstractSpringTest { - protected static final String DEFAULT_PORTAL = "meeds"; + public static final String MODULE_NAME = "io.meeds.kudos"; - protected KudosEntityType kudosEntityType = KudosEntityType.USER_TIPTIP; + public static final String CHANGELOG_PATH = "classpath:db/changelog/kudos-rdbms.db.changelog-master.xml"; - protected int entityType = kudosEntityType.ordinal(); + protected KudosEntityType kudosEntityType = KudosEntityType.USER_TIPTIP; - protected long entityId = 1; + protected int entityType = kudosEntityType.ordinal(); - protected long parentEntityId = 2; + protected long entityId = 1; - protected long receiverId = 3; + protected long parentEntityId = 2; - protected long senderId = 4; + protected long receiverId = 3; - protected long createdTimestamp = System.currentTimeMillis() / 1000; + protected long senderId = 4; - protected String message = "message"; + protected long createdTimestamp = System.currentTimeMillis() / 1000; - protected PortalContainer container; + protected String message = "message"; - @Before - @Override - public void setUp() throws Exception { - container = getContainer(); - assertNotNull("Container shouldn't be null", container); - assertTrue("Container should have been started", container.isStarted()); + @BeforeEach + public void setUp() { + getContainer(); begin(); - super.setUp(); } - @After - @Override - public void tearDown() throws Exception { - KudosDAO kudosDAO = getService(KudosDAO.class); - - restartTransaction(); - - kudosDAO.deleteAll(); - - int kudosCount = kudosDAO.findAll().size(); - assertEquals("The previous test didn't cleaned kudos entities correctly, should add entities to clean into 'entitiesToClean' list.", - 0, - kudosCount); - + @AfterEach + public void tearDown() { + if (getKudosDAO() != null) { + restartTransaction(); + getKudosDAO().deleteAll(); + } end(); - super.tearDown(); } - protected T getService(Class componentType) { - return container.getComponentInstanceOfType(componentType); + public KudosDAO getKudosDAO() { + return getContainer().getComponentInstanceOfType(KudosDAO.class); } protected Kudos newKudosDTO() { @@ -84,7 +113,7 @@ protected Kudos newKudosDTO() { protected KudosEntity newKudos() { return newKudos(parentEntityId, entityId, entityType, receiverId, senderId, createdTimestamp, message); } - + protected KudosEntity newKudosInstance() { return newKudosInstance(parentEntityId, entityId, entityType, receiverId, senderId, createdTimestamp, message); } @@ -96,8 +125,7 @@ protected KudosEntity newKudos(long parentEntityId, long senderId, long createdTimestamp, String message) { - KudosDAO kudosDAO = getService(KudosDAO.class); - + assertNotNull(getKudosDAO()); KudosEntity kudosEntity = newKudosInstance(parentEntityId, entityId, entityType, @@ -105,7 +133,7 @@ protected KudosEntity newKudos(long parentEntityId, senderId, createdTimestamp, message); - return kudosDAO.create(kudosEntity); + return getKudosDAO().save(kudosEntity); } private KudosEntity newKudosInstance(long parentEntityId, diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/listener/GamificationIntegrationListenerTest.java b/kudos-services/src/test/java/io/meeds/kudos/listener/GamificationIntegrationListenerTest.java similarity index 80% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/listener/GamificationIntegrationListenerTest.java rename to kudos-services/src/test/java/io/meeds/kudos/listener/GamificationIntegrationListenerTest.java index ab6ebafde..e412ae61a 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/listener/GamificationIntegrationListenerTest.java +++ b/kudos-services/src/test/java/io/meeds/kudos/listener/GamificationIntegrationListenerTest.java @@ -1,42 +1,52 @@ /** * This file is part of the Meeds project (https://meeds.io/). - * - * Copyright (C) 2020 - 2023 Meeds Association contact@meeds.io - * + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.test.listener; +package io.meeds.kudos.listener; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_CANCEL_EVENT; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_GENERIC_EVENT; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_RECEIVE_KUDOS_EVENT_NAME; -import static org.exoplatform.kudos.service.utils.Utils.GAMIFICATION_SEND_KUDOS_EVENT_NAME; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_CANCEL_EVENT; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_GENERIC_EVENT; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_RECEIVE_KUDOS_EVENT_NAME; +import static io.meeds.kudos.service.utils.Utils.GAMIFICATION_SEND_KUDOS_EVENT_NAME; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.codec.binary.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.kudos.test.BaseKudosTest; import org.exoplatform.services.listener.Asynchronous; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.listener.ListenerService; +import io.meeds.kudos.BaseKudosTest; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosEntityType; +import io.meeds.kudos.service.KudosService; + +@SpringJUnitConfig(BaseKudosTest.class) public class GamificationIntegrationListenerTest extends BaseKudosTest { private static final String SENDER_REMOTE_ID = "root4"; @@ -53,16 +63,19 @@ public class GamificationIntegrationListenerTest extends BaseKudosTest { private static boolean listenerInstalled; + @Autowired private KudosService kudosService; + @Autowired + private ListenerService listenerService; + + @BeforeEach @Override - public void setUp() throws Exception { + public void setUp() { super.setUp(); - kudosService = getService(KudosService.class); resetCounters(); if (!listenerInstalled) { Listener, String> listener = newListener(); - ListenerService listenerService = getService(ListenerService.class); listenerService.addListener(GAMIFICATION_GENERIC_EVENT, listener); listenerService.addListener(GAMIFICATION_CANCEL_EVENT, listener); listenerInstalled = true; @@ -119,8 +132,8 @@ private void waitForListenerToBeCalled() { if (GAMIFICATION_LISTENER_COUNT.get() == 2) { break; } else if (GAMIFICATION_LISTENER_COUNT.get() > 2) { - throw new IllegalStateException("Listener shouldn't be invoked more than twice, but was: " - + GAMIFICATION_LISTENER_COUNT.get()); + throw new IllegalStateException("Listener shouldn't be invoked more than twice, but was: " + + GAMIFICATION_LISTENER_COUNT.get()); } try { Thread.sleep(1000); @@ -128,7 +141,7 @@ private void waitForListenerToBeCalled() { Thread.currentThread().interrupt(); } } - assertTrue("Listener seems not being executed after 3 tentatives", tentatives >= 0); + assertTrue(tentatives >= 0); } @Asynchronous diff --git a/kudos-services/src/test/java/io/meeds/kudos/listener/ProfileUpdateListenerTest.java b/kudos-services/src/test/java/io/meeds/kudos/listener/ProfileUpdateListenerTest.java new file mode 100644 index 000000000..457b2dff3 --- /dev/null +++ b/kudos-services/src/test/java/io/meeds/kudos/listener/ProfileUpdateListenerTest.java @@ -0,0 +1,92 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.listener; + +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; + +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import org.exoplatform.social.core.identity.model.Identity; +import org.exoplatform.social.core.identity.model.Profile; +import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; +import org.exoplatform.social.core.manager.IdentityManager; +import org.exoplatform.social.core.storage.cache.CachedActivityStorage; + +import io.meeds.kudos.BaseKudosTest; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +@SpringJUnitConfig(BaseKudosTest.class) +public class ProfileUpdateListenerTest extends BaseKudosTest { + + @Mock + private KudosService kudosService; + + @Mock + private CachedActivityStorage activityStorage; + + @Autowired + private IdentityManager identityManager; + + @Test + public void testUpdateProfileAndDetectChanges() { + ProfileUpdateListener profileUpdateListener = new ProfileUpdateListener(activityStorage, kudosService, identityManager); + Identity rootIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, "root1"); + Profile profile = rootIdentity.getProfile(); + identityManager.registerProfileListener(profileUpdateListener); + Kudos kudos = new Kudos(); + kudos.setActivityId(1); + when(kudosService.countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong())).thenReturn(1L); + when(kudosService.getKudosByPeriodAndReceiver(anyLong(), + anyLong(), + anyLong(), + anyInt())).thenReturn(Collections.singletonList(kudos)); + doNothing().when((activityStorage)).clearActivityCached(anyString()); + profile.setProperty(Profile.FIRST_NAME, "Changed Firstname"); + identityManager.updateProfile(profile); + verify(activityStorage, times(1)).clearActivityCached(anyString()); + verify(kudosService, times(1)).countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong()); + verify(kudosService, times(1)).getKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong(), anyInt()); + + profile.setProperty(Profile.ABOUT_ME, "Changed ABOUT_ME"); + profile.removeProperty(Profile.FIRST_NAME); + identityManager.updateProfile(profile); + verify(activityStorage, times(1)).clearActivityCached(anyString()); + verify(kudosService, times(1)).countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong()); + verify(kudosService, times(1)).getKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong(), anyInt()); + + profile.setProperty(Profile.AVATAR, "new/avatar"); + identityManager.updateProfile(profile); + verify(activityStorage, times(2)).clearActivityCached(anyString()); + verify(kudosService, times(2)).countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong()); + verify(kudosService, times(2)).getKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong(), anyInt()); + } +} diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/KudosPeriodTypeTest.java b/kudos-services/src/test/java/io/meeds/kudos/model/KudosPeriodTypeTest.java similarity index 79% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/KudosPeriodTypeTest.java rename to kudos-services/src/test/java/io/meeds/kudos/model/KudosPeriodTypeTest.java index 8631d277d..d2536666c 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/KudosPeriodTypeTest.java +++ b/kudos-services/src/test/java/io/meeds/kudos/model/KudosPeriodTypeTest.java @@ -1,16 +1,36 @@ -package org.exoplatform.kudos.test; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.LocalDate; import java.time.ZoneId; import org.json.JSONException; import org.json.JSONObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import org.exoplatform.kudos.model.KudosPeriod; -import org.exoplatform.kudos.model.KudosPeriodType; - -public class KudosPeriodTypeTest extends BaseKudosTest { +public class KudosPeriodTypeTest { @Test public void testGetWeekPeriod() { diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/activity/KudosActivityChildPluginTest.java b/kudos-services/src/test/java/io/meeds/kudos/notification/plugin/KudosActivityChildPluginTest.java similarity index 63% rename from kudos-services/src/test/java/org/exoplatform/kudos/activity/KudosActivityChildPluginTest.java rename to kudos-services/src/test/java/io/meeds/kudos/notification/plugin/KudosActivityChildPluginTest.java index 158ec8e3a..714d4f8f0 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/activity/KudosActivityChildPluginTest.java +++ b/kudos-services/src/test/java/io/meeds/kudos/notification/plugin/KudosActivityChildPluginTest.java @@ -1,77 +1,84 @@ /** * This file is part of the Meeds project (https://meeds.io/). - * - * Copyright (C) 2020 - 2023 Meeds Association contact@meeds.io - * + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.activity; +package io.meeds.kudos.notification.plugin; -import static org.exoplatform.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE; +import static io.meeds.kudos.service.utils.Utils.KUDOS_ACTIVITY_COMMENT_TYPE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import org.apache.commons.lang3.StringUtils; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.exoplatform.commons.api.notification.NotificationContext; import org.exoplatform.commons.api.notification.model.NotificationInfo; import org.exoplatform.container.xml.InitParams; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.notification.plugin.KudosActivityChildPlugin; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.kudos.test.BaseKudosTest; import org.exoplatform.social.notification.plugin.SocialNotificationUtils; -@RunWith(MockitoJUnitRunner.class) +import io.meeds.kudos.BaseKudosTest; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.service.KudosService; + +@SpringJUnitConfig(BaseKudosTest.class) public class KudosActivityChildPluginTest extends BaseKudosTest { - private static final long KUDOS_BY_ACTIVITY_ID = 5l; + private static final long KUDOS_BY_ACTIVITY_ID = 5l; - private static final String KUDOS_MESSAGE = "KUDOS_MESSAGE"; + private static final String KUDOS_MESSAGE = "KUDOS_MESSAGE"; @Mock - private KudosService kudosService; + private KudosService kudosService; @Mock - private InitParams initParams; + private NotificationContext ctx; @Mock - private NotificationContext ctx; + private InitParams initParams; @Mock - private NotificationInfo notification; + private NotificationInfo notification; @Mock - private Kudos kudos; + private Kudos kudos; @Test public void testGetId() { - KudosActivityChildPlugin kudosActivityChildPlugin = new KudosActivityChildPlugin(kudosService, initParams); + KudosActivityChildPlugin kudosActivityChildPlugin = new KudosActivityChildPlugin(initParams); + kudosActivityChildPlugin.kudosService = kudosService; assertEquals(KUDOS_ACTIVITY_COMMENT_TYPE, kudosActivityChildPlugin.getId()); } @Test public void testIsValid() { - KudosActivityChildPlugin kudosActivityChildPlugin = new KudosActivityChildPlugin(kudosService, initParams); + KudosActivityChildPlugin kudosActivityChildPlugin = new KudosActivityChildPlugin(initParams); + kudosActivityChildPlugin.kudosService = kudosService; assertFalse(kudosActivityChildPlugin.isValid(null)); } @Test public void testMakeContent() { - KudosActivityChildPlugin kudosActivityChildPlugin = new KudosActivityChildPlugin(kudosService, initParams); + KudosActivityChildPlugin kudosActivityChildPlugin = new KudosActivityChildPlugin(initParams); + kudosActivityChildPlugin.kudosService = kudosService; when(kudosService.getKudosByActivityId(KUDOS_BY_ACTIVITY_ID)).thenReturn(kudos); when(kudos.getMessage()).thenReturn(KUDOS_MESSAGE); when(ctx.getNotificationInfo()).thenReturn(notification); diff --git a/kudos-services/src/test/java/io/meeds/kudos/rest/KudosRestTest.java b/kudos-services/src/test/java/io/meeds/kudos/rest/KudosRestTest.java new file mode 100644 index 000000000..1b8823ec3 --- /dev/null +++ b/kudos-services/src/test/java/io/meeds/kudos/rest/KudosRestTest.java @@ -0,0 +1,344 @@ +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.rest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.fasterxml.jackson.core.json.JsonReadFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +import org.exoplatform.commons.exception.ObjectNotFoundException; +import org.exoplatform.services.security.ConversationState; +import org.exoplatform.services.security.Identity; +import org.exoplatform.social.core.manager.IdentityManager; + +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosPeriodType; +import io.meeds.kudos.model.exception.KudosAlreadyLinkedException; +import io.meeds.kudos.service.KudosService; +import io.meeds.spring.web.security.PortalAuthenticationManager; +import io.meeds.spring.web.security.WebSecurityConfiguration; + +import jakarta.servlet.Filter; +import lombok.SneakyThrows; + +@SpringBootTest(classes = { KudosREST.class, PortalAuthenticationManager.class, }) +@ContextConfiguration(classes = { WebSecurityConfiguration.class }) +@AutoConfigureWebMvc +@AutoConfigureMockMvc(addFilters = false) +@ExtendWith(MockitoExtension.class) +public class KudosRestTest { + + private static final String REST_PATH = "/kudos"; // NOSONAR + + private static final String SIMPLE_USER = "simple"; + + private static final String TEST_PASSWORD = "testPassword"; + + static final ObjectMapper OBJECT_MAPPER; + + static { + // Workaround when Jackson is defined in shared library with different + // version and without artifact jackson-datatype-jsr310 + OBJECT_MAPPER = JsonMapper.builder() + .configure(JsonReadFeature.ALLOW_MISSING_VALUES, true) + .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) + .build(); + OBJECT_MAPPER.registerModule(new JavaTimeModule()); + } + + @Autowired + private SecurityFilterChain filterChain; + + @Autowired + private WebApplicationContext context; + + @MockBean + private KudosService kudosService; + + @MockBean + private IdentityManager identityManager; + + private MockMvc mockMvc; + + @BeforeEach + public void setUp() { + mockMvc = MockMvcBuilders.webAppContextSetup(context) + .addFilters(filterChain.getFilters().toArray(new Filter[0])) + .build(); + } + + @Test + public void testGetAllKudos() throws Exception { + ResultActions response = mockMvc.perform(get(REST_PATH).with(testAdminUser())); + response.andExpect(status().isOk()); + } + + @Test + public void testGetAllKudosByUser() throws Exception { + ResultActions response = mockMvc.perform(get(REST_PATH).with(testSimpleUser())); + response.andExpect(status().isForbidden()); + } + + @Test + public void testGetReceivedKudos() throws Exception { + when(kudosService.getDefaultKudosPeriodType()).thenReturn(KudosPeriodType.DEFAULT); + + ResultActions response = mockMvc.perform(get(REST_PATH + "/1/received?returnSize=true&limit=10").with(testSimpleUser())); + response.andExpect(status().isOk()); + } + + @Test + public void testGetSentKudos() throws Exception { + when(kudosService.getDefaultKudosPeriodType()).thenReturn(KudosPeriodType.DEFAULT); + + ResultActions response = mockMvc.perform(get(REST_PATH + "/1/sent?returnSize=true&limit=10").with(testSimpleUser())); + response.andExpect(status().isOk()); + } + + @Test + public void countKudosNoEntity() throws Exception { + ResultActions response = mockMvc.perform(get(REST_PATH + "/byEntity/sent/count").with(testSimpleUser())); + response.andExpect(status().isBadRequest()); + } + + @Test + public void countKudosNoEntityId() throws Exception { + ResultActions response = mockMvc.perform(get(REST_PATH + "/byEntity/sent/count?entityType=activity").with(testSimpleUser())); + response.andExpect(status().isBadRequest()); + } + + @Test + public void countKudosNoEntityType() throws Exception { + ResultActions response = mockMvc.perform(get(REST_PATH + "/byEntity/sent/count?entityId=1").with(testSimpleUser())); + response.andExpect(status().isBadRequest()); + } + + @Test + public void countKudos() throws Exception { + try (MockedStatic conversationStateMock = mockCurrentIdentityId()) { + ResultActions response = mockMvc.perform(get(REST_PATH + + "/byEntity/sent/count?entityType=activity&entityId=1").with(testSimpleUser())); + response.andExpect(status().isOk()); + } + } + + @Test + public void testGetKudosByActivityIdForbidden() throws Exception { + try (MockedStatic conversationStateMock = mockConversationState()) { + when(kudosService.getKudosByActivityId(anyLong(), any())).thenThrow(IllegalAccessException.class); + + ResultActions response = mockMvc.perform(get(REST_PATH + "/byActivity/1").with(testSimpleUser())); + response.andExpect(status().isForbidden()); + } + } + + @Test + public void testGetKudosByActivityId() throws Exception { + try (MockedStatic conversationStateMock = mockConversationState()) { + ResultActions response = mockMvc.perform(get(REST_PATH + "/byActivity/1").with(testSimpleUser())); + response.andExpect(status().isOk()); + } + } + + @Test + public void testGetKudosListOfActivityForbidden() throws Exception { + try (MockedStatic conversationStateMock = mockConversationState()) { + when(kudosService.getKudosListOfActivity(any(), any())).thenThrow(IllegalAccessException.class); + + ResultActions response = mockMvc.perform(get(REST_PATH + "/byActivity/1/all").with(testSimpleUser())); + response.andExpect(status().isForbidden()); + } + } + + @Test + public void testGetKudosListOfActivity() throws Exception { + try (MockedStatic conversationStateMock = mockConversationState()) { + ResultActions response = mockMvc.perform(get(REST_PATH + "/byActivity/1/all").with(testSimpleUser())); + response.andExpect(status().isOk()); + } + } + + @Test + public void testSendKudosNoEntityId() throws Exception { + Kudos kudos = newKudos(); + kudos.setEntityId(null); + ResultActions response = mockMvc.perform(post(REST_PATH).with(testSimpleUser()) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(kudos))); + response.andExpect(status().isBadRequest()); + } + + @Test + public void testSendKudosNoEntityType() throws Exception { + Kudos kudos = newKudos(); + kudos.setEntityType(null); + ResultActions response = mockMvc.perform(post(REST_PATH).with(testSimpleUser()) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(kudos))); + response.andExpect(status().isBadRequest()); + } + + @Test + public void testSendKudosNoReceiverId() throws Exception { + Kudos kudos = newKudos(); + kudos.setReceiverId(null); + ResultActions response = mockMvc.perform(post(REST_PATH).with(testSimpleUser()) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(kudos))); + response.andExpect(status().isBadRequest()); + } + + @Test + public void testSendKudosNoReceiverType() throws Exception { + Kudos kudos = newKudos(); + kudos.setReceiverType(null); + ResultActions response = mockMvc.perform(post(REST_PATH).with(testSimpleUser()) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(kudos))); + response.andExpect(status().isBadRequest()); + } + + @Test + public void testSendKudos() throws Exception { + try (MockedStatic conversationStateMock = mockCurrentIdentityId()) { + Kudos kudos = newKudos(); + ResultActions response = mockMvc.perform(post(REST_PATH).with(testSimpleUser()) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(kudos))); + response.andExpect(status().isOk()); + } + } + + @Test + public void testDeleteKudosForbidden() throws Exception { + try (MockedStatic conversationStateMock = mockCurrentIdentityId()) { + doThrow(IllegalAccessException.class).when(kudosService).deleteKudosById(1, SIMPLE_USER); + ResultActions response = mockMvc.perform(delete(REST_PATH + "/1").with(testSimpleUser())); + response.andExpect(status().isForbidden()); + } + } + + @Test + public void testDeleteKudosNotFound() throws Exception { + try (MockedStatic conversationStateMock = mockCurrentIdentityId()) { + doThrow(ObjectNotFoundException.class).when(kudosService).deleteKudosById(1, SIMPLE_USER); + ResultActions response = mockMvc.perform(delete(REST_PATH + "/1").with(testSimpleUser())); + response.andExpect(status().isNotFound()); + } + } + + @Test + public void testDeleteKudosAlreadyLinked() throws Exception { + try (MockedStatic conversationStateMock = mockCurrentIdentityId()) { + doThrow(KudosAlreadyLinkedException.class).when(kudosService).deleteKudosById(1, SIMPLE_USER); + ResultActions response = mockMvc.perform(delete(REST_PATH + "/1").with(testSimpleUser())); + response.andExpect(status().isUnauthorized()); + } + } + + @Test + public void testDeleteKudos() throws Exception { + try (MockedStatic conversationStateMock = mockCurrentIdentityId()) { + ResultActions response = mockMvc.perform(delete(REST_PATH + "/1").with(testSimpleUser())); + response.andExpect(status().isOk()); + } + } + + private Kudos newKudos() { + Kudos kudos = new Kudos(); + kudos.setEntityType("activity"); + kudos.setEntityId("1"); + kudos.setReceiverType("user"); + kudos.setReceiverId("1"); + return kudos; + } + + private RequestPostProcessor testSimpleUser() { + return user(SIMPLE_USER).password(TEST_PASSWORD) + .authorities(new SimpleGrantedAuthority("users")); + } + + private RequestPostProcessor testAdminUser() { + return user(SIMPLE_USER).password(TEST_PASSWORD) + .authorities(new SimpleGrantedAuthority("administrators")); + } + + @SneakyThrows + public static String asJsonString(final Object obj) { + return OBJECT_MAPPER.writeValueAsString(obj); + } + + @SneakyThrows + public static MockedStatic mockConversationState() { + Identity identity = mock(Identity.class); + ConversationState conversationState = mock(ConversationState.class); + MockedStatic conversationStateStatic = mockStatic(ConversationState.class); + conversationStateStatic.when(ConversationState::getCurrent).thenReturn(conversationState); + when(conversationState.getIdentity()).thenReturn(identity); + return conversationStateStatic; + } + + @SneakyThrows + public MockedStatic mockCurrentIdentityId() { + MockedStatic conversationStateStatic = mockConversationState(); + when(ConversationState.getCurrent().getIdentity().getUserId()).thenReturn(SIMPLE_USER); + org.exoplatform.social.core.identity.model.Identity identity = + mock(org.exoplatform.social.core.identity.model.Identity.class); + lenient().when(identity.getId()).thenReturn("1"); + when(identityManager.getOrCreateUserIdentity(SIMPLE_USER)).thenReturn(identity); + return conversationStateStatic; + } + +} diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/service/KudosServiceTest.java b/kudos-services/src/test/java/io/meeds/kudos/service/KudosServiceTest.java similarity index 78% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/service/KudosServiceTest.java rename to kudos-services/src/test/java/io/meeds/kudos/service/KudosServiceTest.java index 771fe8ff6..ce83998e2 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/service/KudosServiceTest.java +++ b/kudos-services/src/test/java/io/meeds/kudos/service/KudosServiceTest.java @@ -1,7 +1,31 @@ -package org.exoplatform.kudos.test.service; - -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThrows; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.kudos.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.List; @@ -9,20 +33,11 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.lang3.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.exoplatform.commons.exception.ObjectNotFoundException; -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.model.AccountSettings; -import org.exoplatform.kudos.model.GlobalSettings; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.model.KudosPeriod; -import org.exoplatform.kudos.model.KudosPeriodType; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.kudos.service.utils.Utils; -import org.exoplatform.kudos.storage.KudosStorage; -import org.exoplatform.kudos.test.BaseKudosTest; import org.exoplatform.services.listener.Event; import org.exoplatform.services.listener.Listener; import org.exoplatform.services.listener.ListenerService; @@ -34,10 +49,23 @@ import org.exoplatform.social.core.manager.ActivityManager; import org.exoplatform.social.core.manager.IdentityManager; +import io.meeds.kudos.BaseKudosTest; +import io.meeds.kudos.dao.KudosDAO; +import io.meeds.kudos.entity.KudosEntity; +import io.meeds.kudos.model.AccountSettings; +import io.meeds.kudos.model.GlobalSettings; +import io.meeds.kudos.model.Kudos; +import io.meeds.kudos.model.KudosEntityType; +import io.meeds.kudos.model.KudosPeriod; +import io.meeds.kudos.model.KudosPeriodType; +import io.meeds.kudos.service.utils.Utils; +import io.meeds.kudos.storage.KudosStorage; + +import lombok.SneakyThrows; + +@SpringJUnitConfig(BaseKudosTest.class) public class KudosServiceTest extends BaseKudosTest { - private static final String DEFAULT_PORTAL = "meeds"; - private static final String ENTITY_TYPE = KudosEntityType.USER_TIPTIP.name(); private static final String ENTITY_ID = "1"; @@ -48,18 +76,31 @@ public class KudosServiceTest extends BaseKudosTest { private static final String SENDER_REMOTE_ID = "root4"; - /** - * Check that service is instantiated and functional - */ - @Test - public void testServiceInstantiated() { - KudosService kudosService = getService(KudosService.class); - assertNotNull(kudosService); + @Autowired + IdentityManager identityManager; + + @Autowired + ListenerService listenerService; + + @Autowired + KudosStorage kudosStorage; + + @Autowired + KudosService kudosService; + + @Autowired + ActivityManager activityManager; + + @Autowired + KudosDAO kudosDAO; + + @Override + public KudosDAO getKudosDAO() { + return kudosDAO; } @Test public void testGetKudosByEntity() { - KudosService kudosService = getService(KudosService.class); List list = kudosService.getKudosByEntity(ENTITY_TYPE, ENTITY_ID, 10); assertNotNull(list); assertEquals(0, list.size()); @@ -84,7 +125,6 @@ public void testGetKudosByEntity() { @Test public void testCountKudosByEntity() { - KudosService kudosService = getService(KudosService.class); long count = kudosService.countKudosByEntity(ENTITY_TYPE, ENTITY_ID); assertEquals(0, count); @@ -99,7 +139,6 @@ public void testCountKudosByEntity() { @Test public void testCountKudosByEntityAndSender() { - KudosService kudosService = getService(KudosService.class); long count = kudosService.countKudosByEntityAndSender(ENTITY_TYPE, ENTITY_ID, String.valueOf(senderId)); assertEquals(0, count); @@ -114,7 +153,6 @@ public void testCountKudosByEntityAndSender() { @Test public void testGetKudosByPeriodAndReceiver() { - KudosService kudosService = getService(KudosService.class); long startTime = getTime(2019, 1, 1); long endTime = getCurrentTimeInSeconds(); @@ -142,8 +180,6 @@ public void testGetKudosByPeriodAndReceiver() { @Test public void testCountKudosByPeriodAndReceiver() { - - KudosService kudosService = getService(KudosService.class); long startTime = getTime(2019, 1, 1); long endTime = getCurrentTimeInSeconds(); @@ -164,8 +200,6 @@ public void testCountKudosByPeriodAndReceiver() { @Test public void testCountKudosByPeriodAndReceivers() { - - KudosService kudosService = getService(KudosService.class); long startTime = getTime(2019, 1, 1); long endTime = getCurrentTimeInSeconds(); @@ -188,7 +222,6 @@ public void testCountKudosByPeriodAndReceivers() { @Test public void testGetKudosByPeriodAndSender() { - KudosService kudosService = getService(KudosService.class); long startTime = getTime(2019, 1, 1); long endTime = getCurrentTimeInSeconds(); @@ -216,8 +249,6 @@ public void testGetKudosByPeriodAndSender() { @Test public void testCountKudosByPeriodAndSender() { - - KudosService kudosService = getService(KudosService.class); long startTime = getTime(2019, 1, 1); long endTime = getCurrentTimeInSeconds(); @@ -238,7 +269,6 @@ public void testCountKudosByPeriodAndSender() { @Test public void testGetKudosByPeriod() { - KudosService kudosService = getService(KudosService.class); long startTime = getTime(2019, 1, 1); long endTime = getCurrentTimeInSeconds(); @@ -262,7 +292,6 @@ public void testGetKudosByPeriod() { @Test public void testGetKudosByPeriodOfDate() { - KudosService kudosService = getService(KudosService.class); long startTime = getCurrentTimeInSeconds(); List list = kudosService.getKudosByPeriodOfDate(startTime, 10); @@ -284,11 +313,9 @@ public void testGetKudosByPeriodOfDate() { } @Test - public void testSendKudos() throws Exception { - KudosService kudosService = getService(KudosService.class); - + @SneakyThrows + public void testSendKudos() { Kudos kudos = newKudosDTO(); - try { kudosService.createKudos(kudos, RECEIVER_REMOTE_ID); fail("Sender shouldn't be able to send kudos to himself"); @@ -309,7 +336,6 @@ public void testSendKudos() throws Exception { kudos = kudosService.createKudos(kudos, SENDER_REMOTE_ID); KudosPeriod currentKudosPeriod = kudosService.getCurrentKudosPeriod(); - IdentityManager identityManager = getService(IdentityManager.class); Identity identity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, RECEIVER_REMOTE_ID); List list = kudosService.getKudosByPeriodAndReceiver(Long.parseLong(identity.getId()), currentKudosPeriod.getStartDateInSeconds(), @@ -328,9 +354,8 @@ public void testSendKudos() throws Exception { } @Test - public void testSendKudosToSpace() throws Exception { - KudosService kudosService = getService(KudosService.class); - + @SneakyThrows + public void testSendKudosToSpace() { String spaceRemoteId = "space3"; Kudos kudos = newKudosDTO(); @@ -343,7 +368,6 @@ public void testSendKudosToSpace() throws Exception { kudos = kudosService.createKudos(kudos, SENDER_REMOTE_ID); KudosPeriod currentKudosPeriod = kudosService.getCurrentKudosPeriod(); - IdentityManager identityManager = getService(IdentityManager.class); Identity identity = identityManager.getOrCreateIdentity(SpaceIdentityProvider.NAME, spaceRemoteId); List list = kudosService.getKudosByPeriodAndReceiver(Long.parseLong(identity.getId()), currentKudosPeriod.getStartDateInSeconds(), @@ -360,7 +384,6 @@ public void testSendKudosToSpace() throws Exception { @Test public void testGetKudosByPeriodType() { - KudosService kudosService = getService(KudosService.class); long startTime = getCurrentTimeInSeconds(); try { @@ -390,8 +413,6 @@ public void testGetKudosByPeriodType() { @Test public void testGlobalSettings() { - KudosService kudosService = getService(KudosService.class); - GlobalSettings globalSettings = kudosService.getGlobalSettings(); assertNotNull(globalSettings); assertNotNull(globalSettings.getKudosPeriodType()); @@ -401,12 +422,9 @@ public void testGlobalSettings() { @Test public void testSaveSettings() { - KudosService kudosService = getService(KudosService.class); - GlobalSettings globalSettings = kudosService.getGlobalSettings(); GlobalSettings defaultSettings = globalSettings.clone(); try { - globalSettings.setAccessPermission("/platform"); globalSettings.setKudosPeriodType(KudosPeriodType.WEEK); globalSettings.setKudosPerPeriod(1); kudosService.saveGlobalSettings(globalSettings); @@ -421,9 +439,8 @@ public void testSaveSettings() { } @Test - public void testSendKudosAfterLimitReached() throws Exception { - KudosService kudosService = getService(KudosService.class); - + @SneakyThrows + public void testSendKudosAfterLimitReached() { GlobalSettings globalSettings = kudosService.getGlobalSettings(); GlobalSettings defaultSettings = globalSettings.clone(); try { @@ -448,9 +465,8 @@ public void testSendKudosAfterLimitReached() throws Exception { } @Test - public void testGetAccountSettings() throws Exception { - KudosService kudosService = getService(KudosService.class); - + @SneakyThrows + public void testGetAccountSettings() { GlobalSettings globalSettings = kudosService.getGlobalSettings(); GlobalSettings defaultSettings = globalSettings.clone(); try { @@ -478,34 +494,8 @@ public void testGetAccountSettings() throws Exception { } @Test - public void testGetAccountSettingsDisabled() { - KudosService kudosService = getService(KudosService.class); - - GlobalSettings globalSettings = kudosService.getGlobalSettings(); - GlobalSettings defaultSettings = globalSettings.clone(); - try { - AccountSettings accountSettings = kudosService.getAccountSettings(SENDER_REMOTE_ID); - assertNotNull(accountSettings); - assertFalse(accountSettings.isDisabled()); - - globalSettings.setAccessPermission("/platform"); - kudosService.saveGlobalSettings(globalSettings); - - AccountSettings savedAccountSettings = kudosService.getAccountSettings(SENDER_REMOTE_ID); - assertNotNull(savedAccountSettings); - assertTrue(savedAccountSettings.isDisabled()); - assertNotEquals(accountSettings, savedAccountSettings); - assertNotEquals(accountSettings.hashCode(), savedAccountSettings.hashCode()); - } finally { - kudosService.saveGlobalSettings(defaultSettings); - } - } - - @Test - public void testSaveKudosActivity() throws Exception { - KudosService kudosService = getService(KudosService.class); - ListenerService listenerService = getService(ListenerService.class); - + @SneakyThrows + public void testSaveKudosActivity() { Kudos kudos = newKudosDTO(); kudos = kudosService.createKudos(kudos, SENDER_REMOTE_ID); @@ -522,11 +512,8 @@ public void onEvent(Event event) throws Exception { } @Test - public void testActivityCreation() throws Exception { - KudosService kudosService = getService(KudosService.class); - KudosStorage kudosStorage = getService(KudosStorage.class); - ListenerService listenerService = getService(ListenerService.class); - + @SneakyThrows + public void testActivityCreation() { final AtomicBoolean listenerInvoked = new AtomicBoolean(false); listenerService.addListener(Utils.GAMIFICATION_GENERIC_EVENT, new Listener() { @Override @@ -552,12 +539,11 @@ public void onEvent(Event event) throws Exception { } @Test - public void testGetKudosByActivityId() throws Exception { // NOSONAR - // comparaison is - // made in private - // method - KudosService kudosService = getService(KudosService.class); - KudosStorage kudosStorage = getService(KudosStorage.class); + @SneakyThrows + public void testGetKudosByActivityId() { // NOSONAR + // comparaison is + // made in private + // method KudosEntity kudosEntity = newKudos(); kudosEntity.setEntityType(KudosEntityType.USER_PROFILE.ordinal()); Kudos kudos = kudosService.createKudos(Utils.fromEntity(kudosEntity), SENDER_REMOTE_ID); @@ -567,16 +553,14 @@ public void testGetKudosByActivityId() throws Exception { // NOSONAR } @Test - public void testGetKudosListOfActivity() throws Exception { + @SneakyThrows + public void testGetKudosListOfActivity() { resetGlobalSettings(); - KudosService kudosService = getService(KudosService.class); - KudosEntity kudosEntity = newKudosInstance(); kudosEntity.setEntityType(KudosEntityType.SPACE_PROFILE.ordinal()); Kudos parentKudos = kudosService.createKudos(Utils.fromEntity(kudosEntity), SENDER_REMOTE_ID); - ActivityManager activityManager = getService(ActivityManager.class); ExoSocialActivity activity = new ExoSocialActivityImpl(); activity.setUserId("root"); activityManager.saveActivityNoReturn(activity); @@ -640,9 +624,8 @@ public void testGetKudosListOfActivity() throws Exception { } @Test - public void testUpdateKudos() throws Exception { - KudosService kudosService = getService(KudosService.class); - KudosStorage kudosStorage = getService(KudosStorage.class); + @SneakyThrows + public void testUpdateKudos() { Kudos kudos = newKudosDTO(); kudos.setEntityType(KudosEntityType.USER_PROFILE.name()); kudos = kudosService.createKudos(kudos, SENDER_REMOTE_ID); @@ -654,9 +637,8 @@ public void testUpdateKudos() throws Exception { } @Test - public void testDeleteKudosById() throws Exception { - KudosService kudosService = getService(KudosService.class); - KudosStorage kudosStorage = getService(KudosStorage.class); + @SneakyThrows + public void testDeleteKudosById() { Kudos kudos = newKudosDTO(); kudos.setEntityType(KudosEntityType.USER_PROFILE.name()); kudos = kudosService.createKudos(kudos, SENDER_REMOTE_ID); @@ -670,27 +652,8 @@ public void testDeleteKudosById() throws Exception { assertNull(kudos1); } - @Test - public void testCancelKudosById() throws Exception { - KudosService kudosService = getService(KudosService.class); - KudosStorage kudosStorage = getService(KudosStorage.class); - Kudos kudos = newKudosDTO(); - kudos.setEntityType(KudosEntityType.USER_PROFILE.name()); - kudos = kudosService.createKudos(kudos, SENDER_REMOTE_ID); - long kudosId = kudos.getTechnicalId(); - - assertThrows(IllegalArgumentException.class, () -> kudosService.deleteKudosById(0, "root4")); - assertThrows(ObjectNotFoundException.class, () -> kudosService.deleteKudosById(100, "root4")); - assertThrows(IllegalAccessException.class, () -> kudosService.deleteKudosById(kudosId, "root3")); - kudosService.deleteKudosById(kudosId, "root4"); - Kudos kudos1 = kudosStorage.getKudoById(kudos.getTechnicalId()); - assertNull(kudos1); - } - private void resetGlobalSettings() { - KudosService kudosService = getService(KudosService.class); GlobalSettings globalSettings = kudosService.getGlobalSettings(); - globalSettings.setAccessPermission(null); globalSettings.setKudosPeriodType(KudosPeriodType.WEEK); globalSettings.setKudosPerPeriod(100); kudosService.saveGlobalSettings(globalSettings); diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/ActivityManagerMock.java b/kudos-services/src/test/java/io/meeds/test/kudos/mock/ActivityManagerMock.java similarity index 84% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/mock/ActivityManagerMock.java rename to kudos-services/src/test/java/io/meeds/test/kudos/mock/ActivityManagerMock.java index 1b49b7bfc..b853ae958 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/ActivityManagerMock.java +++ b/kudos-services/src/test/java/io/meeds/test/kudos/mock/ActivityManagerMock.java @@ -1,4 +1,23 @@ -package org.exoplatform.kudos.test.mock; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.test.kudos.mock; import java.util.HashMap; import java.util.List; @@ -20,6 +39,10 @@ public class ActivityManagerMock implements ActivityManager { private Map activities = new HashMap<>(); + public ActivityManagerMock() { + System.out.println("ActivityManagerMock instanciated"); + } + public void saveActivityNoReturn(Identity streamOwner, ExoSocialActivity activity) { saveActivityNoReturn(activity); } diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/ActivityStorageMock.java b/kudos-services/src/test/java/io/meeds/test/kudos/mock/ActivityStorageMock.java similarity index 94% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/mock/ActivityStorageMock.java rename to kudos-services/src/test/java/io/meeds/test/kudos/mock/ActivityStorageMock.java index 09e124996..95bf062a7 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/ActivityStorageMock.java +++ b/kudos-services/src/test/java/io/meeds/test/kudos/mock/ActivityStorageMock.java @@ -1,4 +1,23 @@ -package org.exoplatform.kudos.test.mock; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.test.kudos.mock; import java.util.HashMap; import java.util.List; diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/IdentityManagerMock.java b/kudos-services/src/test/java/io/meeds/test/kudos/mock/IdentityManagerMock.java similarity index 90% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/mock/IdentityManagerMock.java rename to kudos-services/src/test/java/io/meeds/test/kudos/mock/IdentityManagerMock.java index 1538307c2..adc9d5e60 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/IdentityManagerMock.java +++ b/kudos-services/src/test/java/io/meeds/test/kudos/mock/IdentityManagerMock.java @@ -1,4 +1,23 @@ -package org.exoplatform.kudos.test.mock; +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package io.meeds.test.kudos.mock; import java.io.IOException; import java.io.InputStream; diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/SpaceServiceMock.java b/kudos-services/src/test/java/io/meeds/test/kudos/mock/SpaceServiceMock.java similarity index 95% rename from kudos-services/src/test/java/org/exoplatform/kudos/test/mock/SpaceServiceMock.java rename to kudos-services/src/test/java/io/meeds/test/kudos/mock/SpaceServiceMock.java index 9f80833bf..450d08487 100644 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/mock/SpaceServiceMock.java +++ b/kudos-services/src/test/java/io/meeds/test/kudos/mock/SpaceServiceMock.java @@ -1,25 +1,27 @@ -/* - * Copyright (C) 2003-2019 eXo Platform SAS. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * +/** + * This file is part of the Meeds project (https://meeds.io/). + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.exoplatform.kudos.test.mock; +package io.meeds.test.kudos.mock; import java.util.List; import org.exoplatform.commons.utils.ListAccess; -import org.exoplatform.services.security.MembershipEntry; import org.exoplatform.social.core.application.PortletPreferenceRequiredPlugin; import org.exoplatform.social.core.identity.model.Identity; import org.exoplatform.social.core.space.SpaceApplicationConfigPlugin; diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/BaseKudosRestTest.java b/kudos-services/src/test/java/org/exoplatform/kudos/test/BaseKudosRestTest.java deleted file mode 100644 index 88ab1701f..000000000 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/BaseKudosRestTest.java +++ /dev/null @@ -1,179 +0,0 @@ -package org.exoplatform.kudos.test; - -import java.time.LocalDate; -import java.time.ZoneId; - -import org.junit.After; -import org.junit.Before; - -import org.exoplatform.component.test.ConfigurationUnit; -import org.exoplatform.component.test.ConfiguredBy; -import org.exoplatform.component.test.ContainerScope; -import org.exoplatform.container.PortalContainer; -import org.exoplatform.kudos.dao.KudosDAO; -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.service.utils.Utils; -import org.exoplatform.social.service.test.AbstractResourceTest; - -@ConfiguredBy({ - @ConfigurationUnit(scope = ContainerScope.ROOT, path = "conf/configuration.xml"), - @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/portal/configuration.xml"), - @ConfigurationUnit(scope = ContainerScope.PORTAL, path = "conf/kudos-test-configuration.xml"), -}) -public abstract class BaseKudosRestTest extends AbstractResourceTest { - - protected static final String DEFAULT_PORTAL = "meeds"; - - protected KudosEntityType kudosEntityType = KudosEntityType.USER_TIPTIP; - - protected int entityType = kudosEntityType.ordinal(); - - protected long entityId = 1; - - protected long parentEntityId = 2; - - protected long receiverId = 3; - - protected long senderId = 4; - - protected long createdTimestamp = System.currentTimeMillis() / 1000; - - protected String message = "message"; - - protected PortalContainer container; - - public BaseKudosRestTest() { - setForceContainerReload(true); - } - - @Before - @Override - public void setUp() throws Exception { - container = getContainer(); - assertNotNull("Container shouldn't be null", container); - assertTrue("Container should have been started", container.isStarted()); - begin(); - super.setUp(); - } - - @After - @Override - public void tearDown() throws Exception { - KudosDAO kudosDAO = getService(KudosDAO.class); - - restartTransaction(); - - kudosDAO.deleteAll(); - - int kudosCount = kudosDAO.findAll().size(); - assertEquals("The previous test didn't cleaned kudos entities correctly, should add entities to clean into 'entitiesToClean' list.", - 0, - kudosCount); - - end(); - super.tearDown(); - } - - @Override - public void begin() { // NOSONAR - super.begin(); - } - - @Override - public void startSessionAs(String user) { // NOSONAR - super.startSessionAs(user); - } - - @Override - protected void deleteAllRelationships() throws Exception { - // Nop - } - - @Override - protected void deleteAllIdentitiesWithActivities() throws Exception { - // Nop - } - - @Override - protected void deleteAllSpaces() throws Exception { - // Nop - } - - protected T getService(Class componentType) { - return container.getComponentInstanceOfType(componentType); - } - - protected Kudos newKudosDTO() { - KudosEntity entity = newKudosInstance(parentEntityId, entityId, entityType, receiverId, senderId, createdTimestamp, message); - return Utils.fromEntity(entity); - } - - protected KudosEntity newKudos() { - return newKudos(parentEntityId, entityId, entityType, receiverId, senderId, createdTimestamp, message); - } - - protected KudosEntity newKudosInstance() { - return newKudosInstance(parentEntityId, entityId, entityType, receiverId, senderId, createdTimestamp, message); - } - - protected KudosEntity newKudos(long parentEntityId, - long entityId, - int entityType, - long receiverId, - long senderId, - long createdTimestamp, - String message) { - KudosDAO kudosDAO = getService(KudosDAO.class); - - KudosEntity kudosEntity = newKudosInstance(parentEntityId, - entityId, - entityType, - receiverId, - senderId, - createdTimestamp, - message); - return kudosDAO.create(kudosEntity); - } - - private KudosEntity newKudosInstance(long parentEntityId, - long entityId, - int entityType, - long receiverId, - long senderId, - long createdTimestamp, - String message) { - KudosEntity kudosEntity = new KudosEntity(); - kudosEntity.setEntityId(entityId); - kudosEntity.setEntityType(entityType); - kudosEntity.setMessage(message); - kudosEntity.setParentEntityId(parentEntityId); - kudosEntity.setReceiverId(receiverId); - kudosEntity.setReceiverUser(true); - kudosEntity.setSenderId(senderId); - kudosEntity.setCreatedDate(createdTimestamp); - return kudosEntity; - } - - protected void compareResults(KudosEntity kudosEntity, Kudos kudos) { - assertEquals(kudosEntity.getActivityId(), kudos.getActivityId()); - assertEquals(kudosEntity.getCreatedDate(), kudos.getTimeInSeconds()); - assertEquals(String.valueOf(kudosEntity.getEntityId()), kudos.getEntityId()); - assertEquals(kudosEntity.getEntityType(), KudosEntityType.valueOf(kudos.getEntityType()).ordinal()); - assertEquals(kudosEntity.getId(), kudos.getTechnicalId()); - assertEquals(kudosEntity.getMessage(), kudos.getMessage()); - assertEquals(String.valueOf(kudosEntity.getParentEntityId()), kudos.getParentEntityId()); - assertEquals(String.valueOf(kudosEntity.getReceiverId()), kudos.getReceiverIdentityId()); - assertEquals(String.valueOf(kudosEntity.getSenderId()), kudos.getSenderIdentityId()); - } - - protected long getTime(int year, int month, int day) { - return LocalDate.of(year, month, day).atStartOfDay(ZoneId.systemDefault()).toEpochSecond(); - } - - protected long getCurrentTimeInSeconds() { - return System.currentTimeMillis() / 1000 + 10; - } - -} diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/dao/KudosDAOTest.java b/kudos-services/src/test/java/org/exoplatform/kudos/test/dao/KudosDAOTest.java deleted file mode 100644 index ac663db37..000000000 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/dao/KudosDAOTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package org.exoplatform.kudos.test.dao; - -import static org.exoplatform.kudos.service.utils.Utils.fromEntity; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.junit.Test; - -import org.exoplatform.kudos.dao.KudosDAO; -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.model.KudosPeriod; -import org.exoplatform.kudos.test.BaseKudosTest; - -public class KudosDAOTest extends BaseKudosTest { - - /** - * Check that service is instantiated and functional - */ - @Test - public void testServiceInstantiated() { - KudosDAO kudosDAO = getService(KudosDAO.class); - assertNotNull(kudosDAO); - } - - @Test - public void testGetKudosByEntity() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - List list = kudosDAO.getKudosByEntity(entityType, entityId, 10); - assertNotNull(list); - assertEquals(0, list.size()); - - newKudos(); - - list = kudosDAO.getKudosByEntity(entityType, entityId, 10); - assertNotNull(list); - assertEquals(1, list.size()); - - list = kudosDAO.getKudosByEntity(KudosEntityType.COMMENT.ordinal(), entityId, 10); - assertNotNull(list); - assertEquals(0, list.size()); - - list = kudosDAO.getKudosByEntity(entityType, 20, 10); - assertNotNull(list); - assertEquals(0, list.size()); - } - - @Test - public void testGetKudosByPeriodAndReceiver() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosPeriod kudosPeriod = new KudosPeriod(getTime(2019, 1, 1), getCurrentTimeInSeconds()); - - List list = kudosDAO.getKudosByPeriodAndReceiver(kudosPeriod, receiverId, true, 10); - assertNotNull(list); - assertEquals(0, list.size()); - - newKudos(); - - list = kudosDAO.getKudosByPeriodAndReceiver(kudosPeriod, receiverId, true, 10); - assertNotNull(list); - assertEquals(1, list.size()); - - list = kudosDAO.getKudosByPeriodAndReceiver(kudosPeriod, receiverId, false, 10); - assertNotNull(list); - assertEquals(0, list.size()); - - list = kudosDAO.getKudosByPeriodAndReceiver(kudosPeriod, 30, true, 10); - assertNotNull(list); - assertEquals(0, list.size()); - } - - @Test - public void testcountKudosByEntity() { - KudosDAO kudosDAO = getService(KudosDAO.class); - long count = kudosDAO.countKudosByEntity(entityType, entityId); - assertEquals(0, count); - - newKudos(); - - count = kudosDAO.countKudosByEntity(entityType, entityId); - assertEquals(1, count); - - count = kudosDAO.countKudosByEntity(entityType, 25); - assertEquals(0, count); - } - - @Test - public void testCountKudosByEntityAndSender() { - KudosDAO kudosDAO = getService(KudosDAO.class); - long count = kudosDAO.countKudosByEntityAndSender(entityType, entityId, senderId); - assertEquals(0, count); - - newKudos(); - - count = kudosDAO.countKudosByEntityAndSender(entityType, entityId, senderId); - assertEquals(1, count); - - count = kudosDAO.countKudosByEntityAndSender(entityType, 25, senderId); - assertEquals(0, count); - } - - @Test - public void testCountKudosByPeriodAndReceiver() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosPeriod kudosPeriod = new KudosPeriod(getTime(2019, 1, 1), getCurrentTimeInSeconds()); - - long count = kudosDAO.countKudosByPeriodAndReceiver(kudosPeriod, receiverId, true); - assertEquals(0, count); - - newKudos(); - - count = kudosDAO.countKudosByPeriodAndReceiver(kudosPeriod, receiverId, true); - assertEquals(1, count); - - count = kudosDAO.countKudosByPeriodAndReceiver(kudosPeriod, receiverId, false); - assertEquals(0, count); - - count = kudosDAO.countKudosByPeriodAndReceiver(kudosPeriod, 30, true); - assertEquals(0, count); - } - - @Test - public void testCountKudosByPeriodAndReceivers() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosPeriod kudosPeriod = new KudosPeriod(getTime(2019, 1, 1), getCurrentTimeInSeconds()); - - List receiversId = new ArrayList<>(); - receiversId.add(receiverId); - - Map counts = kudosDAO.countKudosByPeriodAndReceivers(kudosPeriod, receiversId); - assertEquals(Long.valueOf(0), java.util.Optional.ofNullable(counts.get(receiverId)).orElse(0L)); - - newKudos(); - - receiversId.add(30L); - - counts = kudosDAO.countKudosByPeriodAndReceivers(kudosPeriod, receiversId); - assertEquals(Long.valueOf(1), java.util.Optional.ofNullable(counts.get(receiverId)).orElse(0L)); - assertEquals(Long.valueOf(0), java.util.Optional.ofNullable(counts.get(30L)).orElse(0L)); - } - - @Test - public void testGetKudosByPeriod() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosPeriod kudosPeriod = new KudosPeriod(getTime(2019, 1, 1), getCurrentTimeInSeconds()); - - List list = kudosDAO.getKudosByPeriod(kudosPeriod, 10); - assertNotNull(list); - assertEquals(0, list.size()); - - newKudos(); - - list = kudosDAO.getKudosByPeriod(kudosPeriod, 10); - assertNotNull(list); - assertEquals(1, list.size()); - - list = kudosDAO.getKudosByPeriod(new KudosPeriod(getTime(2019, 1, 1), getTime(2019, 7, 1)), 10); - assertNotNull(list); - assertEquals(0, list.size()); - } - - @Test - public void testGetKudosByPeriodAndEntityType() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosPeriod kudosPeriod = new KudosPeriod(getTime(2019, 1, 1), getCurrentTimeInSeconds()); - - List list = kudosDAO.getKudosByPeriodAndEntityType(kudosPeriod, entityType, 10); - assertNotNull(list); - assertEquals(0, list.size()); - - newKudos(); - - list = kudosDAO.getKudosByPeriodAndEntityType(kudosPeriod, entityType, 10); - assertNotNull(list); - assertEquals(1, list.size()); - - list = kudosDAO.getKudosByPeriodAndEntityType(kudosPeriod, KudosEntityType.COMMENT.ordinal(), 10); - assertNotNull(list); - assertEquals(0, list.size()); - } - - @Test - public void testGetKudosByPeriodAndSender() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosPeriod kudosPeriod = new KudosPeriod(getTime(2019, 1, 1), getCurrentTimeInSeconds()); - - List list = kudosDAO.getKudosByPeriodAndSender(kudosPeriod, senderId, 10); - assertNotNull(list); - assertEquals(0, list.size()); - - newKudos(); - - list = kudosDAO.getKudosByPeriodAndSender(kudosPeriod, senderId, 10); - assertNotNull(list); - assertEquals(1, list.size()); - - list = kudosDAO.getKudosByPeriodAndSender(kudosPeriod, 30, 10); - assertNotNull(list); - assertEquals(0, list.size()); - } - - @Test - public void testCountKudosByPeriodAndSender() { - - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosPeriod kudosPeriod = new KudosPeriod(getTime(2019, 1, 1), getCurrentTimeInSeconds()); - - long count = kudosDAO.countKudosByPeriodAndSender(kudosPeriod, senderId); - assertEquals(0, count); - - newKudos(); - - count = kudosDAO.countKudosByPeriodAndSender(kudosPeriod, senderId); - assertEquals(1, count); - - count = kudosDAO.countKudosByPeriodAndSender(kudosPeriod, 30); - assertEquals(0, count); - } - @Test - public void testGetKudosByActivityId() { - KudosDAO kudosDAO = getService(KudosDAO.class); - KudosEntity kudos = newKudos(); - Long activityId = 1L ; - kudos.setActivityId(activityId); - kudosDAO.create(kudos); - KudosEntity newKudos = kudosDAO.getKudosByActivityId(activityId); - compareResults(newKudos, fromEntity(kudos)); - - } -} diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/listener/ProfileUpdateListenerTest.java b/kudos-services/src/test/java/org/exoplatform/kudos/test/listener/ProfileUpdateListenerTest.java deleted file mode 100644 index bb181f77d..000000000 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/listener/ProfileUpdateListenerTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.exoplatform.kudos.test.listener; - -import org.exoplatform.kudos.listener.ProfileUpdateListener; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.kudos.test.BaseKudosTest; -import org.exoplatform.social.core.identity.model.Identity; -import org.exoplatform.social.core.identity.model.Profile; -import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; -import org.exoplatform.social.core.manager.IdentityManager; -import org.exoplatform.social.core.storage.api.ActivityStorage; -import org.exoplatform.social.core.storage.cache.CachedActivityStorage; -import org.junit.Test; - -import java.util.Collections; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; - -public class ProfileUpdateListenerTest extends BaseKudosTest { - - private IdentityManager identityManager; - - private KudosService kudosService; - - private ActivityStorage activityStorage; - - @Test - public void testUpdateProfileAndDetectChanges() { - identityManager = getService(IdentityManager.class); - kudosService = mock(KudosService.class); - activityStorage = mock(CachedActivityStorage.class); - Identity rootIdentity = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, "root1"); - Profile profile = rootIdentity.getProfile(); - ProfileUpdateListener profileUpdateListener =new ProfileUpdateListener(kudosService, activityStorage); - identityManager.registerProfileListener(profileUpdateListener); - Kudos kudos = new Kudos() ; - kudos.setActivityId(1); - when(kudosService.countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong())).thenReturn(1L); - when(kudosService.getKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong(), anyInt())).thenReturn(Collections.singletonList(kudos)); - doNothing().when(((CachedActivityStorage) activityStorage)).clearActivityCached(anyString()); - profile.setProperty(Profile.FIRST_NAME, "Changed Firstname"); - identityManager.updateProfile(profile); - verify((CachedActivityStorage) activityStorage, times(1)).clearActivityCached(anyString()); - verify(kudosService, times(1)).countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong()); - verify(kudosService, times(1)).getKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong(), anyInt()); - - profile.setProperty(Profile.ABOUT_ME, "Changed ABOUT_ME"); - profile.removeProperty(Profile.FIRST_NAME); - identityManager.updateProfile(profile); - verify((CachedActivityStorage) activityStorage, times(1)).clearActivityCached(anyString()); - verify(kudosService, times(1)).countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong()); - verify(kudosService, times(1)).getKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong(), anyInt()); - - profile.setProperty(Profile.AVATAR, "new/avatar"); - identityManager.updateProfile(profile); - verify((CachedActivityStorage) activityStorage, times(2)).clearActivityCached(anyString()); - verify(kudosService, times(2)).countKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong()); - verify(kudosService, times(2)).getKudosByPeriodAndReceiver(anyLong(), anyLong(), anyLong(), anyInt()); - } -} diff --git a/kudos-services/src/test/java/org/exoplatform/kudos/test/rest/KudosRestTest.java b/kudos-services/src/test/java/org/exoplatform/kudos/test/rest/KudosRestTest.java deleted file mode 100644 index 447440367..000000000 --- a/kudos-services/src/test/java/org/exoplatform/kudos/test/rest/KudosRestTest.java +++ /dev/null @@ -1,423 +0,0 @@ -package org.exoplatform.kudos.test.rest; - -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.exoplatform.kudos.entity.KudosEntity; -import org.exoplatform.kudos.listener.KudosSentActivityGeneratorListener; -import org.exoplatform.kudos.model.Kudos; -import org.exoplatform.kudos.model.KudosEntityType; -import org.exoplatform.kudos.model.KudosList; -import org.exoplatform.kudos.rest.KudosREST; -import org.exoplatform.kudos.service.KudosService; -import org.exoplatform.kudos.service.utils.Utils; -import org.exoplatform.kudos.test.BaseKudosRestTest; -import org.exoplatform.services.listener.Event; -import org.exoplatform.services.rest.impl.ContainerResponse; -import org.exoplatform.social.core.activity.model.ExoSocialActivity; -import org.exoplatform.social.core.activity.model.ExoSocialActivityImpl; -import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider; -import org.exoplatform.social.core.manager.ActivityManager; - -@SuppressWarnings("unchecked") -public class KudosRestTest extends BaseKudosRestTest { - - @Before - public void setUp() throws Exception { - super.setUp(); - addResource(KudosREST.class, null); - } - - @After - public void tearDown() throws Exception { - super.tearDown(); - removeResource(KudosREST.class); - } - - @Override - public String getURLResource(String resourceURL) { - return "/kudos/api/kudos/" + resourceURL; - } - - @Test - public void testGetAllKudos() throws Exception { - startSessionAs("root4"); - begin(); - try { - ContainerResponse response = service("GET", getURLResource(""), "", null, null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - List kudosList = (List) response.getEntity(); - assertEquals(0, kudosList.size()); - - newKudos(); - - response = service("GET", getURLResource(""), "", null, null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - kudosList = (List) response.getEntity(); - assertEquals(1, kudosList.size()); - Kudos retrievedKudos = kudosList.get(0); - assertNotNull(retrievedKudos); - } finally { - end(); - } - } - - @Test - public void testGetReceivedKudos() throws Exception { - String url = getURLResource(receiverId + "/received?returnSize=true&limit=10"); - - startSessionAs("root4"); - ContainerResponse response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - KudosList kudosList = (KudosList) response.getEntity(); - assertEquals(0, kudosList.getSize()); - - newKudos(); - - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - kudosList = (KudosList) response.getEntity(); - assertEquals(1, kudosList.getSize()); - Kudos retrievedKudos = kudosList.getKudos().get(0); - assertNotNull(retrievedKudos); - } - - @Test - public void testGetSentKudos() throws Exception { - String url = getURLResource(senderId + "/sent?returnSize=true&limit=10"); - - startSessionAs("root4"); - ContainerResponse response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - KudosList kudosList = (KudosList) response.getEntity(); - assertEquals(0, kudosList.getSize()); - - newKudos(); - - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - kudosList = (KudosList) response.getEntity(); - assertEquals(1, kudosList.getSize()); - Kudos retrievedKudos = kudosList.getKudos().get(0); - assertNotNull(retrievedKudos); - } - - @Test - public void testGetKudosByActivityId() throws Exception { - startSessionAs("root4"); - KudosService kudosService = getService(KudosService.class); - - KudosEntity kudosEntity = newKudosInstance(); - Kudos kudos = kudosService.createKudos(Utils.fromEntity(kudosEntity), "root4"); - long activityId = 5; - - kudosService.updateKudosGeneratedActivityId(kudos.getTechnicalId(), activityId); - kudos = kudosService.getKudosByActivityId(activityId); - - assertEquals(activityId, kudos.getActivityId()); - - String url = getURLResource("byActivity/" + activityId); - ContainerResponse response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - - Kudos kudosByActivity = (Kudos) response.getEntity(); - assertNotNull(kudosByActivity); - assertTrue(kudosByActivity.getActivityId() > 0); - assertEquals(kudos.getTechnicalId(), kudosByActivity.getTechnicalId()); - - url = getURLResource("byActivity/200"); - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - kudosByActivity = (Kudos) response.getEntity(); - assertNull(kudosByActivity); - - startSessionAs("root3"); - url = getURLResource("byActivity/" + activityId); - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - - kudosByActivity = (Kudos) response.getEntity(); - assertNotNull(kudosByActivity); - assertTrue(kudosByActivity.getActivityId() > 0); - assertEquals(kudos.getTechnicalId(), kudosByActivity.getTechnicalId()); - - startSessionAs("root2"); - url = getURLResource("byActivity/" + activityId); - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - - kudosByActivity = (Kudos) response.getEntity(); - assertNull(kudosByActivity); - - ActivityManager activityManager = getService(ActivityManager.class); - new KudosSentActivityGeneratorListener(activityManager, null).onEvent(new Event(null, - kudosService, - kudos)); - List kudosList = kudosService.getKudosByEntity(kudos.getEntityType(), kudos.getEntityId(), 1); - assertEquals(1, kudosList.size()); - kudos = kudosList.get(0); - - activityId = kudos.getActivityId(); - - url = getURLResource("byActivity/" + activityId); - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(404, response.getStatus()); - - startSessionAs("root4"); - url = getURLResource("byActivity/" + activityId); - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - - startSessionAs("root3"); - url = getURLResource("byActivity/" + activityId); - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - } - - @Test - public void testGetKudosListOfActivity() throws Exception { - String senderUsername = "root4"; - - startSessionAs(senderUsername); - KudosService kudosService = getService(KudosService.class); - - KudosEntity kudosEntity = newKudosInstance(); - kudosEntity.setEntityType(KudosEntityType.SPACE_PROFILE.ordinal()); - Kudos parentKudos = kudosService.createKudos(Utils.fromEntity(kudosEntity), senderUsername); - - ActivityManager activityManager = getService(ActivityManager.class); - ExoSocialActivity activity = new ExoSocialActivityImpl(); - activity.setUserId(senderUsername); - activityManager.saveActivityNoReturn(activity); - String activityId = activity.getId(); - parentKudos.setActivityId(Long.parseLong(activityId)); - kudosService.updateKudosGeneratedActivityId(parentKudos.getTechnicalId(), Long.parseLong(activityId)); - - KudosEntity childKudosEntity = newKudosInstance(); - childKudosEntity.setEntityType(KudosEntityType.ACTIVITY.ordinal()); - childKudosEntity.setEntityId(250l); - childKudosEntity.setParentEntityId(parentKudos.getActivityId()); - Kudos childKudos = kudosService.createKudos(Utils.fromEntity(childKudosEntity), senderUsername); - - getKudosListOfActivity("%20", senderUsername, 400); - getKudosListOfActivity(activityId, "root3", 404); - - List kudosList = getKudosListOfActivity("66699963", senderUsername, 200); - assertNotNull(kudosList); - assertTrue(kudosList.isEmpty()); - - kudosList = getKudosListOfActivity(activityId, senderUsername, 200); - assertNotNull(kudosList); - assertEquals(2, kudosList.size()); - assertTrue(kudosList.stream().anyMatch(kudos -> kudos.getTechnicalId() == parentKudos.getTechnicalId())); - assertTrue(kudosList.stream().anyMatch(kudos -> kudos.getTechnicalId() == childKudos.getTechnicalId())); - - ExoSocialActivity comment = new ExoSocialActivityImpl(); - comment.setUserId("root,root4"); - activityManager.saveActivityNoReturn(comment); - childKudos.setActivityId(Long.parseLong(comment.getId())); - kudosService.updateKudosGeneratedActivityId(childKudos.getTechnicalId(), Long.parseLong(comment.getId())); - - KudosEntity subCommentKudosEntity = newKudosInstance(); - subCommentKudosEntity.setEntityType(KudosEntityType.COMMENT.ordinal()); - subCommentKudosEntity.setEntityId(255l); - subCommentKudosEntity.setParentEntityId(parentKudos.getActivityId()); - Kudos subCommentKudos = kudosService.createKudos(Utils.fromEntity(subCommentKudosEntity), senderUsername); - - kudosList = getKudosListOfActivity(activityId, senderUsername, 200); - - assertNotNull(kudosList); - assertEquals(3, kudosList.size()); - assertTrue(kudosList.stream().anyMatch(kudos -> kudos.getTechnicalId() == parentKudos.getTechnicalId())); - assertTrue(kudosList.stream().anyMatch(kudos -> kudos.getTechnicalId() == childKudos.getTechnicalId())); - assertTrue(kudosList.stream().anyMatch(kudos -> kudos.getTechnicalId() == subCommentKudos.getTechnicalId())); - } - - @Test - public void testCountSentKudosByEntityAndUser() throws Exception { - startSessionAs("root4"); - - String url = getURLResource("byEntity/sent/count?entityType=" + kudosEntityType + "&entityId=" + entityId); - ContainerResponse response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - String count = (String) response.getEntity(); - assertNotNull(count); - assertEquals("0", count); - - newKudos(); - - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - count = (String) response.getEntity(); - assertNotNull(count); - assertEquals("1", count); - - startSessionAs("root3"); - - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - count = (String) response.getEntity(); - assertNotNull(count); - assertEquals("0", count); - } - - @Test - public void testSendKudos() throws Exception { - startSessionAs("root4"); - - String url = getURLResource(""); - String input = "{\"entityId\":\"" + entityId + "\", \"entityType\":\"" + kudosEntityType.name() + "\", \"receiverId\":\"root" - + receiverId - + "\", \"receiverType\":\"" + OrganizationIdentityProvider.NAME + "\", \"parentEntityId\":\"" + parentEntityId - + "\", \"message\":\"" + message + "\"}"; - ContainerResponse response = getResponse("POST", - url, - input); - - assertNotNull(response); - assertEquals(String.valueOf(response.getEntity()), 200, response.getStatus()); - - Kudos kudos = (Kudos) response.getEntity(); - assertEquals(String.valueOf(entityId), kudos.getEntityId()); - assertEquals(String.valueOf(receiverId), kudos.getReceiverIdentityId()); - assertEquals(String.valueOf(parentEntityId), kudos.getParentEntityId()); - assertEquals(kudosEntityType.name(), kudos.getEntityType()); - assertEquals(message, kudos.getMessage()); - - url = getURLResource("byEntity/sent/count?entityType=" + kudosEntityType + "&entityId=" + entityId); - response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(200, response.getStatus()); - String count = (String) response.getEntity(); - assertNotNull(count); - assertEquals("1", count); - } - - - @Test - public void testDeleteKudos() throws Exception { - startSessionAs("root4"); - - String url = getURLResource("" + entityId); - ContainerResponse response = service("DELETE", url, "", null, null); - assertNotNull(response); - assertEquals(404, response.getStatus()); - - KudosEntity kudos = newKudos(); - - startSessionAs("root3"); - url = getURLResource("" + kudos.getId()); - response = service("DELETE", url, "", null, null); - assertNotNull(response); - assertEquals(401, response.getStatus()); - - startSessionAs("root4"); - - response = service("DELETE", url, "", null, null); - assertNotNull(response); - assertEquals(204, response.getStatus()); - - response = service("DELETE", url, "", null, null); - assertNotNull(response); - assertEquals(404, response.getStatus()); - } - - private List getKudosListOfActivity(String activityId, String username, int expectedStatus) throws Exception { - startSessionAs(username); - String url = getURLResource("byActivity/" + activityId + "/all"); - ContainerResponse response = service("GET", - url, - "", - null, - null); - assertNotNull(response); - assertEquals(response.getEntity() == null ? "Unexpected status: " + response.getStatus() : response.getEntity().toString(), - expectedStatus, - response.getStatus()); - List kudosList = null; - if (expectedStatus == 200) { - kudosList = (List) response.getEntity(); - } - return kudosList; - } - -} diff --git a/kudos-services/src/test/resources/conf/kudos-test-configuration.xml b/kudos-services/src/test/resources/conf/portal/kudos-test-configuration.xml similarity index 52% rename from kudos-services/src/test/resources/conf/kudos-test-configuration.xml rename to kudos-services/src/test/resources/conf/portal/kudos-test-configuration.xml index 59dc7c527..4824cbfcd 100644 --- a/kudos-services/src/test/resources/conf/kudos-test-configuration.xml +++ b/kudos-services/src/test/resources/conf/portal/kudos-test-configuration.xml @@ -3,66 +3,33 @@ for more details. You should have received a copy of the GNU Lesser General Public License along with this software; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF site: http://www.fsf.org. --> - - org.exoplatform.kudos.storage.KudosStorage - - org.exoplatform.social.core.space.spi.SpaceService - org.exoplatform.kudos.test.mock.SpaceServiceMock + io.meeds.test.kudos.mock.SpaceServiceMock org.exoplatform.social.core.manager.IdentityManager - org.exoplatform.kudos.test.mock.IdentityManagerMock + io.meeds.test.kudos.mock.IdentityManagerMock org.exoplatform.social.core.storage.api.ActivityStorage - org.exoplatform.kudos.test.mock.ActivityStorageMock + io.meeds.test.kudos.mock.ActivityStorageMock org.exoplatform.social.core.manager.ActivityManager - org.exoplatform.kudos.test.mock.ActivityManagerMock + io.meeds.test.kudos.mock.ActivityManagerMock - - org.exoplatform.services.listener.ListenerService - - exo.kudos.activity - addListener - org.exoplatform.kudos.listener.KudosSentNotificationListener - - - exo.kudos.sent - addListener - org.exoplatform.kudos.listener.KudosSentActivityGeneratorListener - - - exo.kudos.activity - addListener - org.exoplatform.kudos.listener.GamificationIntegrationListener - - - kudos.cancel.activity - addListener - org.exoplatform.kudos.listener.GamificationIntegrationListener - - - kudos.cancel.activity - addListener - org.exoplatform.kudos.listener.KudosCanceledListener - - - org.exoplatform.commons.api.notification.service.setting.PluginContainer notification.plugins addChildPlugin - org.exoplatform.kudos.notification.plugin.KudosActivityChildPlugin + io.meeds.kudos.notification.plugin.KudosActivityChildPlugin Initial information for Kudos child notification plugin. @@ -86,24 +53,4 @@ - - org.exoplatform.social.core.manager.ActivityManager - - NewsActivityTypePlugin - addActivityTypePlugin - org.exoplatform.kudos.activity.KudosActivityTypePlugin - - - type - exokudos:activity - - - enableNotification - true - - - - - - org.exoplatform.commons.search.index.IndexingOperationProcessor diff --git a/kudos-webapps/src/main/java/io/meeds/kudos/KudosApplication.java b/kudos-webapps/src/main/java/io/meeds/kudos/KudosApplication.java index 54ac890b5..efcf1bc0f 100644 --- a/kudos-webapps/src/main/java/io/meeds/kudos/KudosApplication.java +++ b/kudos-webapps/src/main/java/io/meeds/kudos/KudosApplication.java @@ -1,14 +1,18 @@ -/* +/** * This file is part of the Meeds project (https://meeds.io/). - * Copyright (C) 2020 - 2022 Meeds Association contact@meeds.io + * + * Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io + * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. + * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. @@ -16,25 +20,25 @@ package io.meeds.kudos; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; import org.springframework.context.annotation.PropertySource; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import io.meeds.spring.AvailableIntegration; import io.meeds.spring.kernel.PortalApplicationContextInitializer; @SpringBootApplication(scanBasePackages = { - KudosApplication.MODULE_NAME, - AvailableIntegration.KERNEL_MODULE, - AvailableIntegration.JPA_MODULE, - AvailableIntegration.WEB_SECURITY_MODULE, -}, -exclude = { - LiquibaseAutoConfiguration.class, + KudosApplication.MODULE_NAME, + AvailableIntegration.KERNEL_MODULE, + AvailableIntegration.JPA_MODULE, + AvailableIntegration.LIQUIBASE_MODULE, + AvailableIntegration.WEB_MODULE, }) +@EnableJpaRepositories(basePackages = KudosApplication.MODULE_NAME) @PropertySource("classpath:application.properties") @PropertySource("classpath:application-common.properties") +@PropertySource("classpath:kudos.properties") public class KudosApplication extends PortalApplicationContextInitializer { - public static final String MODULE_NAME = "org.exoplatform.kudos"; + public static final String MODULE_NAME = "io.meeds.kudos"; } diff --git a/kudos-webapps/src/main/resources/kudos.properties b/kudos-webapps/src/main/resources/kudos.properties new file mode 100644 index 000000000..2b61ad5d5 --- /dev/null +++ b/kudos-webapps/src/main/resources/kudos.properties @@ -0,0 +1,20 @@ +# +# This file is part of the Meeds project (https://meeds.io/). +# +# Copyright (C) 2020 - 2024 Meeds Association contact@meeds.io +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 3 of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program; if not, write to the Free Software Foundation, +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +spring.liquibase.change-log=classpath:db/changelog/kudos-rdbms.db.changelog-master.xml \ No newline at end of file diff --git a/kudos-webapps/src/main/webapp/WEB-INF/conf/configuration.xml b/kudos-webapps/src/main/webapp/WEB-INF/conf/configuration.xml index cfb974537..7c29e1949 100644 --- a/kudos-webapps/src/main/webapp/WEB-INF/conf/configuration.xml +++ b/kudos-webapps/src/main/webapp/WEB-INF/conf/configuration.xml @@ -7,7 +7,6 @@ war:/conf/kudos/dynamic-container-configuration.xml war:/conf/kudos/notification-configuration.xml war:/conf/kudos/gamification-configuration.xml - war:/conf/kudos/activity-configuration.xml war:/conf/kudos/upgrade-configuration.xml diff --git a/kudos-webapps/src/main/webapp/WEB-INF/conf/kudos/activity-configuration.xml b/kudos-webapps/src/main/webapp/WEB-INF/conf/kudos/activity-configuration.xml deleted file mode 100644 index ed326d9c5..000000000 --- a/kudos-webapps/src/main/webapp/WEB-INF/conf/kudos/activity-configuration.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - org.exoplatform.social.core.manager.ActivityManager - - ActivityKudosProcessor - addProcessorPlugin - org.exoplatform.kudos.activity.processor.ActivityKudosProcessor - - - priority - priority of this processor (lower are executed first) - 20 - - - - - - \ No newline at end of file diff --git a/kudos-webapps/src/main/webapp/WEB-INF/conf/kudos/notification-configuration.xml b/kudos-webapps/src/main/webapp/WEB-INF/conf/kudos/notification-configuration.xml index 6666d1c29..edb8fadb9 100644 --- a/kudos-webapps/src/main/webapp/WEB-INF/conf/kudos/notification-configuration.xml +++ b/kudos-webapps/src/main/webapp/WEB-INF/conf/kudos/notification-configuration.xml @@ -36,7 +36,7 @@ notification.plugins addChildPlugin - org.exoplatform.kudos.notification.plugin.KudosActivityChildPlugin + io.meeds.kudos.notification.plugin.KudosActivityChildPlugin Initial information for Kudos child notification plugin. @@ -65,7 +65,7 @@ notification.plugins addPlugin - org.exoplatform.kudos.notification.plugin.KudosReceiverNotificationPlugin + io.meeds.kudos.notification.plugin.KudosReceiverNotificationPlugin template.KudosActivityReceiverNotificationPlugin @@ -107,7 +107,7 @@ mail.channel.kudos.template registerTemplateProvider - org.exoplatform.kudos.notification.provider.MailTemplateProvider + io.meeds.kudos.notification.provider.MailTemplateProvider channel-id @@ -118,7 +118,7 @@ push.channel.kudos.template registerTemplateProvider - org.exoplatform.kudos.notification.provider.MobilePushTemplateProvider + io.meeds.kudos.notification.provider.MobilePushTemplateProvider channel-id @@ -127,34 +127,6 @@ - - org.exoplatform.services.listener.ListenerService - - exo.kudos.activity - addListener - org.exoplatform.kudos.listener.KudosSentNotificationListener - - - exo.kudos.sent - addListener - org.exoplatform.kudos.listener.KudosSentActivityGeneratorListener - - - exo.kudos.activity - addListener - org.exoplatform.kudos.listener.GamificationIntegrationListener - - - kudos.cancel.activity - addListener - org.exoplatform.kudos.listener.GamificationIntegrationListener - - - kudos.cancel.activity - addListener - org.exoplatform.kudos.listener.KudosCanceledListener - - org.exoplatform.social.core.processor.I18NActivityProcessor @@ -186,25 +158,6 @@ - - org.exoplatform.social.core.manager.ActivityManager - - NewsActivityTypePlugin - addActivityTypePlugin - org.exoplatform.kudos.activity.KudosActivityTypePlugin - - - type - exokudos:activity - - - enableNotification - true - - - - - org.exoplatform.social.notification.service.SpaceWebNotificationService diff --git a/kudos-webapps/src/main/webapp/WEB-INF/portlet.xml b/kudos-webapps/src/main/webapp/WEB-INF/portlet.xml index 0ecef56a1..6221584a4 100644 --- a/kudos-webapps/src/main/webapp/WEB-INF/portlet.xml +++ b/kudos-webapps/src/main/webapp/WEB-INF/portlet.xml @@ -26,7 +26,7 @@ preload.resource.rest - + -1 PUBLIC diff --git a/kudos-webapps/src/main/webapp/vue-app/js/Kudos.js b/kudos-webapps/src/main/webapp/vue-app/js/Kudos.js index 26635f4d5..881d31c63 100644 --- a/kudos-webapps/src/main/webapp/vue-app/js/Kudos.js +++ b/kudos-webapps/src/main/webapp/vue-app/js/Kudos.js @@ -34,7 +34,7 @@ export function computeCommentKudosList(activity, comment) { export function sendKudos(kudo) { if (kudo) { - return fetch('/portal/rest/kudos/api/kudos', { + return fetch('/kudos/rest/kudos', { credentials: 'include', method: 'POST', headers: { @@ -55,7 +55,7 @@ export function sendKudos(kudo) { } export function deleteKudos(kudosId) { - return fetch(`${eXo.env.portal.context}/${eXo.env.portal.rest}/kudos/api/kudos/${kudosId}`, { + return fetch(`/kudos/rest/kudos/${kudosId}`, { method: 'DELETE', credentials: 'include', }).then((resp) => { @@ -72,7 +72,7 @@ export function deleteKudos(kudosId) { } export function getKudosSent(senderIdentityId, limit, returnSize, periodType, dateInSeconds) { - return fetch(`/portal/rest/kudos/api/kudos/${senderIdentityId}/sent?limit=${limit || 0}&returnSize=${returnSize || true}&periodType=${periodType || ''}&dateInSeconds=${dateInSeconds || '0'}`, { + return fetch(`/kudos/rest/kudos/${senderIdentityId}/sent?limit=${limit || 0}&returnSize=${returnSize || true}&periodType=${periodType || ''}&dateInSeconds=${dateInSeconds || '0'}`, { method: 'GET', credentials: 'include', }).then(resp => { @@ -85,7 +85,7 @@ export function getKudosSent(senderIdentityId, limit, returnSize, periodType, da } export function getKudosReceived(receiverIdentityId, limit, returnSize, periodType, dateInSeconds) { - return fetch(`/portal/rest/kudos/api/kudos/${receiverIdentityId}/received?limit=${limit || 0}&returnSize=${returnSize || true}&periodType=${periodType || ''}&dateInSeconds=${dateInSeconds || '0'}`, { + return fetch(`/kudos/rest/kudos/${receiverIdentityId}/received?limit=${limit || 0}&returnSize=${returnSize || true}&periodType=${periodType || ''}&dateInSeconds=${dateInSeconds || '0'}`, { method: 'GET', credentials: 'include', }).then(resp => { @@ -98,7 +98,7 @@ export function getKudosReceived(receiverIdentityId, limit, returnSize, periodTy } export function getKudosListByActivity(activityId) { - return fetch(`/portal/rest/kudos/api/kudos/byActivity/${activityId}/all`, { + return fetch(`/kudos/rest/kudos/byActivity/${activityId}/all`, { method: 'GET', credentials: 'include', }).then(resp => { @@ -112,7 +112,7 @@ export function getKudosListByActivity(activityId) { export function getEntityKudos(entityType, entityId, limit) { if (entityType && entityId) { - return fetch(`/portal/rest/kudos/api/kudos/byEntity?entityId=${entityId}&entityType=${entityType}&limit=${limit || 0}`, { + return fetch(`/kudos/rest/kudos/byEntity?entityId=${entityId}&entityType=${entityType}&limit=${limit || 0}`, { method: 'GET', credentials: 'include', }).then(resp => { @@ -128,7 +128,7 @@ export function getEntityKudos(entityType, entityId, limit) { } export function countUserKudosSentByEntity(entityType, entityId) { - return fetch(`/portal/rest/kudos/api/kudos/byEntity/sent/count?entityId=${entityId}&entityType=${entityType}`, { + return fetch(`/kudos/rest/kudos/byEntity/sent/count?entityId=${entityId}&entityType=${entityType}`, { method: 'GET', credentials: 'include', }).then(resp => { @@ -143,7 +143,7 @@ export function countUserKudosSentByEntity(entityType, entityId) { export function getKudosByPeriodOfDate(date, limit) { // convert from milliseconds to seconds date = parseInt(date.getTime() / 1000); - return fetch(`/portal/rest/kudos/api/kudos?dateInSeconds=${date}&limit=${limit || 0}`, { + return fetch(`/kudos/rest/kudos?dateInSeconds=${date}&limit=${limit || 0}`, { method: 'GET', credentials: 'include', }).then(resp => { @@ -159,7 +159,7 @@ export function getKudosByPeriod(startDate, endDate, limit) { // convert from milliseconds to seconds startDate = parseInt(startDate.getTime() / 1000); endDate = parseInt(endDate.getTime() / 1000); - return fetch(`/portal/rest/kudos/api/kudos/byDates?startDateInSeconds=${startDate}&endDateInSeconds=${endDate}&limit=${limit || 0}`, { + return fetch(`/kudos/rest/kudos/byDates?startDateInSeconds=${startDate}&endDateInSeconds=${endDate}&limit=${limit || 0}`, { method: 'GET', credentials: 'include', }).then(resp => { @@ -174,7 +174,7 @@ export function getKudosByPeriod(startDate, endDate, limit) { export function getPeriodDates(date, periodType) { // convert from milliseconds to seconds date = parseInt(date.getTime() / 1000); - return fetch(`/portal/rest/kudos/api/kudos/period?dateInSeconds=${date}&periodType=${periodType}`, { + return fetch(`/kudos/rest/kudos/period?dateInSeconds=${date}&periodType=${periodType}`, { method: 'GET', credentials: 'include', }).then(resp => { diff --git a/kudos-webapps/src/main/webapp/vue-app/js/KudosIdentity.js b/kudos-webapps/src/main/webapp/vue-app/js/KudosIdentity.js index db0b22d08..3b9af510c 100644 --- a/kudos-webapps/src/main/webapp/vue-app/js/KudosIdentity.js +++ b/kudos-webapps/src/main/webapp/vue-app/js/KudosIdentity.js @@ -49,7 +49,7 @@ export function getIdentityDetails(urlId, type, remoteId) { }; // check if user is authorized to receive Kudos - return (window.kudosSettings.accessPermission && type === 'user' ? fetch(`/portal/rest/kudos/api/account/isAuthorized?username=${urlId}`, {credentials: 'include'}) : Promise.resolve({ok: true})) + return (window.kudosSettings.accessPermission && type === 'user' ? fetch(`/kudos/rest/account/isAuthorized?username=${urlId}`, {credentials: 'include'}) : Promise.resolve({ok: true})) .then((resp) => { if (!resp || !resp.ok) { ownerDetails.notAuthorized = true; diff --git a/kudos-webapps/src/main/webapp/vue-app/js/KudosSettings.js b/kudos-webapps/src/main/webapp/vue-app/js/KudosSettings.js index 9fb889290..d7b1edc32 100644 --- a/kudos-webapps/src/main/webapp/vue-app/js/KudosSettings.js +++ b/kudos-webapps/src/main/webapp/vue-app/js/KudosSettings.js @@ -1,5 +1,5 @@ export function initSettings() { - return fetch('/portal/rest/kudos/api/account/settings', {credentials: 'include'}) + return fetch('/kudos/rest/account/settings', {credentials: 'include'}) .then((resp) => resp && resp.ok && resp.json()) .then((settings) => (window.kudosSettings = settings ? settings : {})) .then(() => getSettings()) @@ -11,12 +11,12 @@ export function initSettings() { } export function getSettings() { - return fetch('/portal/rest/kudos/api/settings', {credentials: 'include'}).then((resp) => resp && resp.ok && resp.json()); + return fetch('/kudos/rest/settings', {credentials: 'include'}).then((resp) => resp && resp.ok && resp.json()); } export function saveSettings(settings) { if (settings) { - return fetch('/portal/rest/kudos/api/settings/save', { + return fetch('/kudos/rest/settings', { credentials: 'include', method: 'POST', headers: {