[AB-138] improving logging at various places fixing various issues regarding async commands and exception handling, fixing role role calculation being done twice

This commit is contained in:
Sheldan
2020-10-07 09:29:56 +02:00
parent a391381ff6
commit 0145e7670d
165 changed files with 1129 additions and 513 deletions

View File

@@ -59,6 +59,7 @@ public class LeaderBoardCommand extends AbstractConditionableCommand {
LeaderBoard leaderBoard = userExperienceService.findLeaderBoardData(commandContext.getUserInitiatedContext().getServer(), page);
LeaderBoardModel leaderBoardModel = (LeaderBoardModel) ContextConverter.fromCommandContext(commandContext, LeaderBoardModel.class);
leaderBoardModel.setUserExperiences(converter.fromLeaderBoard(leaderBoard));
log.info("Rendering leaderboard for page {} in server {} for user {}.", page, commandContext.getAuthor().getId(), commandContext.getGuild().getId());
LeaderBoardEntry userRank = userExperienceService.getRankOfUserInServer(commandContext.getUserInitiatedContext().getAUserInAServer());
leaderBoardModel.setUserExecuting(converter.fromLeaderBoardEntry(userRank));

View File

@@ -19,6 +19,7 @@ import dev.sheldan.abstracto.experience.service.ExperienceLevelService;
import dev.sheldan.abstracto.experience.service.AUserExperienceService;
import dev.sheldan.abstracto.templating.model.MessageToSend;
import dev.sheldan.abstracto.templating.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -30,6 +31,7 @@ import java.util.concurrent.CompletableFuture;
* Command used to show an embed containing information about the experience amount, level and message count of a ember on a server
*/
@Component
@Slf4j
public class Rank extends AbstractConditionableCommand {
public static final String RANK_POST_EMBED_TEMPLATE = "rank_post";
@@ -56,6 +58,7 @@ public class Rank extends AbstractConditionableCommand {
LeaderBoardEntry userRank = userExperienceService.getRankOfUserInServer(commandContext.getUserInitiatedContext().getAUserInAServer());
rankModel.setRankUser(converter.fromLeaderBoardEntry(userRank));
AUserExperience experienceObj = userRank.getExperience();
log.info("Rendering rank for user {} in server {}.", commandContext.getAuthor().getId(), commandContext.getGuild().getId());
rankModel.setExperienceToNextLevel(experienceLevelService.calculateExperienceToNextLevel(experienceObj.getCurrentLevel().getLevel(), experienceObj.getExperience()));
MessageToSend messageToSend = templateService.renderEmbedTemplate(RANK_POST_EMBED_TEMPLATE, rankModel);
return FutureUtils.toSingleFutureGeneric(channelService.sendMessageToSendToChannel(messageToSend, commandContext.getChannel()))

View File

@@ -5,6 +5,7 @@ import dev.sheldan.abstracto.core.service.BotService;
import dev.sheldan.abstracto.experience.models.LeaderBoard;
import dev.sheldan.abstracto.experience.models.LeaderBoardEntry;
import dev.sheldan.abstracto.experience.models.templates.LeaderBoardEntryModel;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -16,6 +17,7 @@ import java.util.List;
* Converter used to convert from {@link LeaderBoard} to a list of {@link LeaderBoardEntryModel}
*/
@Component
@Slf4j
public class LeaderBoardModelConverter {
@Autowired
@@ -30,6 +32,7 @@ public class LeaderBoardModelConverter {
*/
public List<LeaderBoardEntryModel> fromLeaderBoard(LeaderBoard leaderBoard) {
List<LeaderBoardEntryModel> models = new ArrayList<>();
log.trace("Converting {} entries to a list of leaderbord entries.", leaderBoard.getEntries().size());
leaderBoard.getEntries().forEach(leaderBoardEntry -> {
LeaderBoardEntryModel entry = fromLeaderBoardEntry(leaderBoardEntry);
models.add(entry);

View File

@@ -36,8 +36,9 @@ public class ExperiencePersistingJob extends QuartzJobBean {
log.info("Running experience persisting job.");
Long pastMinute = (Instant.now().getEpochSecond() / 60) - 1;
if(runtimeExperience.containsKey(pastMinute)) {
log.info("Found experience to persist.");
userExperienceService.handleExperienceGain(runtimeExperience.get(pastMinute)).thenAccept(aVoid ->
List<ServerExperience> foundServers = runtimeExperience.get(pastMinute);
log.info("Found experience from {} servers to persist.", foundServers.size());
userExperienceService.handleExperienceGain(foundServers).thenAccept(aVoid ->
runtimeExperience.remove(pastMinute)
);
}

View File

@@ -34,8 +34,10 @@ public class JoiningUserRoleListener implements JoinListener {
if(userExperience != null) {
log.info("User {} joined {} with previous experience. Setting up experience role again (if necessary).", member.getUser().getIdLong(), guild.getIdLong());
userExperienceService.syncForSingleUser(userExperience).thenAccept(result ->
log.trace("Finished re-assigning experience for re-joning user {} in server {}.", userInServerId, guild.getIdLong())
log.info("Finished re-assigning experience for re-joning user {} in server {}.", userInServerId, guild.getIdLong())
);
} else {
log.info("Joined user {} in server {} does not have any previous experience. Not setting up anything.", member.getId(), guild.getId());
}
}

View File

@@ -32,7 +32,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -89,23 +88,27 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
*/
@Override
public void addExperience(AUserInAServer userInAServer) {
Long second = Instant.now().getEpochSecond() / 60;
Long minute = Instant.now().getEpochSecond() / 60;
Map<Long, List<ServerExperience>> runtimeExperience = runTimeExperienceService.getRuntimeExperience();
if(runtimeExperience.containsKey(second)) {
List<ServerExperience> existing = runtimeExperience.get(second);
existing.forEach(server -> {
if(server.getUserInServerIds().stream().noneMatch(userInAServer1 -> userInAServer.getUserInServerId().equals(userInAServer1))) {
if(runtimeExperience.containsKey(minute)) {
log.trace("Minute {} already tracked, adding user {} in server {}.",
minute, userInAServer.getUserReference().getId(), userInAServer.getServerReference().getId());
List<ServerExperience> existing = runtimeExperience.get(minute);
for (ServerExperience server : existing) {
if (server.getServerId().equals(userInAServer.getServerReference().getId()) && server.getUserInServerIds().stream().noneMatch(userInAServer1 -> userInAServer.getUserInServerId().equals(userInAServer1))) {
server.getUserInServerIds().add(userInAServer.getUserInServerId());
break;
}
});
}
} else {
log.trace("Minute {} did not exist yet. Creating new entry for user {} in server {}.", minute, userInAServer.getUserReference().getId(), userInAServer.getServerReference().getId());
ServerExperience serverExperience = ServerExperience
.builder()
.serverId(userInAServer.getServerReference().getId())
.build();
serverExperience.getUserInServerIds().add(userInAServer.getUserInServerId());
runtimeExperience.put(second, new ArrayList<>(Arrays.asList(serverExperience)));
runtimeExperience.put(minute, new ArrayList<>(Arrays.asList(serverExperience)));
}
}
@@ -128,11 +131,13 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
AExperienceLevel lastLevel = levels.get(0);
for (AExperienceLevel level : levels) {
if(level.getExperienceNeeded() >= experienceCount) {
log.trace("Calculated level {} for {} experience.", lastLevel.getLevel(), experienceCount);
return lastLevel;
} else {
lastLevel = level;
}
}
log.trace("Calculated level {} for {} experience.", lastLevel.getLevel(), experienceCount);
return lastLevel;
}
@@ -166,7 +171,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
// TODO what if there are a lot in here...., transaction size etc
servers.forEach(serverExp -> {
AServer server = serverManagementService.loadOrCreate(serverExp.getServerId());
log.trace("Handling experience for server {}", serverExp.getServerId());
log.info("Handling {} experience for server {}", serverExp.getUserInServerIds().size(), serverExp.getServerId());
int minExp = configService.getLongValue(ExperienceFeatureConfig.MIN_EXP_KEY, serverExp.getServerId()).intValue();
int maxExp = configService.getLongValue(ExperienceFeatureConfig.MAX_EXP_KEY, serverExp.getServerId()).intValue();
Double multiplier = configService.getDoubleValue(ExperienceFeatureConfig.EXP_MULTIPLIER_KEY, serverExp.getServerId());
@@ -206,7 +211,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
log.trace("Experience gain was disabled. User did not gain any experience.");
}
} else {
log.info("user experience for user {} was not found. Planning to create new instance.", userInAServer.getUserInServerId());
log.info("User experience for user {} was not found. Planning to create new instance.", userInAServer.getUserInServerId());
Long newExperience = gainedExperience.longValue();
AExperienceLevel newLevel = calculateLevel(levels, newExperience);
Long newMessageCount = 1L;
@@ -246,6 +251,8 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
}
AExperienceRole role = experienceRoleService.calculateRole(roles, currentLevel);
if(role == null) {
log.trace("No experience role calculated. Applying none to user {} in server {}.",
aUserInAServer.getUserReference().getId(), aUserInAServer.getServerReference().getId());
return CompletableFuture.completedFuture(RoleCalculationResult
.builder()
.userInServerId(aUserInAServer.getUserInServerId())
@@ -254,6 +261,8 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
}
Long experienceRoleId = role.getId();
Long userInServerId = aUserInAServer.getUserInServerId();
log.trace("Applying {} as the first experience role for user {} in server {}.",
experienceRoleId, aUserInAServer.getUserReference().getId(), aUserInAServer.getServerReference().getId());
return roleService.addRoleToUserFuture(aUserInAServer, role.getRole()).thenApply(aVoid -> RoleCalculationResult
.builder()
.experienceRoleId(experienceRoleId)
@@ -264,6 +273,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
@Transactional
public void persistExperienceChanges(List<ExperienceGainResult> resultFutures) {
List<AExperienceLevel> levels = experienceLevelManagementService.getLevelConfig();
log.info("Storing {} experience gain results.", resultFutures.size());
HashMap<Long, List<AExperienceRole>> serverRoleMapping = new HashMap<>();
resultFutures.forEach(experienceGainResult -> {
AUserInAServer user = userInServerManagementService.loadUser(experienceGainResult.getUserInServerId());
@@ -280,14 +290,14 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
if(foundLevel.isPresent()) {
userExperience.setCurrentLevel(foundLevel.get());
} else {
log.warn("User {} was present, but no level could be found.", userExperience.getUser().getUserReference().getId());
log.warn("User {} was present, but no level matching the calculation result {} could be found.", userExperience.getUser().getUserReference().getId(), experienceGainResult.getNewLevel());
}
AServer server = user.getServerReference();
if(!serverRoleMapping.containsKey(server.getId())) {
serverRoleMapping.put(server.getId(), experienceRoleManagementService.getExperienceRolesForServer(server));
}
List<AExperienceRole> roleConfig = serverRoleMapping.get(server.getId());
AExperienceRole role = experienceRoleService.calculateRole(roleConfig, userExperience.getLevelOrDefault());
RoleCalculationResult roleCalculationResult = experienceGainResult.getCalculationResult().join();
AExperienceRole role = experienceRoleManagementService.getExperienceRoleById(roleCalculationResult.getExperienceRoleId());
userExperience.setCurrentExperienceRole(role);
if(experienceGainResult.isCreateUserExperience()) {
userExperienceManagementService.saveUser(userExperience);
@@ -321,6 +331,8 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
Member member = botService.getMemberInServer(user.getServerReference(), user.getUserReference());
boolean currentlyHasNoExperienceRole = userExperience.getCurrentExperienceRole() == null;
if(role == null) {
log.trace("User {} in server {} does not have an experience role, according to new calculation.",
user.getUserReference().getId(), user.getServerReference().getId());
if(!currentlyHasNoExperienceRole){
return roleService.removeRoleFromUserFuture(user, userExperience.getCurrentExperienceRole().getRole())
.thenApply(returnNullRole);
@@ -335,7 +347,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
.userInServerId(userInServerId)
.build();
if(!userHasRoleAlready && (currentlyHasNoExperienceRole || !role.getRole().getId().equals(userExperience.getCurrentExperienceRole().getRole().getId()))) {
log.info("User {} in server {} gets a new role {}", user.getUserReference().getId(), user.getServerReference().getId(), role.getRole().getId());
log.info("User {} in server {} gets a new role {} because of experience.", user.getUserReference().getId(), user.getServerReference().getId(), role.getRole().getId());
CompletableFuture<Void> removalFuture;
if(!currentlyHasNoExperienceRole && botService.isUserInGuild(userExperience.getUser())) {
removalFuture = roleService.removeRoleFromUserFuture(user, userExperience.getCurrentExperienceRole().getRole());
@@ -395,9 +407,11 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
AUserExperience userExperience = userExperienceManagementService.findUserInServer(user);
log.trace("Updating experience role for {} in server {} to {}", user.getUserInServerId(), user.getServerReference(), result.getExperienceRoleId());
if(result.getExperienceRoleId() != null) {
log.trace("User experience {} gets new experience role with id {}.", userExperience.getId(), result.getExperienceRoleId());
AExperienceRole role = experienceRoleManagementService.getExperienceRoleById(result.getExperienceRoleId());
userExperience.setCurrentExperienceRole(role);
} else {
log.trace("User experience {} does not get a user experience role.", userExperience.getId());
userExperience.setCurrentExperienceRole(null);
}
}
@@ -414,30 +428,26 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
public CompletableFutureList<RoleCalculationResult> executeActionOnUserExperiencesWithFeedBack(List<AUserExperience> experiences, AChannel channel, Function<AUserExperience, CompletableFuture<RoleCalculationResult>> toExecute) {
List<CompletableFuture<RoleCalculationResult>> futures = new ArrayList<>();
MessageToSend status = getUserSyncStatusUpdateModel(0, experiences.size());
try {
Message statusMessage = messageService.createStatusMessage(status, channel).get();
int interval = Math.min(Math.max(experiences.size() / 10, 1), 100);
for (int i = 0; i < experiences.size(); i++) {
if((i % interval) == 1) {
log.trace("Updating feedback message with new index {} out of {}", i, experiences.size());
status = getUserSyncStatusUpdateModel(i, experiences.size());
messageService.updateStatusMessage(channel, statusMessage.getIdLong(), status);
}
futures.add(toExecute.apply(experiences.get(i)));
log.trace("Synchronizing {} out of {}", i, experiences.size());
Message statusMessage = messageService.createStatusMessage(status, channel).join();
int interval = Math.min(Math.max(experiences.size() / 10, 1), 100);
for (int i = 0; i < experiences.size(); i++) {
if((i % interval) == 1) {
log.trace("Updating feedback message with new index {} out of {}", i, experiences.size());
status = getUserSyncStatusUpdateModel(i, experiences.size());
messageService.updateStatusMessage(channel, statusMessage.getIdLong(), status);
}
status = getUserSyncStatusUpdateModel(experiences.size(), experiences.size());
messageService.updateStatusMessage(channel, statusMessage.getIdLong(), status);
} catch (InterruptedException | ExecutionException e) {
log.info("Failed to synchronize users.", e);
Thread.currentThread().interrupt();
futures.add(toExecute.apply(experiences.get(i)));
log.trace("Synchronizing {} out of {}", i, experiences.size());
}
status = getUserSyncStatusUpdateModel(experiences.size(), experiences.size());
messageService.updateStatusMessage(channel, statusMessage.getIdLong(), status);
return new CompletableFutureList<>(futures);
}
@Override
public void disableExperienceForUser(AUserInAServer userInAServer) {
log.info("Disabling experience gain for user {} in server {}.", userInAServer.getUserReference().getId(), userInAServer.getServerReference().getId());
AUserExperience userExperience = userExperienceManagementService.findUserInServer(userInAServer);
userExperience.setExperienceGainDisabled(true);
}
@@ -445,6 +455,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
@Override
public void enableExperienceForUser(AUserInAServer userInAServer) {
AUserExperience userExperience = userExperienceManagementService.findUserInServer(userInAServer);
log.info("Enabling experience gain for user {} in server {}.", userInAServer.getUserReference().getId(), userInAServer.getServerReference().getId());
userExperience.setExperienceGainDisabled(false);
}
@@ -478,8 +489,10 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
}
page--;
int pageSize = 10;
log.trace("Loading leaderboard page {} for server {}.", page, server.getId());
List<AUserExperience> experiences = userExperienceManagementService.findLeaderBoardUsersPaginated(server, page * pageSize, (page + 1) * pageSize);
List<LeaderBoardEntry> entries = new ArrayList<>();
log.trace("Found {} experiences.", experiences.size());
for (int i = 0; i < experiences.size(); i++) {
AUserExperience userExperience = experiences.get(i);
entries.add(LeaderBoardEntry.builder().experience(userExperience).rank((page * pageSize) + i + 1).build());
@@ -494,7 +507,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
*/
@Override
public LeaderBoardEntry getRankOfUserInServer(AUserInAServer userInAServer) {
log.info("Retrieving rank for {}", userInAServer.getUserReference().getId());
log.trace("Retrieving rank for {}", userInAServer.getUserReference().getId());
AUserExperience aUserExperience = userExperienceManagementService.findUserInServer(userInAServer);
Integer rank = 0;
if(aUserExperience != null) {

View File

@@ -21,7 +21,7 @@ public class ExperienceLevelServiceBean implements ExperienceLevelService {
*/
private void createExperienceLevel(Integer level, Long experienceNeeded) {
if(!experienceLevelManagementService.levelExists(level)) {
log.trace("Creating new experience level {} with experience needed {}.", level, experienceNeeded);
log.info("Creating new experience level {} with experience needed {}.", level, experienceNeeded);
experienceLevelManagementService.createExperienceLevel(level, experienceNeeded);
}
}
@@ -32,6 +32,7 @@ public class ExperienceLevelServiceBean implements ExperienceLevelService {
*/
@Override
public void createLevelsUntil(Integer level) {
log.info("Creating experience levels until level {}.", level);
createExperienceLevel(0, 0L);
long experience = 0L;
for (int i = 1; i < level; i++) {

View File

@@ -59,6 +59,7 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
@Transactional
public void unsetRoleInDb(Integer level, Long roleId) {
log.info("Unsetting role {} from level {}.", roleId, level);
AExperienceLevel experienceLevel = experienceLevelService.getLevel(level).orElseThrow(() -> new IllegalArgumentException(String.format("Could not find level %s", level)));
ARole loadedRole = roleManagementService.findRole(roleId);
experienceRoleManagementService.removeAllRoleAssignmentsForLevelInServer(experienceLevel, loadedRole.getServer());
@@ -87,6 +88,7 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
self.persistData(calculationResults, roleId)
);
} else {
log.info("Roles does not have any active users, no need to remove them.");
experienceRoleManagementService.unsetRole(roleInServer);
return CompletableFuture.completedFuture(null);
}
@@ -98,6 +100,7 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
@Transactional
public void persistData(CompletableFutureList<RoleCalculationResult> results, Long roleId) {
log.info("Persisting {} role calculation results after changing the role {}.", results.getFutures().size(), roleId);
AExperienceRole roleInServer = experienceRoleManagementService.getRoleInServer(roleId);
experienceRoleManagementService.unsetRole(roleInServer);
userExperienceService.syncRolesInStorage(results.getObjects());
@@ -115,6 +118,7 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
if(roles == null || roles.isEmpty()) {
return null;
}
log.trace("Calculating role for level {} in server {}. Using {} roles in our config.", currentLevel, roles.get(0).getRoleServer().getId(), roles.size());
AExperienceRole lastRole = null;
for (AExperienceRole experienceRole : roles) {
if(currentLevel >= experienceRole.getLevel().getLevel()) {
@@ -128,6 +132,7 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
@Override
public AExperienceLevel getLevelOfNextRole(AExperienceLevel startLevel, AServer server) {
log.trace("Calculating level of next role for level {} in server {}.", startLevel.getLevel(), server.getId());
List<AExperienceRole> roles = experienceRoleManagementService.getExperienceRolesForServer(server);
roles = roles.stream().filter(role -> role.getLevel().getLevel() > startLevel.getLevel()).collect(Collectors.toList());
roles.sort(Comparator.comparing(role -> role.getLevel().getLevel()));

View File

@@ -8,6 +8,7 @@ import dev.sheldan.abstracto.core.service.SystemCondition;
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
import dev.sheldan.abstracto.experience.service.management.UserExperienceManagementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -16,6 +17,7 @@ import java.util.HashMap;
import java.util.Optional;
@Component
@Slf4j
public class HasLevelCondition implements SystemCondition {
public static final String USER_ID_VARIABLE = "userId";
@@ -29,15 +31,18 @@ public class HasLevelCondition implements SystemCondition {
@Override
public boolean checkCondition(ConditionContextInstance conditionContext) {
HashMap<String, Object> parameters = conditionContext.getParameters();
Long userId = (Long) parameters.get(USER_ID_VARIABLE);
Integer level = (Integer) parameters.get(LEVEL_VARIABLE);
log.info("Evaluating has level condition.");
Optional<AUserInAServer> userInServerOptional = userInServerManagementService.loadUserConditional(userId);
if(userInServerOptional.isPresent()) {
AUserInAServer userInServer = userInServerOptional.get();
log.info("Evaluating has level condition for user {} in server {} with level {}.",
userInServer.getUserReference().getId(), userInServer.getServerReference().getId(), level);
AUserExperience user = userExperienceManagementService.findUserInServer(userInServer);
return user.getCurrentLevel() != null && user.getCurrentLevel().getLevel() >= level;
}
log.info("No user experience object was found. Evaluating to false.");
return false;
}

View File

@@ -4,12 +4,14 @@ import dev.sheldan.abstracto.core.models.database.ARole;
import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.experience.models.database.ADisabledExpRole;
import dev.sheldan.abstracto.experience.repository.DisabledExpRoleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Slf4j
public class DisabledExpRoleManagementServiceBean implements DisabledExpRoleManagementService {
@Autowired
@@ -21,7 +23,7 @@ public class DisabledExpRoleManagementServiceBean implements DisabledExpRoleMana
.builder()
.role(role)
.build();
log.info("Adding disabled exp role {} for server {}.", role.getId(),role.getServer().getId());
return disabledExpRoleRepository.save(newRole);
}

View File

@@ -9,7 +9,7 @@ import java.util.List;
import java.util.Optional;
@Component
public class ExperienceLevelManagementServiceBean implements ExperienceLevelManagementService {
public class ExperienceLevelManagementServiceBean implements ExperienceLevelManagementService {
@Autowired
private ExperienceLevelRepository experienceLevelRepository;

View File

@@ -31,13 +31,14 @@ public class ExperienceRoleManagementServiceBean implements ExperienceRoleManage
*/
@Override
public void removeAllRoleAssignmentsForLevelInServer(AExperienceLevel level, AServer server) {
log.trace("Removing all role assignments for level {}.", level.getLevel());
List<AExperienceRole> existingExperienceRoles = experienceRoleRepository.findByLevelAndRoleServer(level, server);
log.info("Removing all role assignments ({}) for level {} in server {}.", existingExperienceRoles.size(), level.getLevel(), server.getId());
existingExperienceRoles.forEach(existingRole -> experienceRoleRepository.delete(existingRole));
}
@Override
public void unsetRole(AExperienceRole role) {
log.info("Deleting experience role {} in server {}.", role.getId(), role.getRoleServer().getId());
experienceRoleRepository.delete(role);
}
@@ -82,7 +83,9 @@ public class ExperienceRoleManagementServiceBean implements ExperienceRoleManage
public AExperienceRole setLevelToRole(AExperienceLevel level, ARole role) {
Optional<AExperienceRole> byRoleServerAndRoleOptional = getRoleInServerOptional(role);
AExperienceRole experienceRole;
log.info("Setting role {} in server {} to level {}.", role.getId(), role.getServer().getId(), level);
if(byRoleServerAndRoleOptional.isPresent()) {
log.trace("Role already existed. Updating.");
experienceRole = byRoleServerAndRoleOptional.get();
experienceRole.setLevel(level);
} else {
@@ -92,6 +95,7 @@ public class ExperienceRoleManagementServiceBean implements ExperienceRoleManage
.roleServer(role.getServer())
.role(role)
.build();
log.trace("Role did not exist. Creating new.");
experienceRole = experienceRoleRepository.save(experienceRole);
}
return experienceRole;

View File

@@ -8,6 +8,7 @@ import dev.sheldan.abstracto.experience.models.database.LeaderBoardEntryResult;
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
import dev.sheldan.abstracto.experience.repository.UserExperienceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
@@ -15,7 +16,7 @@ import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Slf4j
@Component
public class UserExperienceManagementServiceBean implements UserExperienceManagementService {
@@ -48,6 +49,7 @@ public class UserExperienceManagementServiceBean implements UserExperienceManage
*/
@Override
public AUserExperience createUserInServer(AUserInAServer aUserInAServer) {
log.info("Creating user experience for user {} in server {}.", aUserInAServer.getUserReference().getId(),aUserInAServer.getServerReference().getId());
AExperienceLevel startingLevel = experienceLevelManagementService.getLevel(0).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", 0)));
return AUserExperience
.builder()
@@ -65,37 +67,6 @@ public class UserExperienceManagementServiceBean implements UserExperienceManage
return repository.findByUser_ServerReference(server);
}
/**
* Creates or updates the {@link AUserExperience} object. Does not change the level or the role.
* @param user The {@link AUserInAServer} to increase the experience for
* @param experience The experience amount to increase by
* @param messageCount The amount of messages to increase the count by
* @return The created/changed {@link AUserExperience} object
*/
@Override
public AUserExperience incrementExpForUser(AUserInAServer user, Long experience, Long messageCount) {
Optional<AUserExperience> byId = repository.findById(user.getUserInServerId());
if(byId.isPresent()) {
AUserExperience userExperience = byId.get();
if(Boolean.FALSE.equals(userExperience.getExperienceGainDisabled())) {
userExperience.setMessageCount(userExperience.getMessageCount() + messageCount);
userExperience.setExperience(userExperience.getExperience() + experience);
}
return userExperience;
} else {
AExperienceLevel startingLevel = experienceLevelManagementService.getLevel(0).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", 0)));
return AUserExperience
.builder()
.experience(experience)
.messageCount(messageCount)
.experienceGainDisabled(false)
.user(user)
.id(user.getUserInServerId())
.currentLevel(startingLevel)
.build();
}
}
@Override
public List<AUserExperience> findLeaderBoardUsersPaginated(AServer aServer, Integer start, Integer end) {
return repository.findTop10ByUser_ServerReferenceOrderByExperienceDesc(aServer, PageRequest.of(start, end));

View File

@@ -13,7 +13,6 @@ import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
import dev.sheldan.abstracto.experience.service.management.ExperienceLevelManagementService;
import dev.sheldan.abstracto.experience.service.management.ExperienceRoleManagementService;
import dev.sheldan.abstracto.test.MockUtils;
import net.dv8tion.jda.api.entities.Role;
import org.junit.Assert;
import org.junit.Test;
@@ -52,10 +51,12 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
@Mock
private ExperienceRoleServiceBean self;
@Mock
private AServer server;
@Test
public void testSettingRoleToLevelWithoutOldUsers() {
AServer server = MockUtils.getServer();
Integer levelCount = 10;
AExperienceLevel level = AExperienceLevel.builder().experienceNeeded(10L).level(levelCount).build();
Role roleToChange = Mockito.mock(Role.class);
@@ -73,7 +74,6 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
@Test
public void testUnsetRoleInDb() {
AServer server = MockUtils.getServer();
Integer levelCount = 10;
AExperienceLevel level = AExperienceLevel.builder().experienceNeeded(10L).level(levelCount).build();
ARole roleToChange = getRole(1L, server);
@@ -89,7 +89,6 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
@Test
public void testSettingRoleToLevelExistingUsers() {
AServer server = MockUtils.getServer();
Integer levelCount = 10;
AExperienceLevel level = AExperienceLevel.builder().experienceNeeded(10L).level(levelCount).build();
Role roleToChange = Mockito.mock(Role.class);
@@ -158,7 +157,6 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
@Test
public void testCalculatingLevelOfNextRole() {
AServer server = MockUtils.getServer();
when(experienceRoleManagementService.getExperienceRolesForServer(server)).thenReturn(getExperienceRoles());
AExperienceLevel levelToCheckFor = AExperienceLevel.builder().level(7).build();
AExperienceLevel levelOfNextRole = testingUnit.getLevelOfNextRole(levelToCheckFor, server);
@@ -167,7 +165,6 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
@Test
public void testCalculatingLevelOfNextRoleIfThereIsNone() {
AServer server = MockUtils.getServer();
when(experienceRoleManagementService.getExperienceRolesForServer(server)).thenReturn(getExperienceRoles());
AExperienceLevel levelToCheckFor = AExperienceLevel.builder().level(15).build();
AExperienceLevel levelOfNextRole = testingUnit.getLevelOfNextRole(levelToCheckFor, server);
@@ -182,7 +179,7 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
private AExperienceRole getExperienceRoleForLevel(int levelToBuild) {
AExperienceLevel firstLevel = AExperienceLevel.builder().level(levelToBuild).build();
return AExperienceRole.builder().level(firstLevel).build();
return AExperienceRole.builder().roleServer(server).level(firstLevel).build();
}
private ARole getRole(Long id, AServer server) {

View File

@@ -61,6 +61,7 @@ public class DisabledExpRoleManagementServiceBeanTest extends ExperienceRelatedT
}
private ARole getARole() {
return ARole.builder().id(1L).build();
AServer server = AServer.builder().id(4L).build();
return ARole.builder().id(1L).server(server).build();
}
}

View File

@@ -132,7 +132,9 @@ public class ExperienceRoleManagementServiceBeanTest extends ExperienceRelatedTe
private AExperienceRole getExperienceRoleForLevel(int levelToBuild) {
AExperienceLevel firstLevel = AExperienceLevel.builder().level(levelToBuild).build();
return AExperienceRole.builder().role(ARole.builder().id((long) levelToBuild).build()).level(firstLevel).build();
AServer server = AServer.builder().id(4L).build();
ARole aRole = ARole.builder().id((long) levelToBuild).server(server).build();
return AExperienceRole.builder().role(aRole).roleServer(server).level(firstLevel).build();
}
private AExperienceLevel getLevel(Integer level, Long neededExperience) {

View File

@@ -15,6 +15,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.domain.PageRequest;
@@ -47,7 +48,13 @@ public class UserExperienceManagementServiceBeanTest extends ExperienceRelatedTe
@Test
public void testNoUserCreateNewWhenSearching() {
AUserInAServer user = AUserInAServer.builder().userInServerId(1L).userReference(AUser.builder().id(2L).build()).build();
AUserInAServer user = Mockito.mock(AUserInAServer.class);
AServer server = Mockito.mock(AServer.class);
when(user.getServerReference()).thenReturn(server);
when(server.getId()).thenReturn(2L);
AUser aUser = Mockito.mock(AUser.class);
when(aUser.getId()).thenReturn(4L);
when(user.getUserReference()).thenReturn(aUser);
when(repository.findById(user.getUserInServerId())).thenReturn(Optional.empty());
AExperienceLevel startLevel = mockInitialLevel();
AUserExperience userInServer = testUnit.findUserInServer(user);
@@ -59,7 +66,13 @@ public class UserExperienceManagementServiceBeanTest extends ExperienceRelatedTe
@Test
public void testCreatingUserExperience() {
AUserInAServer user = AUserInAServer.builder().userInServerId(1L).userReference(AUser.builder().id(2L).build()).build();
AUserInAServer user = Mockito.mock(AUserInAServer.class);
AServer server = Mockito.mock(AServer.class);
when(user.getServerReference()).thenReturn(server);
when(server.getId()).thenReturn(2L);
AUser aUser = Mockito.mock(AUser.class);
when(aUser.getId()).thenReturn(4L);
when(user.getUserReference()).thenReturn(aUser);
AExperienceLevel startLevel = mockInitialLevel();
AUserExperience userInServer = testUnit.createUserInServer(user);
Assert.assertEquals(0L, userInServer.getExperience().longValue());
@@ -109,28 +122,6 @@ public class UserExperienceManagementServiceBeanTest extends ExperienceRelatedTe
Assert.assertEquals(experienceValue, rankOfUserInServer.getExperience().longValue());
}
@Test
public void testIncrementExpForUser() {
executeTestForExperienceGain(false);
}
@Test
public void testIncrementExpForUserWithDisabledExp() {
executeTestForExperienceGain(true);
}
@Test
public void testIncrementForNonExistingUser() {
long addedExperience = 15L;
long addedMessages = 1L;
AUserInAServer user = AUserInAServer.builder().userInServerId(1L).userReference(AUser.builder().id(2L).build()).build();
when(repository.findById(user.getUserInServerId())).thenReturn(Optional.empty());
mockInitialLevel();
AUserExperience userExperience = testUnit.incrementExpForUser(user, addedExperience, addedMessages);
Assert.assertEquals(addedExperience, userExperience.getExperience().longValue());
Assert.assertEquals(addedMessages, userExperience.getMessageCount().longValue());
}
@Test
public void testSaveUser() {
AUserInAServer user = AUserInAServer.builder().userInServerId(1L).userReference(AUser.builder().id(2L).build()).build();
@@ -147,28 +138,6 @@ public class UserExperienceManagementServiceBeanTest extends ExperienceRelatedTe
return startLevel;
}
private void executeTestForExperienceGain(boolean experienceGainDisabled) {
long oldExperience = 20L;
long oldMessageCount = 25L;
long addedExperience = 15L;
long addedMessages = 1L;
AUserInAServer user = AUserInAServer.builder().userInServerId(1L).userReference(AUser.builder().id(2L).build()).build();
AUserExperience experience = AUserExperience.builder().user(user).experienceGainDisabled(experienceGainDisabled).experience(oldExperience).messageCount(oldMessageCount).id(3L).build();
when(repository.findById(user.getUserInServerId())).thenReturn(Optional.of(experience));
AUserExperience userExperience = testUnit.incrementExpForUser(user, addedExperience, addedMessages);
long wantedExperience;
long wantedMessageCount;
if(experienceGainDisabled) {
wantedExperience = oldExperience;
wantedMessageCount = oldMessageCount;
} else {
wantedExperience = oldExperience + addedExperience;
wantedMessageCount = oldMessageCount + addedMessages;
}
Assert.assertEquals(wantedExperience, userExperience.getExperience().longValue());
Assert.assertEquals(wantedMessageCount, userExperience.getMessageCount().longValue());
}
private List<AUserExperience> getUserExperiences() {
AUserExperience experience = AUserExperience.builder().experience(2L).build();
AUserExperience experience2 = AUserExperience.builder().experience(2L).build();