From e53aae240453030442f66e160f9d598c7fef8817 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Fri, 31 Jan 2020 06:47:08 +0100 Subject: [PATCH 01/17] Upgrade Spring (WIP) --- sonarQuest-backend/pom.xml | 7 +- .../viadee/sonarquest/entities/Adventure.java | 5 + .../repositories/LevelRepository.java | 2 - .../repositories/TaskRepository.java | 5 - .../repositories/WorldRepository.java | 1 - .../sonarquest/services/AdventureService.java | 47 ++++---- .../sonarquest/services/LevelService.java | 12 ++- .../services/RestTemplateService.java | 2 +- .../sonarquest/services/SkillService.java | 14 ++- .../services/SpecialTaskService.java | 5 +- .../sonarquest/services/TaskService.java | 5 +- .../sonarquest/services/UserService.java | 100 ++++++++---------- .../sonarquest/services/WorldService.java | 34 +++--- .../resources/application-prod.properties | 12 +-- .../src/main/resources/application.properties | 12 +-- 15 files changed, 124 insertions(+), 139 deletions(-) diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index 6ae71b6c..3db975cb 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -26,7 +26,7 @@ org.springframework.boot spring-boot-starter-parent - 1.5.14.RELEASE + 2.2.4.RELEASE @@ -37,6 +37,11 @@ + + org.springframework.boot + spring-boot-properties-migrator + runtime + org.springframework.boot spring-boot-starter-data-jpa diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java index f1401f09..169294dc 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java @@ -17,6 +17,7 @@ import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; +import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.AdventureState; @@ -166,6 +167,10 @@ public synchronized void addUser(final User user) { users.add(user); } + public synchronized void removeUser(final User user) { + users.remove(user); + } + public World getWorld() { return world; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/LevelRepository.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/LevelRepository.java index c2af85e8..24b0d0bc 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/LevelRepository.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/LevelRepository.java @@ -6,8 +6,6 @@ public interface LevelRepository extends JpaRepository { - Level findById(Long id); - Level findFirstByMinXpIsLessThanEqualOrderByLevelNumberDesc(Long xp); Level findFirstByLevelNumberOrderByLevelNumberDesc(int levelNumber); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java index df50fa1c..5475128c 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java @@ -15,11 +15,6 @@ public interface TaskRepository extends TaskBaseRepository { @Override List findAll(); - @Override - List findAll(Iterable iterable); - - Task findById(Long id); - List findByQuestAndStatus(Quest quest, SonarQuestStatus status); List findByWorldAndStatus(World world, SonarQuestStatus status); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/WorldRepository.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/WorldRepository.java index e31b7f5e..6c44f784 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/WorldRepository.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/WorldRepository.java @@ -12,5 +12,4 @@ public interface WorldRepository extends JpaRepository { List findByActiveTrue(); - World findFirst1By(); } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java index cc729d78..4d3b5af2 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java @@ -2,8 +2,10 @@ import java.util.ArrayList; import java.util.List; +import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -16,6 +18,8 @@ import com.viadee.sonarquest.repositories.AdventureRepository; import com.viadee.sonarquest.repositories.QuestRepository; +import javax.persistence.EntityNotFoundException; + @Service public class AdventureService { @@ -81,46 +85,33 @@ public List getFreeAdventuresForUserInWorld(final World world, final /** * Removes the developer from adventure - * - * @param adventureId - * @param developerId + * + * @param adventureId The ID of the adventure to which a developer should be added + * @param userId The user ID of the developer to be added * @return adventure */ - public Adventure removeUserFromAdventure(final long adventureId, final long userId) { - Adventure adventure = adventureRepository.findOne(adventureId); + public Adventure removeUserFromAdventure(final long adventureId, final long userId) throws ResourceNotFoundException { + final Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); final User user = userService.findById(userId); - if (adventure != null && user != null) { - final List developerList = adventure.getUsers(); - if (developerList.contains(user)) { - developerList.remove(user); - } - adventure = adventureRepository.save(adventure); - } - - return adventure; - + adventure.removeUser(user); + return adventureRepository.save(adventure); } /** * Add a developer to adventure - * - * @param adventureId - * @param userId + * + * @param adventureId The ID of the adventure from which a developer should be removed + * @param userId The user ID of the developer to be removed * @return adventure */ public Adventure addUserToAdventure(final long adventureId, final long userId) { - Adventure adventure = adventureRepository.findOne(adventureId); + final Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); final User user = userService.findById(userId); - if (adventure != null && user != null) { - final List userList = adventure.getUsers(); - if (!userList.contains(user)) { - userList.add(user); - } - adventure = adventureRepository.save(adventure); + final List userList = adventure.getUsers(); + if (!userList.contains(user)) { + adventure.addUser(user); } - - return adventure; - + return adventureRepository.save(adventure); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java index 259aa2df..9a28334a 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java @@ -1,6 +1,7 @@ package com.viadee.sonarquest.services; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import com.viadee.sonarquest.entities.Level; @@ -9,16 +10,19 @@ @Service public class LevelService { - @Autowired - private LevelRepository levelRepository; + private final LevelRepository levelRepository; + + public LevelService(LevelRepository levelRepository) { + this.levelRepository = levelRepository; + } public Level getLevelByUserXp(final Long xp) { // find highest level within users XP return levelRepository.findFirstByMinXpIsLessThanEqualOrderByLevelNumberDesc(xp); } - public Level findById(final Long id) { - return levelRepository.findById(id); + public Level findById(final Long id) throws ResourceNotFoundException { + return levelRepository.findById(id).orElseThrow(ResourceNotFoundException::new); } public void createLevel(Level newLevel) { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java index 66f587cf..67d5897b 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java @@ -34,7 +34,7 @@ public RestTemplate getRestTemplate(final SonarConfig sonarConfig) { if (sonarConfig.hasHttpBasicAuth()) { LOGGER.debug("Connecting using HTTP Basic Auth"); - return restTemplateBuilder.basicAuthorization(sonarConfig.getHttpBasicAuthUsername(), + return restTemplateBuilder.basicAuthentication(sonarConfig.getHttpBasicAuthUsername(), sonarConfig.getHttpBasicAuthPassword()) .requestFactory(requestFactory()).build(); } else { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java index f28cb91c..4c110b46 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java @@ -5,6 +5,7 @@ import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import com.viadee.sonarquest.entities.Artefact; @@ -15,11 +16,14 @@ @Service public class SkillService { - @Autowired - private SkillRepository skillRepository; + private final SkillRepository skillRepository; - @Autowired - private ArtefactRepository artefactRepository; + private final ArtefactRepository artefactRepository; + + public SkillService(SkillRepository skillRepository, ArtefactRepository artefactRepository) { + this.skillRepository = skillRepository; + this.artefactRepository = artefactRepository; + } @Transactional public Skill createSkill(final Skill skillDto) { @@ -31,7 +35,7 @@ public Skill createSkill(final Skill skillDto) { } public List getSkillsForArtefact(final Artefact a) { - return artefactRepository.findOne(a.getId()).getSkills(); + return artefactRepository.findById(a.getId()).orElseThrow(ResourceNotFoundException::new).getSkills(); } @Transactional diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java index 0cd7c728..40f47376 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java @@ -3,6 +3,7 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import com.viadee.sonarquest.entities.SpecialTask; @@ -37,7 +38,7 @@ public void saveDto(final SpecialTask specialTaskDto) { } public SpecialTask updateSpecialTask(final SpecialTask taskDto) { - final SpecialTask task = specialTaskRepository.findOne(taskDto.getId()); + final SpecialTask task = specialTaskRepository.findById(taskDto.getId()).orElseThrow(ResourceNotFoundException::new); task.setTitle(taskDto.getTitle()); task.setGold(taskDto.getGold()); task.setXp(taskDto.getXp()); @@ -54,7 +55,7 @@ public List findByWorld(final World w) { } public SpecialTask findById(final Long id) { - return specialTaskRepository.findOne(id); + return specialTaskRepository.findById(id).orElseThrow(ResourceNotFoundException::new); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java index 7a4ce214..4d27a516 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java @@ -6,6 +6,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -41,8 +42,8 @@ public Task save(final Task task) { return taskRepository.save(task); } - public Task find(final Long id) { - return taskRepository.findById(id); + public Task find(final Long taskId) throws ResourceNotFoundException { + return taskRepository.findById(taskId).orElseThrow(ResourceNotFoundException::new); } public void delete(final Task task) { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java index 8f5fbe34..62e636ed 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java @@ -1,17 +1,11 @@ package com.viadee.sonarquest.services; -import java.security.Principal; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.transaction.Transactional; - +import com.viadee.sonarquest.entities.*; +import com.viadee.sonarquest.repositories.UserRepository; +import com.viadee.sonarquest.repositories.WorldRepository; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; @@ -19,58 +13,59 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; -import com.viadee.sonarquest.entities.Level; -import com.viadee.sonarquest.entities.Permission; -import com.viadee.sonarquest.entities.Role; -import com.viadee.sonarquest.entities.RoleName; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.entities.UserToWorldDto; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.UserRepository; -import com.viadee.sonarquest.repositories.WorldRepository; +import javax.transaction.Transactional; +import javax.validation.constraints.NotNull; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; @Service public class UserService implements UserDetailsService { protected static final Log LOGGER = LogFactory.getLog(UserService.class); - @Autowired - private RoleService roleService; + private final RoleService roleService; - @Autowired - private UserRepository userRepository; + private final UserRepository userRepository; - @Autowired - private WorldService worldService; + private final WorldService worldService; - @Autowired - private LevelService levelService; + private final LevelService levelService; - @Autowired - private PermissionService permissionService; + private final PermissionService permissionService; - @Autowired - private WorldRepository worldRepository; + private final WorldRepository worldRepository; + + public UserService(RoleService roleService, UserRepository userRepository, WorldService worldService, LevelService levelService, PermissionService permissionService, WorldRepository worldRepository) { + this.roleService = roleService; + this.userRepository = userRepository; + this.worldService = worldService; + this.levelService = levelService; + this.permissionService = permissionService; + this.worldRepository = worldRepository; + } @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { final User user = findByUsername(username); final Set permissions = permissionService.getAccessPermissions(user); - final List authoritys = permissions.stream() + final List authorities = permissions.stream() .map(berechtigung -> new SimpleGrantedAuthority(berechtigung.getPermission())) .collect(Collectors.toList()); return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, - true, true, true, authoritys); + true, true, true, authorities); } public User findByUsername(final String username) { return userRepository.findByUsername(username); } - private User findById(final Long id) { - return userRepository.findOne(id); + private User findById(final Long id) throws ResourceNotFoundException{ + return userRepository.findById(id).orElseThrow(ResourceNotFoundException::new); } public World updateUsersCurrentWorld(final User user, final Long worldId) { @@ -83,7 +78,7 @@ public World updateUsersCurrentWorld(final User user, final Long worldId) { @Transactional public synchronized User save(final User user) { - User toBeSaved = null; + User toBeSaved; final String username = user.getUsername(); final String mail = user.getMail(); final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); @@ -99,9 +94,9 @@ public synchronized User save(final User user) { toBeSaved.setPassword(password); toBeSaved.setRole(userRole); toBeSaved.setCurrentWorld(user.getCurrentWorld()); - toBeSaved.setGold(0l); - toBeSaved.setXp(0l); - toBeSaved.setLevel(levelService.getLevelByUserXp(0l)); + toBeSaved.setGold(0L); + toBeSaved.setXp(0L); + toBeSaved.setLevel(levelService.getLevelByUserXp(0L)); } } else { toBeSaved = findById(user.getId()); @@ -175,8 +170,9 @@ public void delete(final Long userId) { userRepository.delete(user); } - public User findById(final long userId) { - return userRepository.findOne(userId); + @NotNull + public User findById(final long userId) throws ResourceNotFoundException { + return userRepository.findById(userId).orElseThrow(ResourceNotFoundException::new); } public List findAll() { @@ -198,16 +194,17 @@ public void updateLastLogin(final String username) { save(user); } - public Boolean updateUserToWorld(List userToWorlds) { + public Boolean updateUserToWorld(List userToWorlds) throws ResourceNotFoundException { userToWorlds.forEach(userToWorld -> { - User user = userRepository.findOne(userToWorld.getUserId()); + User user = userRepository.findById(userToWorld.getUserId()).orElseThrow(ResourceNotFoundException::new); if (userToWorld.getJoined()) { - user.addWorld(worldRepository.findOne(userToWorld.getWorldId())); + World world = worldRepository.findById(userToWorld.getWorldId()).orElseThrow(ResourceNotFoundException::new); + user.addWorld(world); } else { if (user.getCurrentWorld() != null && user.getCurrentWorld().getId().equals(userToWorld.getWorldId())) { user.setCurrentWorld(null); } - user.removeWorld(worldRepository.findOne(userToWorld.getWorldId())); + user.removeWorld(worldRepository.findById(userToWorld.getWorldId()).orElseThrow(ResourceNotFoundException::new)); } userRepository.save(user); @@ -216,19 +213,6 @@ public Boolean updateUserToWorld(List userToWorlds) { return true; } - public UserRepository getUserRepository() { - return userRepository; - } - - public void setUserRepository(UserRepository userRepository) { - this.userRepository = userRepository; - } - - public User getUser(Principal principal) { - final String username = principal.getName(); - return findByUsername(username); - } - public void updateLastTavernVisit(String username, Timestamp lastVisit) { User user = userRepository.findByUsername(username); if (user != null) { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java index 37ed46d1..ed677de2 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java @@ -1,24 +1,26 @@ package com.viadee.sonarquest.services; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import com.viadee.sonarquest.entities.World; import com.viadee.sonarquest.repositories.WorldRepository; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.List; @Service public class WorldService { - @Autowired - private ExternalRessourceService externalRessourceService; + private final ExternalRessourceService externalRessourceService; - @Autowired - private WorldRepository worldRepository; + private final WorldRepository worldRepository; - @Autowired - private StandardTaskService standardTaskService; + private final StandardTaskService standardTaskService; + + public WorldService(ExternalRessourceService externalRessourceService, WorldRepository worldRepository, StandardTaskService standardTaskService) { + this.externalRessourceService = externalRessourceService; + this.worldRepository = worldRepository; + this.standardTaskService = standardTaskService; + } public List findAll() { return worldRepository.findAll(); @@ -40,22 +42,18 @@ private void saveWorldIfNotExists(final World externalWorld) { } } - public void setExternalRessourceService(final ExternalRessourceService externalRessourceService) { - this.externalRessourceService = externalRessourceService; - } - public List findAllActiveWorlds() { return worldRepository.findByActiveTrue(); } - public World findById(final Long id) { - return worldRepository.findOne(id); + public World findById(final Long id) throws ResourceNotFoundException { + return worldRepository.findById(id).orElseThrow(ResourceNotFoundException::new); } public World updateWorld(final World world) { World currentWorld = null; if (world != null) { - currentWorld = worldRepository.findOne(world.getId()); + currentWorld = worldRepository.findById(world.getId()).orElseThrow(ResourceNotFoundException::new); currentWorld.setName(world.getName()); currentWorld.setActive(world.getActive()); currentWorld.setUsequestcards(world.getUsequestcards()); diff --git a/sonarQuest-backend/src/main/resources/application-prod.properties b/sonarQuest-backend/src/main/resources/application-prod.properties index bc68c86e..6849fd45 100644 --- a/sonarQuest-backend/src/main/resources/application-prod.properties +++ b/sonarQuest-backend/src/main/resources/application-prod.properties @@ -18,12 +18,12 @@ spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # ======================================== # FLYWAY # ======================================== -flyway.enabled=true -flyway.validate-on-migrate=true -flyway.clean-on-validation-error=false -flyway.baseline-on-migrate=true -flyway.locations=db/schema,db/data -flyway.baselineOnMigrate=true +spring.flyway.enabled=true +spring.flyway.validate-on-migrate=true +spring.flyway.clean-on-validation-error=false +spring.flyway.baseline-on-migrate=true +spring.flyway.locations=db/schema,db/data +spring.flyway.baselineOnMigrate=true # ======================================== # HIBERNATE diff --git a/sonarQuest-backend/src/main/resources/application.properties b/sonarQuest-backend/src/main/resources/application.properties index bd95a877..5758080a 100644 --- a/sonarQuest-backend/src/main/resources/application.properties +++ b/sonarQuest-backend/src/main/resources/application.properties @@ -30,12 +30,12 @@ spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # ======================================== # FLYWAY # ======================================== -flyway.enabled=true -flyway.validate-on-migrate=true -flyway.clean-on-validation-error=true -flyway.baseline-on-migrate=true -flyway.locations=db/schema,db/data -flyway.baselineOnMigrate=true +spring.flyway.enabled=true +spring.flyway.validate-on-migrate=true +spring.flyway.clean-on-validation-error=true +spring.flyway.baseline-on-migrate=true +spring.flyway.locations=db/schema,db/data +spring.flyway.baselineOnMigrate=true # ======================================== # HIBERNATE From 113f9ba7af9dad01e4494170c7505cca4be21ed8 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Wed, 19 Feb 2020 16:32:29 +0100 Subject: [PATCH 02/17] Upgrade Spring (WIP) --- .../sonarquest/services/GratificationService.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/GratificationService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/GratificationService.java index 2442b7d2..9f34b6c8 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/GratificationService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/GratificationService.java @@ -29,17 +29,20 @@ @Service public class GratificationService implements UserGratification { - @Autowired - private UserService userService; + private final UserService userService; - @Autowired - private LevelService levelService; + private final LevelService levelService; - @Autowired - private StandardTaskRepository taskRepo; + private final StandardTaskRepository taskRepo; private static final Logger LOGGER = LoggerFactory.getLogger(GratificationService.class); + public GratificationService(UserService userService, LevelService levelService, StandardTaskRepository taskRepo) { + this.userService = userService; + this.levelService = levelService; + this.taskRepo = taskRepo; + } + @Override @Transactional public synchronized void rewardUserForSolvingTask(final Task task) { From c0e3b8f2b100045f8853959ceffb3fa8e3d0ab15 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Thu, 20 Feb 2020 17:21:56 +0100 Subject: [PATCH 03/17] Removed Autowired --- .../viadee/sonarquest/services/RestTemplateService.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java index ef23449f..79f7b965 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java @@ -27,8 +27,11 @@ public class RestTemplateService { private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateService.class); - @Autowired - private RestTemplateBuilder restTemplateBuilder; + private final RestTemplateBuilder restTemplateBuilder; + + public RestTemplateService(RestTemplateBuilder restTemplateBuilder) { + this.restTemplateBuilder = restTemplateBuilder; + } public RestTemplate getRestTemplate(final SonarConfig sonarConfig) { if (sonarConfig.hasHttpBasicAuth()) { From c496a880394757e8e362e78062a31d1c55a4125e Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Thu, 20 Feb 2020 18:21:01 +0100 Subject: [PATCH 04/17] Refactoring of ExternalRessourceService --- .../services/ExternalRessourceService.java | 66 ++++++++----------- 1 file changed, 29 insertions(+), 37 deletions(-) diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java index 24a5d70a..898c3633 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java @@ -1,10 +1,12 @@ package com.viadee.sonarquest.services; -import java.net.ConnectException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - +import com.viadee.sonarquest.entities.SonarConfig; +import com.viadee.sonarquest.entities.StandardTask; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.externalressources.*; +import com.viadee.sonarquest.repositories.StandardTaskRepository; +import com.viadee.sonarquest.rules.SonarQubeStatusMapper; +import com.viadee.sonarquest.rules.SonarQuestStatus; import org.apache.commons.collections4.ListUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,21 +17,10 @@ import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; -import com.viadee.sonarquest.entities.SonarConfig; -import com.viadee.sonarquest.entities.StandardTask; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.externalressources.SonarQubeApiCall; -import com.viadee.sonarquest.externalressources.SonarQubeComponentQualifier; -import com.viadee.sonarquest.externalressources.SonarQubeIssue; -import com.viadee.sonarquest.externalressources.SonarQubeIssueRessource; -import com.viadee.sonarquest.externalressources.SonarQubeIssueType; -import com.viadee.sonarquest.externalressources.SonarQubePaging; -import com.viadee.sonarquest.externalressources.SonarQubeProject; -import com.viadee.sonarquest.externalressources.SonarQubeProjectRessource; -import com.viadee.sonarquest.externalressources.SonarQubeSeverity; -import com.viadee.sonarquest.repositories.StandardTaskRepository; -import com.viadee.sonarquest.rules.SonarQubeStatusMapper; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import java.net.ConnectException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; /** * Service to access SonarQube server. @@ -37,23 +28,17 @@ @Service public class ExternalRessourceService { - @Autowired - private StandardTaskEvaluationService standardTaskEvaluationService; + private final StandardTaskEvaluationService standardTaskEvaluationService; - @Autowired - private SonarQubeStatusMapper statusMapper; + private final SonarQubeStatusMapper statusMapper; - @Autowired - private StandardTaskRepository standardTaskRepository; + private final StandardTaskRepository standardTaskRepository; - @Autowired - private SonarConfigService sonarConfigService; + private final SonarConfigService sonarConfigService; - @Autowired - private RestTemplateService restTemplateService; + private final RestTemplateService restTemplateService; - @Autowired - private GratificationService gratificationService; + private final GratificationService gratificationService; private static final Logger LOGGER = LoggerFactory.getLogger(ExternalRessourceService.class); @@ -68,6 +53,15 @@ public class ExternalRessourceService { @Value("#{'${issue.severities}'.split(',')}") private List issueSeverities; + public ExternalRessourceService(StandardTaskEvaluationService standardTaskEvaluationService, SonarQubeStatusMapper statusMapper, StandardTaskRepository standardTaskRepository, SonarConfigService sonarConfigService, RestTemplateService restTemplateService, GratificationService gratificationService) { + this.standardTaskEvaluationService = standardTaskEvaluationService; + this.statusMapper = statusMapper; + this.standardTaskRepository = standardTaskRepository; + this.sonarConfigService = sonarConfigService; + this.restTemplateService = restTemplateService; + this.gratificationService = gratificationService; + } + public List generateWorldsFromSonarQubeProjects() { return getSonarQubeProjects().stream().map(this::toWorld).collect(Collectors.toList()); } @@ -131,13 +125,12 @@ private StandardTask loadTask(final SonarQubeIssue sonarQubeIssue, final World w public List getSonarQubeProjects() { try { final SonarConfig sonarConfig = sonarConfigService.getConfig(); - final List sonarQubeProjects = new ArrayList<>(); final SonarQubeProjectRessource sonarQubeProjectRessource = getSonarQubeProjectRessourceForPageIndex( sonarConfig, 1); - sonarQubeProjects.addAll(sonarQubeProjectRessource.getSonarQubeProjects()); + final List sonarQubeProjects = new ArrayList<>(sonarQubeProjectRessource.getSonarQubeProjects()); - final Integer pagesOfExternalProjects = determinePagesOfExternalRessourcesToBeRequested( + final int pagesOfExternalProjects = determinePagesOfExternalRessourcesToBeRequested( sonarQubeProjectRessource.getPaging()); for (int i = 2; i <= pagesOfExternalProjects; i++) { sonarQubeProjects @@ -156,10 +149,9 @@ private List getIssuesForSonarQubeProject(final String projectKe issueSeverities, projectKey); final SonarConfig sonarConfig = sonarConfigService.getConfig(); final RestTemplate restTemplate = restTemplateService.getRestTemplate(sonarConfig); - final List sonarQubeIssueList = new ArrayList<>(); SonarQubeIssueRessource sonarQubeIssueRessource = getSonarQubeIssuesWithDefaultSeverities(restTemplate, sonarConfig.getSonarServerUrl(), projectKey); - sonarQubeIssueList.addAll(sonarQubeIssueRessource.getIssues()); + final List sonarQubeIssueList = new ArrayList<>(sonarQubeIssueRessource.getIssues()); LOGGER.info("Retrieved {} SonarQube issues in total for projectKey {}", sonarQubeIssueList.size(), projectKey); return sonarQubeIssueList; From a20740564001a0d3c7091df4d1f493d903d1b646 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Sat, 22 Feb 2020 21:23:08 +0100 Subject: [PATCH 05/17] Refactoring of Spring Boot 1 specific code to fit Spring Boot 2 --- sonarQuest-backend/pom.xml | 17 +- .../controllers/AdventureController.java | 102 +++---- .../controllers/ArtefactController.java | 138 ++++----- .../controllers/AvatarClassController.java | 35 ++- .../controllers/AvatarRaceController.java | 31 +- .../controllers/EventController.java | 2 +- .../controllers/LevelController.java | 15 +- .../controllers/QuestController.java | 204 +++++-------- .../controllers/SkillController.java | 61 ++-- .../controllers/SonarConfigController.java | 7 +- .../controllers/TaskController.java | 48 +-- .../controllers/UiDesignController.java | 15 +- .../controllers/WizardController.java | 20 +- .../controllers/WorldController.java | 2 +- .../sonarquest/entities/SpecialTask.java | 8 +- .../sonarquest/entities/StandardTask.java | 12 +- .../com/viadee/sonarquest/entities/Task.java | 8 +- .../externalressources/SonarQubeApiCall.java | 2 +- .../repositories/TaskRepository.java | 8 +- .../rules/SonarQubeStatusMapper.java | 14 +- ...tStatus.java => SonarQuestTaskStatus.java} | 102 +++---- .../viadee/sonarquest/rules/StatusMapper.java | 2 +- .../sonarquest/services/AdventureService.java | 23 +- .../sonarquest/services/ArtefactService.java | 282 +++++++++--------- .../sonarquest/services/EventService.java | 84 +++--- .../services/ExternalRessourceService.java | 11 +- .../sonarquest/services/LevelService.java | 10 +- .../services/ParticipationService.java | 49 +-- .../sonarquest/services/QuestService.java | 153 +++++++--- .../services/RestTemplateService.java | 20 +- .../sonarquest/services/RoleService.java | 7 +- .../sonarquest/services/SkillService.java | 35 ++- .../services/SonarConfigService.java | 11 +- .../services/SpecialTaskService.java | 26 +- .../services/StandardTaskService.java | 16 +- .../sonarquest/services/TaskService.java | 14 +- .../sonarquest/services/UiDesignService.java | 7 +- .../sonarquest/services/WizardService.java | 7 +- .../sonarquest/services/WorldService.java | 18 +- .../integration/SonarQuestApplicationIT.java | 8 +- .../rules/SonarQubeStatusMapperTest.java | 28 +- ...est.java => SonarQuestTaskStatusTest.java} | 54 ++-- .../services/ArtefactServiceTest.java | 57 ++-- .../sonarquest/services/QuestServiceTest.java | 2 +- .../services/StandardTaskServiceTest.java | 14 +- 45 files changed, 883 insertions(+), 906 deletions(-) rename sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/{SonarQuestStatus.java => SonarQuestTaskStatus.java} (79%) rename sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/{SonarQuestStatusTest.java => SonarQuestTaskStatusTest.java} (59%) diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index 3db975cb..36768e64 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -37,11 +37,6 @@ - - org.springframework.boot - spring-boot-properties-migrator - runtime - org.springframework.boot spring-boot-starter-data-jpa @@ -169,14 +164,9 @@ org.springframework.cloud spring-cloud-starter-sleuth - 1.3.3.RELEASE + 2.2.1.RELEASE - - org.springframework.cloud - spring-cloud-starter-sleuth - 1.3.3.RELEASE - net.logstash.logback logstash-logback-encoder @@ -206,6 +196,11 @@ activation 1.1.1 + + org.apache.httpcomponents + httpclient + 4.5.2 + diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AdventureController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AdventureController.java index 13d12cb9..f44a8087 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AdventureController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AdventureController.java @@ -1,23 +1,5 @@ package com.viadee.sonarquest.controllers; -import java.security.Principal; -import java.sql.Date; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -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.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - import com.viadee.sonarquest.constants.AdventureState; import com.viadee.sonarquest.entities.Adventure; import com.viadee.sonarquest.entities.Quest; @@ -30,6 +12,15 @@ import com.viadee.sonarquest.services.EventService; import com.viadee.sonarquest.services.GratificationService; import com.viadee.sonarquest.services.UserService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +import java.security.Principal; +import java.sql.Date; +import java.util.List; @RestController @RequestMapping("/adventure") @@ -37,26 +28,29 @@ public class AdventureController { private static final Logger LOGGER = LoggerFactory.getLogger(AdventureController.class); - @Autowired - private AdventureRepository adventureRepository; + private final AdventureRepository adventureRepository; - @Autowired - private QuestRepository questRepository; + private final QuestRepository questRepository; - @Autowired - private UserService userService; + private final UserService userService; - @Autowired - private WorldRepository worldRepository; + private final WorldRepository worldRepository; - @Autowired - private AdventureService adventureService; + private final AdventureService adventureService; - @Autowired - private GratificationService gratificationService; + private final GratificationService gratificationService; - @Autowired - private EventService eventService; + private final EventService eventService; + + public AdventureController(AdventureRepository adventureRepository, QuestRepository questRepository, UserService userService, WorldRepository worldRepository, AdventureService adventureService, GratificationService gratificationService, EventService eventService) { + this.adventureRepository = adventureRepository; + this.questRepository = questRepository; + this.userService = userService; + this.worldRepository = worldRepository; + this.adventureService = adventureService; + this.gratificationService = gratificationService; + this.eventService = eventService; + } @GetMapping public List getAllAdventures() { @@ -64,28 +58,28 @@ public List getAllAdventures() { } @GetMapping(value = "/world/{id}") - public List getAllAdventuresForWorld(@PathVariable(value = "id") final Long world_id) { - final World w = worldRepository.findOne(world_id); + public List getAllAdventuresForWorld(@PathVariable(value = "id") final Long worldId) { + final World w = worldRepository.findById(worldId).orElseThrow(ResourceNotFoundException::new); return adventureRepository.findByWorld(w); } @GetMapping(value = "/{id}") - public Adventure getAdventureById(@PathVariable(value = "id") final Long id) { - return adventureRepository.findOne(id); + public Adventure getAdventureById(@PathVariable(value = "id") final Long adventureId) { + return adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); } @GetMapping(value = "/getJoined/{world_id}") public List getJoinedAdventures(final Principal principal, - @PathVariable(value = "world_id") final Long world_id) { - final World w = worldRepository.findOne(world_id); + @PathVariable(value = "world_id") final Long worldId) { + final World w = worldRepository.findById(worldId).orElseThrow(ResourceNotFoundException::new); final User user = userService.findByUsername(principal.getName()); return adventureService.getJoinedAdventuresForUserInWorld(w, user); } @GetMapping(value = "/getFree/{world_id}") public List getFreeAdventures(final Principal principal, - @PathVariable(value = "world_id") final Long world_id) { - final World w = worldRepository.findOne(world_id); + @PathVariable(value = "world_id") final Long worldId) { + final World w = worldRepository.findById(worldId).orElseThrow(ResourceNotFoundException::new); final User user = userService.findByUsername(principal.getName()); return adventureService.getFreeAdventuresForUserInWorld(w, user); } @@ -100,39 +94,35 @@ public Adventure createAdventure(final Principal principal, @RequestBody final A } @PutMapping(value = "/{id}") - public Adventure updateAdventure(@PathVariable(value = "id") final Long id, @RequestBody final Adventure data) { - Adventure adventure = adventureRepository.findOne(id); - if (adventure != null) { + public Adventure updateAdventure(@PathVariable(value = "id") final Long adventureId, @RequestBody final Adventure data) { + Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); + adventure.setTitle(data.getTitle()); adventure.setGold(data.getGold()); adventure.setXp(data.getXp()); adventure.setStory(data.getStory()); adventure.setVisible(data.getVisible()); adventure = adventureRepository.save(adventure); - } + return adventure; } @DeleteMapping(value = "/{id}") - public void deleteAdventure(@PathVariable(value = "id") final Long id) { - final Adventure adventure = adventureRepository.findOne(id); - if (adventure != null) { + public void deleteAdventure(@PathVariable(value = "id") final Long adventureId) { + final Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); adventureRepository.delete(adventure); - LOGGER.info("Deleted adventure with id {}", id); - } + LOGGER.info("Deleted adventure with id {}", adventureId); } @PutMapping(value = "/{adventureId}/solveAdventure") public Adventure solveAdventure(final Principal principal, @PathVariable(value = "adventureId") final Long adventureId) { - final Adventure adventure = adventureRepository.findOne(adventureId); - if (adventure != null) { + final Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); adventure.setStatus(AdventureState.SOLVED); adventure.setEnddate(new Date(System.currentTimeMillis())); adventureRepository.save(adventure); gratificationService.rewardUsersForSolvingAdventure(adventure); eventService.createEventForSolvedAdventure(adventure, principal); - } return adventure; } @@ -140,17 +130,15 @@ public Adventure solveAdventure(final Principal principal, @ResponseStatus(HttpStatus.CREATED) public Adventure addQuest(@PathVariable(value = "adventureId") final Long adventureId, @PathVariable(value = "questId") final Long questId) { - Adventure adventure = adventureRepository.findOne(adventureId); - if (adventure != null) { - final Quest quest = questRepository.findOne(questId); + Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); + + final Quest quest = questRepository.findById(questId).orElseThrow(ResourceNotFoundException::new); quest.setAdventure(adventure); questRepository.save(quest); if (adventure.getWorld() == null) { adventure.setWorld(quest.getWorld()); adventureRepository.save(adventure); } - adventure = adventureRepository.findOne(adventureId); - } return adventure; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java index 48ad7c4f..8ae0ace9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java @@ -4,6 +4,7 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -25,93 +26,68 @@ @RequestMapping("/artefact") public class ArtefactController { - @Autowired - private ArtefactRepository artefactRepository; + private final ArtefactService artefactService; - @Autowired - private ArtefactService artefactService; + private final UserService userService; - @Autowired - private UserService userService; - - @Autowired - private WebSocketController webSocketController; + private final WebSocketController webSocketController; - @GetMapping - public List getAllArtefacts() { - return artefactService.getArtefacts(); - } + public ArtefactController(ArtefactService artefactService, UserService userService, WebSocketController webSocketController) { + this.artefactService = artefactService; + this.userService = userService; + this.webSocketController = webSocketController; + } - @GetMapping(value = "/forMarketplace/") - public List getArtefactsforMarketplace() { - return artefactService.getArtefactsForMarketplace(); - } + @GetMapping + public List getAllArtefacts() { + return artefactService.getArtefacts(); + } - @GetMapping(value = "/{id}") - public Artefact getArtefactById(@PathVariable(value = "id") final Long id) { - return artefactService.getArtefact(id); - } + @GetMapping(value = "/forMarketplace/") + public List getArtefactsforMarketplace() { + return artefactService.getArtefactsForMarketplace(); + } - @PostMapping - @ResponseStatus(HttpStatus.CREATED) - public Artefact createArtefact(final Principal principal, @RequestBody final Artefact artefact) { + @GetMapping(value = "/{artefactId}") + public Artefact getArtefactById(@PathVariable(value = "artefactId") final Long id) { + return artefactService.getArtefact(id); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Artefact createArtefact(final Principal principal, @RequestBody final Artefact artefact) { webSocketController.onCreateArtefact(artefact, principal); - return artefactService.createArtefact(artefact); - } - - @PutMapping(value = "/{id}") - public Artefact updateArtefact(final Principal principal, @PathVariable(value = "id") final Long id, @RequestBody final Artefact data) { - Artefact artefact = artefactRepository.findOne(data.getId()); - if (artefact != null) { - artefact.setDescription(data.getDescription()); - artefact.setIcon(data.getIcon()); - artefact.setMinLevel(data.getMinLevel()); - artefact.setName(data.getName()); - artefact.setPrice(data.getPrice()); - artefact.setQuantity(data.getQuantity()); - artefact.setSkills(data.getSkills()); - artefact.setUsers(data.getUsers()); - artefact.setOnMarketplace(data.isOnMarketplace()); - artefactService.updateArtefact(id, artefact); - webSocketController.onUpdateArtefact(artefact, principal); - } - return artefact; - } - - @PutMapping(value = "/{artefact_id}/buy") - public boolean buyArtefact(final Principal principal, @PathVariable(value = "artefact_id") final Long artefact_id) { - User user = userService.findByUsername(principal.getName()); - user = userService.findById(user.getId()); - final Artefact artefact = artefactRepository.findOne(artefact_id); - - return artefactService.buyArtefact(artefact, user) != null; - } - - @DeleteMapping(value = "/{id}") - public boolean deleteArtefact(final Principal principal, @PathVariable(value = "id") final Long id) { - Artefact artefact = artefactRepository.findOne(id); - if (artefact != null) { - if (artefact.getUsers().size() != 0) { - return false; - } else { - artefactRepository.delete(id); - webSocketController.onDeleteArtefact(artefact, principal); - return true; - } - } - return false; - } - - @DeleteMapping(value = "/{id}/payout") - public void payoutArtefact(@PathVariable(value = "id") final Long id) { - Artefact artefact = artefactRepository.findOne(id); - artefactService.payoutArtefact(artefact); - } - - @PutMapping(value = "/{id}/removeFromMarketplace") - public void removeArtefactFromMarketplace(@PathVariable(value = "id") final Long id) { - Artefact artefact = artefactRepository.findOne(id); - artefactService.removeArtefactFromMarketplace(artefact); - } + return artefactService.createArtefact(artefact); + } + + @PutMapping(value = "/{artefactId}") + public Artefact updateArtefact(final Principal principal, @PathVariable(value = "artefactId") final Long artefactId, @RequestBody final Artefact artefact) { + Artefact savedArtefact = artefactService.updateArtefact(artefactId, artefact); + webSocketController.onUpdateArtefact(artefact, principal); + return savedArtefact; + } + + @PutMapping(value = "/{artefactId}/buy") + public Artefact buyArtefact(final Principal principal, @PathVariable(value = "artefactId") final Long artefactId) { + final User user = userService.findByUsername(principal.getName()); + return artefactService.buyArtefact(artefactId, user); + } + + @DeleteMapping(value = "/{artefactId}") + public void deleteArtefact(final Principal principal, @PathVariable(value = "artefactId") final Long artefactId) { + final Artefact artefact = artefactService.getArtefact(artefactId); + webSocketController.onDeleteArtefact(artefact, principal); + artefactService.deleteArtefact(artefactId); + } + + @DeleteMapping(value = "/{artefactId}/payout") + public void payoutArtefact(@PathVariable(value = "artefactId") final Long artefactId) { + artefactService.payoutArtefact(artefactId); + } + + @PutMapping(value = "/{artefactId}/removeFromMarketplace") + public void removeArtefactFromMarketplace(@PathVariable(value = "artefactId") final Long artefactId) { + artefactService.removeArtefactFromMarketplace(artefactId); + } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java index 0ecc99b6..71e53c56 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java @@ -3,6 +3,7 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -21,8 +22,11 @@ @RequestMapping("/avatarClass") public class AvatarClassController { - @Autowired - private AvatarClassRepository avatarClassRepository; + private final AvatarClassRepository avatarClassRepository; + + public AvatarClassController(AvatarClassRepository avatarClassRepository) { + this.avatarClassRepository = avatarClassRepository; + } @GetMapping public List getAllAvatarClasses() { @@ -30,8 +34,8 @@ public List getAllAvatarClasses() { } @GetMapping(value = "/{id}") - public AvatarClass getAvatarClassById(@PathVariable(value = "id") final Long id) { - return avatarClassRepository.findOne(id); + public AvatarClass getAvatarClassById(@PathVariable(value = "id") final Long avatarClassId) { + return avatarClassRepository.findById(avatarClassId).orElseThrow(ResourceNotFoundException::new); } @PostMapping @@ -42,23 +46,18 @@ public AvatarClass createAvatarClass(@RequestBody final AvatarClass avatarClass) } @PutMapping(value = "/{id}") - public AvatarClass updateAvatarClass(@PathVariable(value = "id") final Long id, - @RequestBody final AvatarClass data) { - AvatarClass avatarClass = avatarClassRepository.findOne(id); - if (avatarClass != null) { - avatarClass.setName(data.getName()); - avatarClass.setSkills(data.getSkills()); - avatarClass = avatarClassRepository.save(avatarClass); - } - return avatarClass; + public AvatarClass updateAvatarClass(@PathVariable(value = "id") final Long avatarClassId, + @RequestBody final AvatarClass avatarClassInput) { + AvatarClass avatarClass = avatarClassRepository.findById(avatarClassId).orElseThrow(ResourceNotFoundException::new); + avatarClass.setName(avatarClassInput.getName()); + avatarClass.setSkills(avatarClassInput.getSkills()); + return avatarClassRepository.save(avatarClass); + } @DeleteMapping(value = "/{id}") - public void deleteAvatarClass(@PathVariable(value = "id") final Long id) { - final AvatarClass level = avatarClassRepository.findOne(id); - if (level != null) { - avatarClassRepository.delete(level); - } + public void deleteAvatarClass(@PathVariable(value = "id") final Long avatarClassId) { + avatarClassRepository.deleteById(avatarClassId); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java index 73b9c411..fcdcc5ce 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java @@ -3,6 +3,7 @@ import java.util.List; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -21,8 +22,11 @@ @RequestMapping("/avatarRace") public class AvatarRaceController { - @Autowired - private AvatarRaceRepository avatarRaceRepository; + private final AvatarRaceRepository avatarRaceRepository; + + public AvatarRaceController(AvatarRaceRepository avatarRaceRepository) { + this.avatarRaceRepository = avatarRaceRepository; + } @GetMapping public List getAllAvatarRaces() { @@ -30,8 +34,8 @@ public List getAllAvatarRaces() { } @GetMapping(value = "/{id}") - public AvatarRace getAvatarRaceById(@PathVariable(value = "id") final Long id) { - return avatarRaceRepository.findOne(id); + public AvatarRace getAvatarRaceById(@PathVariable(value = "id") final Long avatarRaceId) { + return avatarRaceRepository.findById(avatarRaceId).orElseThrow(ResourceNotFoundException::new); } @PostMapping @@ -42,21 +46,16 @@ public AvatarRace createAvatarRace(@RequestBody final AvatarRace avatarRace) { } @PutMapping(value = "/{id}") - public AvatarRace updateAvatarRace(@PathVariable(value = "id") final Long id, @RequestBody final AvatarRace data) { - AvatarRace avatarRace = avatarRaceRepository.findOne(id); - if (avatarRace != null) { - avatarRace.setName(data.getName()); - avatarRace = avatarRaceRepository.save(avatarRace); - } - return avatarRace; + public AvatarRace updateAvatarRace(@PathVariable(value = "id") final Long avatarRaceId, @RequestBody final AvatarRace avatarRaceInput) { + AvatarRace avatarRace = avatarRaceRepository.findById(avatarRaceId).orElseThrow(ResourceNotFoundException::new); + avatarRace.setName(avatarRaceInput.getName()); + return avatarRaceRepository.save(avatarRace); + } @DeleteMapping(value = "/{id}") - public void deleteAvatarRace(@PathVariable(value = "id") final Long id) { - final AvatarRace level = avatarRaceRepository.findOne(id); - if (level != null) { - avatarRaceRepository.delete(level); - } + public void deleteAvatarRace(@PathVariable(value = "id") final Long avatarRaceId) { + avatarRaceRepository.deleteById(avatarRaceId); } } \ No newline at end of file diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/EventController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/EventController.java index bf709151..f696eb00 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/EventController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/EventController.java @@ -64,7 +64,7 @@ public String something(final Principal principal, @RequestBody String message) @GetMapping(value="/checkForUnseenEvents") public boolean checkForUnseenEvents(final Principal principal) { - return eventService.checkForUnseenEvents(principal.getName()); + return eventService.areUnseenEventsAvailable(principal.getName()); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java index 8a358694..d802f7af 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java @@ -2,7 +2,7 @@ import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; +import com.viadee.sonarquest.services.LevelService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @@ -15,17 +15,20 @@ @RequestMapping("/level") public class LevelController { - @Autowired - private LevelRepository levelRepository; + private LevelService levelService; + + public LevelController(LevelService levelService) { + this.levelService = levelService; + } @GetMapping public List getAllLevels() { - return levelRepository.findAll(); + return levelService.getAllLevels(); } @GetMapping(value = "/{id}") - public Level getLevelById(@PathVariable(value = "id") final Long id) { - return levelRepository.findById(id); + public Level getLevelById(@PathVariable(value = "id") final Long levelId) { + return levelService.findById(levelId); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/QuestController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/QuestController.java index 6cfd8d08..567e6160 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/QuestController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/QuestController.java @@ -1,39 +1,21 @@ package com.viadee.sonarquest.controllers; -import java.security.Principal; -import java.sql.Date; -import java.util.List; -import java.util.stream.Collectors; - -import org.apache.commons.lang3.BooleanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -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.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - import com.viadee.sonarquest.constants.QuestState; -import com.viadee.sonarquest.entities.Adventure; import com.viadee.sonarquest.entities.Quest; import com.viadee.sonarquest.entities.Task; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.AdventureRepository; -import com.viadee.sonarquest.repositories.QuestRepository; -import com.viadee.sonarquest.repositories.WorldRepository; -import com.viadee.sonarquest.rules.SonarQuestStatus; -import com.viadee.sonarquest.services.AdventureService; -import com.viadee.sonarquest.services.GratificationService; -import com.viadee.sonarquest.services.QuestService; -import com.viadee.sonarquest.services.UserService; +import com.viadee.sonarquest.services.*; +import org.apache.commons.lang3.BooleanUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; @RestController @RequestMapping("/quest") @@ -41,148 +23,103 @@ public class QuestController { private static final Logger LOGGER = LoggerFactory.getLogger(QuestController.class); - @Autowired - private QuestRepository questRepository; + private final WorldService worldService; - @Autowired - private WorldRepository worldRepository; + private final QuestService questService; - @Autowired - private AdventureRepository adventureRepository; + private final GratificationService gratificationService; - @Autowired - private QuestService questService; + private final AdventureService adventureService; - @Autowired - private GratificationService gratificationService; + private final UserService userService; - @Autowired - private AdventureService adventureService; + private final WebSocketController webSocketController; - @Autowired - private UserService userService; - - @Autowired - private WebSocketController webSocketController; + public QuestController(WorldService worldService, QuestService questService, GratificationService gratificationService, AdventureService adventureService, UserService userService, WebSocketController webSocketController) { + this.worldService = worldService; + this.questService = questService; + this.gratificationService = gratificationService; + this.adventureService = adventureService; + this.userService = userService; + this.webSocketController = webSocketController; + } @GetMapping public List getAllQuests() { - return questRepository.findAll(); + return questService.getAllQuests(); } @GetMapping(value = "/world/{id}") - public List getAllQuestsForWorld(@PathVariable(value = "id") final Long world_id) { - final World w = worldRepository.findOne(world_id); - return questRepository.findByWorld(w); + public List getAllQuestsForWorld(@PathVariable(value = "id") final Long worldId) { + return questService.getAllQuestsForWorld(worldId); } @GetMapping(value = "/{id}") - public Quest getQuestById(@PathVariable(value = "id") final Long id) { - return questRepository.findOne(id); + public Quest getQuestById(@PathVariable(value = "id") final Long questId) { + return questService.findById(questId); } @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Quest createQuest(final Principal principal, @RequestBody final Quest questDto) { + public Quest createQuest(final Principal principal, @RequestBody final Quest quest) { final String username = principal.getName(); - final User user = userService.findByUsername(username); - questDto.setStartdate(new Date(System.currentTimeMillis())); - questDto.setStatus(QuestState.OPEN); - questDto.setCreatorName(user.getUsername()); - webSocketController.onCreateQuest(questDto, principal); - return questRepository.save(questDto); + webSocketController.onCreateQuest(quest, principal); + return questService.createQuest(quest, username); } @PutMapping(value = "/{id}") - public Quest updateQuest(final Principal principal, @PathVariable(value = "id") final Long id, @RequestBody final Quest data) { - Quest quest = questRepository.findOne(id); - if (quest != null) { - quest.setTitle(data.getTitle()); - quest.setGold(data.getGold()); - quest.setXp(data.getXp()); - quest.setStory(data.getStory()); - quest.setImage(data.getImage()); - quest.setVisible(data.getVisible()); - quest.setCreatorName(data.getCreatorName()); - quest = questRepository.save(quest); - webSocketController.onUpdateQuest(quest, principal); - } + public Quest updateQuest(final Principal principal, @PathVariable(value = "id") final Long questId, @RequestBody final Quest questInput) { + Quest quest = questService.updateQuest(questId, questInput); + webSocketController.onUpdateQuest(questInput, principal); return quest; } @DeleteMapping(value = "/{id}") - public void deleteQuest(final Principal principal, @PathVariable(value = "id") final Long id) { - final Quest quest = questRepository.findOne(id); - if (quest != null) { - final List tasks = quest.getTasks(); - tasks.forEach(task -> task.setStatus(SonarQuestStatus.OPEN)); - questRepository.delete(quest); - webSocketController.onDeleteQuest(quest, principal); - LOGGER.info("Deleted quest with id {}", id); - } + public void deleteQuest(final Principal principal, @PathVariable(value = "id") final Long questId) { + questService.deleteById(questId); + webSocketController.onDeleteQuest(questService.findById(questId), principal); + LOGGER.info("Deleted quest with id {}", questId); + } @PutMapping(value = "/{questId}/solveQuest/") - public void solveQuest(final Principal principal, @PathVariable(value = "questId") final Long questId) { - final Quest quest = questRepository.findOne(questId); - if (quest != null) { - gratificationService.rewardUsersForSolvingQuest(quest); - adventureService.updateAdventure(quest.getAdventure()); - quest.setEnddate(new Date(System.currentTimeMillis())); - quest.setStatus(QuestState.SOLVED); - questRepository.save(quest); - webSocketController.onSolveQuest(quest, principal); - } + public Quest solveQuest(final Principal principal, @PathVariable(value = "questId") final Long questId) { + Quest quest = questService.findById(questId); + gratificationService.rewardUsersForSolvingQuest(quest); + adventureService.updateAdventure(quest.getAdventure()); + Quest solvedQuest = questService.solveQuest(questId); + webSocketController.onSolveQuest(quest, principal); + return solvedQuest; } @PostMapping(value = "/{questId}/addWorld/{worldId}") @ResponseStatus(HttpStatus.CREATED) public Quest addWorld(@PathVariable(value = "questId") final Long questId, - @PathVariable(value = "worldId") final Long worldId) { - Quest quest = questRepository.findOne(questId); - if (quest != null) { - final World world = worldRepository.findOne(worldId); - quest.setWorld(world); - quest = questRepository.save(quest); - } - return quest; + @PathVariable(value = "worldId") final Long worldId) { + return questService.addQuestToWorld(questId, worldId); } @PostMapping(value = "/{questId}/addAdventure/{adventureId}") @ResponseStatus(HttpStatus.CREATED) public Quest addAdventure(@PathVariable(value = "questId") final Long questId, - @PathVariable(value = "adventureId") final Long adventureId) { - Quest quest = questRepository.findOne(questId); - if (quest != null) { - final Adventure adventure = adventureRepository.findOne(adventureId); - quest.setAdventure(adventure); - quest = questRepository.save(quest); - } - return quest; + @PathVariable(value = "adventureId") final Long adventureId) { + return questService.addQuestToAdventure(questId, adventureId); } @DeleteMapping(value = "/{questId}/deleteWorld") - public void deleteWorld(@PathVariable(value = "questId") final Long questId) { - final Quest quest = questRepository.findOne(questId); - if (quest != null) { - quest.setWorld(null); - questRepository.save(quest); - } + public void removeQuestFromWorld(@PathVariable(value = "questId") final Long questId) { + questService.removeQuestFromWorld(questId); } @DeleteMapping(value = "/{questId}/removeAdventure") - public void deleteAdventure(@PathVariable(value = "questId") final Long questId) { - final Quest quest = questRepository.findOne(questId); - if (quest != null) { - quest.setAdventure(null); - questRepository.save(quest); - } + public void removeQuestFromAdventure(@PathVariable(value = "questId") final Long questId) { + questService.removeQuestFromAdventure(questId); } @GetMapping(value = "/suggestTasksForQuestByGoldAmount/{worldId}/{goldAmount}") public List suggestTasksForQuestByGoldAmount(@PathVariable("worldId") final Long worldId, - @PathVariable("goldAmount") final Long goldAmount) { - final World world = worldRepository.findOne(worldId); + @PathVariable("goldAmount") final Long goldAmount) { + final World world = worldService.findById(worldId); List suggestedTasks = null; if (world != null) { suggestedTasks = questService.suggestTasksWithApproxGoldAmount(world, goldAmount); @@ -193,8 +130,8 @@ public List suggestTasksForQuestByGoldAmount(@PathVariable("worldId") fina @GetMapping(value = "/suggestTasksForQuestByXpAmount/{worldId}/{xpAmount}") public List suggestTasksForQuestByXpAmount(@PathVariable("worldId") final Long worldId, - @PathVariable("xpAmount") final Long xpAmount) { - final World world = worldRepository.findOne(worldId); + @PathVariable("xpAmount") final Long xpAmount) { + final World world = worldService.findById(worldId); List suggestedTasks = null; if (world != null) { suggestedTasks = questService.suggestTasksWithApproxXpAmount(world, xpAmount); @@ -205,25 +142,21 @@ public List suggestTasksForQuestByXpAmount(@PathVariable("worldId") final @GetMapping(value = "/getAllFreeForWorld/{worldId}") public List getAllFreeQuestsForWorld(@PathVariable(value = "worldId") final Long worldId) { - final World world = worldRepository.findOne(worldId); - List freeQuests = null; - if (world != null) { - freeQuests = questRepository.findByWorldAndAdventure(world, null); - freeQuests.removeIf(q -> q.getStatus() == QuestState.SOLVED); - } + List freeQuests = questService.getAllQuestsForWorld(worldId); + freeQuests.removeIf(q -> q.getStatus() == QuestState.SOLVED); return freeQuests; } @GetMapping(value = "/getAllQuestsForWorldAndUser/{worldId}") public List> getAllQuestsForWorldAndUser(final Principal principal, - @PathVariable(value = "worldId") final Long worldId) { + @PathVariable(value = "worldId") final Long worldId) { final String username = principal.getName(); final User user = userService.findByUsername(username); - final World world = worldRepository.findOne(worldId); + List> quests = null; - if (world != null && user != null) { + if (user != null) { final List> allQuestsForWorldAndDeveloper = questService - .getAllQuestsForWorldAndUser(world, user); + .getAllQuestsForWorldAndUser(worldId, user); // now filter visible quests for the dev if (user.isDeveloper()) { @@ -236,9 +169,8 @@ public List> getAllQuestsForWorldAndUser(final Principal principal, } else { LOGGER.debug("Returning getAllQuestsForWorldAndUser with ALL Quests (for gm/admin)"); quests = allQuestsForWorldAndDeveloper.stream() - .map(questlist -> questlist.stream() - .collect(Collectors.toList())) - .collect(Collectors.toList()); + .map(ArrayList::new) + .collect(Collectors.toList()); } } return quests; diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java index feea940d..352684a2 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java @@ -1,76 +1,53 @@ package com.viadee.sonarquest.controllers; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -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.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - -import com.viadee.sonarquest.entities.Artefact; import com.viadee.sonarquest.entities.Skill; -import com.viadee.sonarquest.repositories.SkillRepository; import com.viadee.sonarquest.services.ArtefactService; import com.viadee.sonarquest.services.SkillService; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.*; + +import java.util.List; @RestController @RequestMapping("/skill") public class SkillController { - @Autowired - private SkillRepository skillRepository; + private final SkillService skillService; - @Autowired - private ArtefactService artefactService; - - @Autowired - private SkillService skillService; + public SkillController(SkillService skillService) { + this.skillService = skillService; + } @GetMapping public List getAllSkills() { - return skillRepository.findAll(); + return skillService.getAllSkills(); } @GetMapping(value = "/{id}") - public Skill getSkillById(@PathVariable(value = "id") final Long id) { - return skillRepository.findOne(id); + public Skill getSkillById(@PathVariable(value = "id") final Long skillId) { + return skillService.getSkillById(skillId); } @PostMapping @ResponseStatus(HttpStatus.CREATED) - public Skill createSkill(@RequestBody final Skill skillDto) { - return skillRepository.save(skillDto); + public Skill createSkill(@RequestBody final Skill skill) { + return skillService.createSkill(skill); } @PutMapping(value = "/{id}") - public Skill updateSkill(@PathVariable(value = "id") final Long id, @RequestBody final Skill data) { - Skill skill = skillRepository.findOne(id); - if (skill != null) { - skill.setName(data.getName()); - skill.setType(data.getType()); - skill.setValue(data.getValue()); - skill = skillRepository.save(skill); - } - return skill; + public Skill updateSkill(@PathVariable(value = "id") final Long skillId, @RequestBody final Skill skill) { + return skillService.updateSkill(skillId, skill); } @DeleteMapping(value = "/{id}") - public void deleteSkill(@PathVariable(value = "id") final Long id) { - skillService.deleteSkill(skillRepository.findOne(id)); + public void deleteSkill(@PathVariable(value = "id") final Long skillId) { + skillService.deleteSkillById(skillId); } @GetMapping(value = "artefact/{artefact_id}") - public List getSkillsForArtefact(@PathVariable(value = "artefact_id") final Long id) { - final Artefact a = artefactService.getArtefact(id); - return skillService.getSkillsForArtefact(a); + public List getSkillsForArtefact(@PathVariable(value = "artefact_id") final Long artefactId) { + return skillService.getSkillsForArtefact(artefactId); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java index 01d25b5c..ed6612a7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java @@ -16,8 +16,11 @@ @RequestMapping("/sonarconfig") public class SonarConfigController { - @Autowired - private SonarConfigService sonarConfigService; + private final SonarConfigService sonarConfigService; + + public SonarConfigController(SonarConfigService sonarConfigService) { + this.sonarConfigService = sonarConfigService; + } @GetMapping public SonarConfig getSonarConfigs() { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/TaskController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/TaskController.java index 139cb0b8..a314f616 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/TaskController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/TaskController.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -24,7 +23,7 @@ import com.viadee.sonarquest.entities.Task; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; import com.viadee.sonarquest.services.AdventureService; import com.viadee.sonarquest.services.ParticipationService; import com.viadee.sonarquest.services.QuestService; @@ -38,29 +37,32 @@ @RequestMapping("/task") public class TaskController { - @Autowired - private ParticipationService participationService; + private final ParticipationService participationService; - @Autowired - private TaskService taskService; + private final TaskService taskService; - @Autowired - private StandardTaskService standardTaskService; + private final StandardTaskService standardTaskService; - @Autowired - private SpecialTaskService specialTaskService; + private final SpecialTaskService specialTaskService; - @Autowired - private WorldService worldService; + private final WorldService worldService; - @Autowired - private QuestService questService; + private final QuestService questService; - @Autowired - private AdventureService adventureService; + private final AdventureService adventureService; - @Autowired - private UserService userService; + private final UserService userService; + + public TaskController(ParticipationService participationService, TaskService taskService, StandardTaskService standardTaskService, SpecialTaskService specialTaskService, WorldService worldService, QuestService questService, AdventureService adventureService, UserService userService) { + this.participationService = participationService; + this.taskService = taskService; + this.standardTaskService = standardTaskService; + this.specialTaskService = specialTaskService; + this.worldService = worldService; + this.questService = questService; + this.adventureService = adventureService; + this.userService = userService; + } @GetMapping public List> getAllTasks() { @@ -137,9 +139,9 @@ public List getFreeTasksForWorld(@PathVariable(value = "worldId") final Lo public Task closeSpecialTask(@PathVariable(value = "taskId") final Long taskId) { Task task = taskService.find(taskId); if (task instanceof SpecialTask) { - task.setStatus(SonarQuestStatus.CLOSED); + task.setStatus(SonarQuestTaskStatus.CLOSED); task = taskService.save(task); - questService.updateQuest(task.getQuest()); + questService.closeQuestWhenAllOfItsTasksAreClosed(task.getQuest()); adventureService.updateAdventure(task.getQuest().getAdventure()); } return task; @@ -153,7 +155,7 @@ public Task addToQuest(@PathVariable(value = "taskId") final Long taskId, if (task != null) { final Quest quest = questService.findById(questId); task.setQuest(quest); - task.setStatus(SonarQuestStatus.OPEN); + task.setStatus(SonarQuestTaskStatus.OPEN); task.setStartdate(new Date(System.currentTimeMillis())); task = taskService.save(task); } @@ -165,7 +167,7 @@ public void deleteFromQuest(@PathVariable(value = "taskId") final Long taskId) { final Task task = taskService.find(taskId); if (task != null) { task.setQuest(null); - task.setStatus(SonarQuestStatus.OPEN); + task.setStatus(SonarQuestTaskStatus.OPEN); task.setStartdate(null); taskService.save(task); } @@ -193,7 +195,7 @@ public void deleteParticipation(@PathVariable(value = "taskId") final Long taskI final Task task = taskService.find(taskId); if (task != null) { task.setParticipation(null); - task.setStatus(SonarQuestStatus.OPEN); + task.setStatus(SonarQuestTaskStatus.OPEN); taskService.save(task); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java index 257c2dca..1ef8ebb9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java @@ -20,14 +20,17 @@ @RequestMapping("/ui") public class UiDesignController { - @Autowired - private UiDesignService uiDesignService; + private final UiDesignService uiDesignService; - @Autowired - private UserService userService; + private final UserService userService; - @Autowired - private UiDesignRepository uiDesignRepository; + private final UiDesignRepository uiDesignRepository; + + public UiDesignController(UiDesignService uiDesignService, UserService userService, UiDesignRepository uiDesignRepository) { + this.uiDesignService = uiDesignService; + this.userService = userService; + this.uiDesignRepository = uiDesignRepository; + } @GetMapping public UiDesign getUiDesign(final Principal principal) { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java index 0d724d6c..65f1450b 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java @@ -2,6 +2,7 @@ import java.util.Optional; +import com.viadee.sonarquest.services.WorldService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -17,18 +18,17 @@ @RequestMapping("/wizard") public class WizardController { - @Autowired - private WizardService wizardService; + private final WizardService wizardService; - @Autowired - private WorldRepository worldRepository; + private final WorldService worldService; + + public WizardController(WizardService wizardService, WorldService worldService) { + this.wizardService = wizardService; + this.worldService = worldService; + } @GetMapping(value = { "/world/{id}", "/world" }) - public WizardMessage getWizardMessageForWorld(@PathVariable(value = "id") final Optional id) { - World world = new World(); - if (id.isPresent()) { - world = worldRepository.findOne(id.get()); - } - return wizardService.getMostImportantMessageFor(world); + public WizardMessage getWizardMessageForWorld(@PathVariable(value = "id") final Long worldId) { + return wizardService.getMostImportantMessageFor(worldService.findById(worldId)); } } \ No newline at end of file diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java index 4f5b8f70..f276afe7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java @@ -83,7 +83,7 @@ public World updateBackground(@PathVariable(value = "id") final Long id, @Reques @PreAuthorize("hasAuthority('FULL_WORLD_ACCESS')") @GetMapping(value = "/generate") public List generateWorlds() { - worldService.updateWorlds(); + worldService.retrieveExternalWorlds(); return worldService.findAll(); } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java index 1ac69d3a..43d55557 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java @@ -4,7 +4,7 @@ import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @Entity @DiscriminatorValue("SPECIAL") @@ -16,9 +16,9 @@ public class SpecialTask extends Task { public SpecialTask() { } - public SpecialTask(final String title, final SonarQuestStatus status, final Long gold, final Long xp, - final Quest quest, - final String message, final World world) { + public SpecialTask(final String title, final SonarQuestTaskStatus status, final Long gold, final Long xp, + final Quest quest, + final String message, final World world) { this.setTitle(title); this.setStatus(status); this.setGold(gold); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java index f6d6c49d..5a979861 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java @@ -4,7 +4,7 @@ import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @Entity @DiscriminatorValue("STANDARD") @@ -31,11 +31,11 @@ public class StandardTask extends Task { public StandardTask() { } - public StandardTask(final String title, final SonarQuestStatus status, final Long gold, final Long xp, - final Quest quest, - final World world, final String key, - final String component, final String severity, final String type, final Integer debt, - final String issueKey, String issueRule) { + public StandardTask(final String title, final SonarQuestTaskStatus status, final Long gold, final Long xp, + final Quest quest, + final World world, final String key, + final String component, final String severity, final String type, final Integer debt, + final String issueKey, String issueRule) { setTitle(title); setStatus(status); setGold(gold); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java index e8b68d29..9a38f3d7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java @@ -17,7 +17,7 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @@ -40,7 +40,7 @@ public class Task { @Column(name = "status") @Enumerated(EnumType.STRING) - private SonarQuestStatus status; + private SonarQuestTaskStatus status; @Column(name = "gold") private Long gold; @@ -81,11 +81,11 @@ public void setTitle(final String title) { this.title = title; } - public SonarQuestStatus getStatus() { + public SonarQuestTaskStatus getStatus() { return status; } - public void setStatus(SonarQuestStatus status) { + public void setStatus(SonarQuestTaskStatus status) { this.status = status; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java index bdff7539..aab623bd 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java @@ -26,7 +26,7 @@ private void appendSearchParameter(String parameter) { * Initializes a new Ressources Object (all values reset) and sets the server URL as a basis for a new REST API * Call. * - * @param sonarQubeServerUrl + * @param sonarQubeServerUrl THe URL of the Sonar Qube server to be contacted * @return the new instance */ public static SonarQubeApiCall onServer(String sonarQubeServerUrl) { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java index 5475128c..b49fcc57 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/TaskRepository.java @@ -7,7 +7,7 @@ import com.viadee.sonarquest.entities.Quest; import com.viadee.sonarquest.entities.Task; import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @Transactional public interface TaskRepository extends TaskBaseRepository { @@ -15,9 +15,9 @@ public interface TaskRepository extends TaskBaseRepository { @Override List findAll(); - List findByQuestAndStatus(Quest quest, SonarQuestStatus status); + List findByQuestAndStatus(Quest quest, SonarQuestTaskStatus status); - List findByWorldAndStatus(World world, SonarQuestStatus status); + List findByWorldAndStatus(World world, SonarQuestTaskStatus status); - List findByWorldAndStatusAndQuestIsNull(World world, SonarQuestStatus status); + List findByWorldAndStatusAndQuestIsNull(World world, SonarQuestTaskStatus status); } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQubeStatusMapper.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQubeStatusMapper.java index ceb4d11a..bfd73650 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQubeStatusMapper.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQubeStatusMapper.java @@ -17,8 +17,8 @@ private enum SonarQubeStatus { } @Override - public SonarQuestStatus mapExternalStatus(final IssueWithStatus issueWithStatus) { - final SonarQuestStatus mappedStatus; + public SonarQuestTaskStatus mapExternalStatus(final IssueWithStatus issueWithStatus) { + final SonarQuestTaskStatus mappedStatus; final String externalStatus = issueWithStatus.getStatus(); final SonarQubeStatus sonarQubeStatus = SonarQubeStatus.valueOf(externalStatus); final String resolution = issueWithStatus.getResolution(); @@ -26,20 +26,20 @@ public SonarQuestStatus mapExternalStatus(final IssueWithStatus issueWithStatus) case OPEN: case REOPENED: case CONFIRMED: - mappedStatus = SonarQuestStatus.OPEN; + mappedStatus = SonarQuestTaskStatus.OPEN; break; case CLOSED: - mappedStatus = SonarQuestStatus.SOLVED; + mappedStatus = SonarQuestTaskStatus.SOLVED; break; case RESOLVED: if ("FALSE-POSITIVE".equals(resolution)) { - mappedStatus = SonarQuestStatus.CLOSED; + mappedStatus = SonarQuestTaskStatus.CLOSED; } else { - mappedStatus = SonarQuestStatus.OPEN; + mappedStatus = SonarQuestTaskStatus.OPEN; } break; default: - mappedStatus = SonarQuestStatus.OPEN; + mappedStatus = SonarQuestTaskStatus.OPEN; break; } return mappedStatus; diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQuestStatus.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQuestTaskStatus.java similarity index 79% rename from sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQuestStatus.java rename to sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQuestTaskStatus.java index 2ac3fcc2..50fb5b3c 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQuestStatus.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/SonarQuestTaskStatus.java @@ -1,51 +1,51 @@ -package com.viadee.sonarquest.rules; - -/** - * Represents the internal SonarQuest-Task-Status. - * - * @author MeC - * - */ -public enum SonarQuestStatus { - - //@formatter:off - OPEN("OPEN"), - CLOSED("CLOSED"), - SOLVED("SOLVED"); - //@formatter:on - - private String text; - - private SonarQuestStatus(String text) { - this.text = text; - } - - public String getText() { - return text; - } - - /** - * Gets a corresponding SonarQuestStatus from a statusText. E.g. will retrieve - * the Status Enum SOLVED when the text "SOLVED" is searched. - * - * @param statusText - * @return - * @throws IllegalArgumentException - * when no status is found, due to the game being inconsistant. All - * status must be mapped. - */ - public static SonarQuestStatus fromStatusText(String statusText) { - if (statusText == null) { - return SonarQuestStatus.OPEN; - } - for (SonarQuestStatus status : values()) { - if (status.getText().equals(statusText)) { - return status; - } - } - throw new IllegalArgumentException( - "All status of external resources/issues must be mapped but an unmapped status was found: " - + statusText); - } - -} +package com.viadee.sonarquest.rules; + +/** + * Represents the internal SonarQuest-Task-Status. + * + * @author MeC + * + */ +public enum SonarQuestTaskStatus { + + //@formatter:off + OPEN("OPEN"), + CLOSED("CLOSED"), + SOLVED("SOLVED"); + //@formatter:on + + private String text; + + private SonarQuestTaskStatus(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + /** + * Gets a corresponding SonarQuestStatus from a statusText. E.g. will retrieve + * the Status Enum SOLVED when the text "SOLVED" is searched. + * + * @param statusText + * @return + * @throws IllegalArgumentException + * when no status is found, due to the game being inconsistant. All + * status must be mapped. + */ + public static SonarQuestTaskStatus fromStatusText(String statusText) { + if (statusText == null) { + return SonarQuestTaskStatus.OPEN; + } + for (SonarQuestTaskStatus status : values()) { + if (status.getText().equals(statusText)) { + return status; + } + } + throw new IllegalArgumentException( + "All status of external resources/issues must be mapped but an unmapped status was found: " + + statusText); + } + +} diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/StatusMapper.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/StatusMapper.java index 5c6d4261..19dbba7d 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/StatusMapper.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/rules/StatusMapper.java @@ -17,6 +17,6 @@ public interface StatusMapper { * @param sourceIssue * @return */ - SonarQuestStatus mapExternalStatus(final IssueWithStatus sourceIssue); + SonarQuestTaskStatus mapExternalStatus(final IssueWithStatus sourceIssue); } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java index 4d3b5af2..24a2fcaa 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java @@ -23,17 +23,20 @@ @Service public class AdventureService { - @Autowired - private AdventureRepository adventureRepository; + private final AdventureRepository adventureRepository; - @Autowired - private QuestRepository questRepository; + private final QuestRepository questRepository; - @Autowired - private GratificationService gratificationService; + private final GratificationService gratificationService; - @Autowired - private UserService userService; + private final UserService userService; + + public AdventureService(AdventureRepository adventureRepository, QuestRepository questRepository, GratificationService gratificationService, UserService userService) { + this.adventureRepository = adventureRepository; + this.questRepository = questRepository; + this.gratificationService = gratificationService; + this.userService = userService; + } public void updateAdventures() { final List adventures = adventureRepository.findAll(); @@ -53,6 +56,10 @@ public synchronized void updateAdventure(final Adventure adventure) { } } + public Adventure findById(final Long adventureId) { + return adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); + } + /** * expects a developer object and the current world and returns the adventures * that the developer has already joined. diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ArtefactService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ArtefactService.java index 5e34a2b2..602b4833 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ArtefactService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ArtefactService.java @@ -1,150 +1,158 @@ package com.viadee.sonarquest.services; -import java.util.List; -import java.util.stream.Collectors; - -import javax.transaction.Transactional; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import com.viadee.sonarquest.entities.Artefact; import com.viadee.sonarquest.entities.Level; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.repositories.ArtefactRepository; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.List; +import java.util.stream.Collectors; @Service public class ArtefactService { - private enum PurchaseResult { - NOT_ENOUGH_GOLD, MIN_LEVEL_NOT_HIGH_ENOUGH, ITEM_SOLD_OUT, ITEM_ALREADY_BOUGHT, SUCCESS - } - - protected static final Log LOGGER = LogFactory.getLog(ArtefactService.class); - - @Autowired - private ArtefactRepository artefactRepository; - - @Autowired - private LevelService levelService; - - @Autowired - private UserService userService; - - @Autowired - private EventService eventService; - - public List getArtefacts() { - return artefactRepository.findAll(); - - } - - public List getArtefactsForMarketplace() { - List artefacts = artefactRepository.findByQuantityIsGreaterThanEqual((long) 1); - return artefacts.stream().filter(Artefact::isOnMarketplace).collect(Collectors.toList()); - } - - public Artefact getArtefact(final long id) { - return artefactRepository.findOne(id); - } - - @Transactional - public Artefact createArtefact(final Artefact artefact) { - LOGGER.info("Creating new artefact " + artefact.getName()); - Level minLevel = artefact.getMinLevel(); - Level existingLevel = levelService.findByLevel(minLevel.getLevelNumber()); - if (existingLevel != null) { - artefact.setMinLevel(existingLevel); - } else { - LOGGER.info("Artefact Level " + minLevel.getLevelNumber() + " does not exist yet - creating it..."); - levelService.createLevel(minLevel); - artefact.setMinLevel(minLevel); - } - artefact.setOnMarketplace(true); - return artefactRepository.save(artefact); - } - - @Transactional - public Artefact updateArtefact(final Long id, final Artefact artefactDto) { - LOGGER.info("Updating artefact " + id); - final Artefact artefact = artefactRepository.findOne(id); - artefact.setName(artefactDto.getName()); - artefact.setIcon(artefactDto.getIcon()); - artefact.setPrice(artefactDto.getPrice()); - artefact.setDescription(artefactDto.getDescription()); - artefact.setQuantity(artefactDto.getQuantity()); - artefact.setSkills(artefactDto.getSkills()); - artefact.setMinLevel(artefactDto.getMinLevel()); - artefact.setOnMarketplace(artefactDto.isOnMarketplace()); - return artefactRepository.save(artefact); - } - - @Transactional - public synchronized Artefact buyArtefact(Artefact artefactToBuy, final User user) { - Artefact artefact = artefactToBuy; - LOGGER.info("UserId " + user.getId() + " tries to buy artefactId " + artefactToBuy.getId()); - - final Level minLevel = artefact.getMinLevel(); - final Level devLevel = user.getLevel(); - - PurchaseResult reason = PurchaseResult.SUCCESS; - - final long gold = user.getGold() - artefact.getPrice(); - // If developer has TOO LITTLE GOLD left after the purchase, Then the purchase - // is canceled - if (gold < 0) { - reason = PurchaseResult.NOT_ENOUGH_GOLD; - } - // If the artefact is SOLD OUT, then the purchase is canceled - else if (artefact.getQuantity() < 1) { - reason = PurchaseResult.ITEM_SOLD_OUT; - } - // When the LEVEL of the developer is too low, then the purchase is canceled - else if (minLevel.getLevelNumber() > devLevel.getLevelNumber()) { - reason = PurchaseResult.MIN_LEVEL_NOT_HIGH_ENOUGH; - } else { - // If the developer has ALREADY BOUGHT the Artefact, Then the purchase is - // canceled - for (final Artefact a : user.getArtefacts()) { - if (a.equals(artefact)) { - reason = PurchaseResult.ITEM_ALREADY_BOUGHT; - break; - } - } - } - - if (reason == PurchaseResult.SUCCESS) { - user.getArtefacts().add(artefact); - user.setGold(gold); - userService.save(user); - - artefact.setQuantity(artefact.getQuantity() - 1); - artefact = artefactRepository.save(artefact); - LOGGER.info("UserId " + user.getId() + " successfully bought artefactId " + artefactToBuy.getId()); - } else { - artefact = null; - LOGGER.info(String.format("UserId %s could not buy artefactId %s, Reason %s", user.getId(), - artefactToBuy.getId(), reason)); - } - return artefact; - } - - public void payoutArtefact(Artefact artefact) { - for (User user : artefact.getUsers()) { - user.getArtefacts().remove(artefact); - user.addGold(artefact.getPrice()); - userService.save(user); - } - artefactRepository.delete(artefact); - LOGGER.info("Artefact '"+artefact.getName()+"' has been deleted by the Gamemaster.The purchase price was paid to the useres."); - } - - public void removeArtefactFromMarketplace(Artefact artefact) { - artefact.setOnMarketplace(false); - artefactRepository.save(artefact); - LOGGER.info("Artefact '"+artefact.getName()+"' has been removed form the marketplace by the Gamemaster."); + public ArtefactService(ArtefactRepository artefactRepository, LevelService levelService, UserService userService) { + this.artefactRepository = artefactRepository; + this.levelService = levelService; + this.userService = userService; + } + + private enum PurchaseResult { + NOT_ENOUGH_GOLD, MIN_LEVEL_NOT_HIGH_ENOUGH, ITEM_SOLD_OUT, ITEM_ALREADY_BOUGHT, SUCCESS + } + + protected static final Log LOGGER = LogFactory.getLog(ArtefactService.class); + + private final ArtefactRepository artefactRepository; + + private final LevelService levelService; + + private final UserService userService; + + public List getArtefacts() { + return artefactRepository.findAll(); + + } + + public List getArtefactsForMarketplace() { + List artefacts = artefactRepository.findByQuantityIsGreaterThanEqual((long) 1); + return artefacts.stream().filter(Artefact::isOnMarketplace).collect(Collectors.toList()); + } + + public Artefact getArtefact(final long artefactId) { + return artefactRepository.findById(artefactId).orElseThrow(ResourceNotFoundException::new); + } + + @Transactional + public Artefact createArtefact(final Artefact artefact) { + LOGGER.info("Creating new artefact " + artefact.getName()); + Level minLevel = artefact.getMinLevel(); + Level existingLevel = levelService.findByLevel(minLevel.getLevelNumber()); + if (existingLevel != null) { + artefact.setMinLevel(existingLevel); + } else { + LOGGER.info("Artefact Level " + minLevel.getLevelNumber() + " does not exist yet - creating it..."); + levelService.createLevel(minLevel); + artefact.setMinLevel(minLevel); + } + artefact.setOnMarketplace(true); + return artefactRepository.save(artefact); + } + + @Transactional + public Artefact updateArtefact(final Long artefactId, final Artefact artefactDto) { + LOGGER.info("Updating artefact " + artefactId); + final Artefact artefact = artefactRepository.findById(artefactId).orElseThrow(ResourceNotFoundException::new); + artefact.setName(artefactDto.getName()); + artefact.setIcon(artefactDto.getIcon()); + artefact.setPrice(artefactDto.getPrice()); + artefact.setDescription(artefactDto.getDescription()); + artefact.setQuantity(artefactDto.getQuantity()); + artefact.setSkills(artefactDto.getSkills()); + artefact.setMinLevel(artefactDto.getMinLevel()); + artefact.setUsers(artefactDto.getUsers()); + artefact.setOnMarketplace(artefactDto.isOnMarketplace()); + return artefactRepository.save(artefact); + } + + @Transactional + public synchronized Artefact buyArtefact(final Long artefactId, final User user) { + Artefact artefact = artefactRepository.findById(artefactId).orElseThrow(ResourceNotFoundException::new); + LOGGER.info("UserId " + user.getId() + " tries to buy artefactId " + artefact.getId()); + + final Level minLevel = artefact.getMinLevel(); + final Level devLevel = user.getLevel(); + + PurchaseResult reason = PurchaseResult.SUCCESS; + + final long gold = user.getGold() - artefact.getPrice(); + // If developer has TOO LITTLE GOLD left after the purchase, Then the purchase + // is canceled + if (gold < 0) { + reason = PurchaseResult.NOT_ENOUGH_GOLD; + } + // If the artefact is SOLD OUT, then the purchase is canceled + else if (artefact.getQuantity() < 1) { + reason = PurchaseResult.ITEM_SOLD_OUT; + } + // When the LEVEL of the developer is too low, then the purchase is canceled + else if (minLevel.getLevelNumber() > devLevel.getLevelNumber()) { + reason = PurchaseResult.MIN_LEVEL_NOT_HIGH_ENOUGH; + } else { + // If the developer has ALREADY BOUGHT the Artefact, Then the purchase is + // canceled + for (final Artefact a : user.getArtefacts()) { + if (a.equals(artefact)) { + reason = PurchaseResult.ITEM_ALREADY_BOUGHT; + break; + } + } + } + + if (reason == PurchaseResult.SUCCESS) { + user.getArtefacts().add(artefact); + user.setGold(gold); + userService.save(user); + + artefact.setQuantity(artefact.getQuantity() - 1); + artefact = artefactRepository.save(artefact); + LOGGER.info("UserId " + user.getId() + " successfully bought artefactId " + artefact.getId()); + } else { + artefact = null; + LOGGER.info(String.format("UserId %s could not buy artefactId %s, Reason %s", user.getId(), + artefactId, reason)); + } + return artefact; + } + + @Transactional + public void payoutArtefact(Long artefactId) { + final Artefact artefact = artefactRepository.findById(artefactId).orElseThrow(ResourceNotFoundException::new); + for (User user : artefact.getUsers()) { + user.getArtefacts().remove(artefact); + user.addGold(artefact.getPrice()); + userService.save(user); + } + artefactRepository.delete(artefact); + LOGGER.info("Artefact '" + artefact.getName() + "' has been deleted by the game master.The purchase price was paid to the users."); + } + + @Transactional + public void removeArtefactFromMarketplace(final Long artefactId) { + final Artefact artefact = artefactRepository.findById(artefactId).orElseThrow(ResourceNotFoundException::new); + artefact.setOnMarketplace(false); + artefactRepository.save(artefact); + LOGGER.info("Artefact '" + artefact.getName() + "' has been removed form the marketplace by the game master."); + } + + @Transactional + public void deleteArtefact(final Long artefactId) { + artefactRepository.deleteById(artefactId); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java index 9d6ab370..ced453f4 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java @@ -1,29 +1,18 @@ package com.viadee.sonarquest.services; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - +import com.viadee.sonarquest.constants.EventState; +import com.viadee.sonarquest.constants.EventType; +import com.viadee.sonarquest.entities.*; +import com.viadee.sonarquest.repositories.EventRepository; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.viadee.sonarquest.constants.EventState; -import com.viadee.sonarquest.constants.EventType; -import com.viadee.sonarquest.entities.Adventure; -import com.viadee.sonarquest.entities.Artefact; -import com.viadee.sonarquest.entities.Event; -import com.viadee.sonarquest.entities.EventDto; -import com.viadee.sonarquest.entities.EventUserDto; -import com.viadee.sonarquest.entities.MessageDto; -import com.viadee.sonarquest.entities.Quest; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.entities.UserDto; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.EventRepository; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; @Service public class EventService { @@ -32,18 +21,21 @@ public class EventService { private static final int EVENT_STORY_MAX_LENGTH = 255; - @Autowired - private EventRepository eventRepository; + private final EventRepository eventRepository; - @Autowired - private UserService userService; + private final UserService userService; + + public EventService(EventRepository eventRepository, UserService userService) { + this.eventRepository = eventRepository; + this.userService = userService; + } public List getAllEvents() { return eventRepository.findAll(); } public List getEventsForWorld(Principal principal) { - User user = userService.getUser(principal); + User user = userService.findByUsername(principal.getName()); World currentWorld = user.getCurrentWorld(); return eventRepository.findByWorldOrWorldIsNull(currentWorld); } @@ -72,7 +64,8 @@ private Event adventureToEvent(Adventure adventure, Principal principal, EventSt String image = StringUtils.EMPTY; World world = adventure.getWorld(); String head = StringUtils.EMPTY; - return new Event(type, title, story, state, image, world, head, userService.getUser(principal)); + User user = userService.findByUsername(principal.getName()); + return new Event(type, title, story, state, image, world, head, user); } public Event createEventForSolvedQuest(Quest quest, Principal principal) { @@ -102,13 +95,14 @@ public Event createEventForUserJoinQuest(Quest quest, Principal principal, User return checkStoryAndSave(event); } private Event questToEvent(Quest quest, Principal principal, EventState state) { - EventType type = EventType.QUEST; - String title = quest.getTitle(); - String story = quest.getStory(); - String image = quest.getImage(); - World world = quest.getWorld(); - String head = StringUtils.EMPTY; - return new Event(type, title, story, state, image, world, head, userService.getUser(principal)); + final EventType type = EventType.QUEST; + final String title = quest.getTitle(); + final String story = quest.getStory(); + final String image = quest.getImage(); + final World world = quest.getWorld(); + final String head = StringUtils.EMPTY; + final User user = userService.findByUsername(principal.getName()); + return new Event(type, title, story, state, image, world, head, user); } public Event createEventForCreatedArtefact(Artefact artefact, Principal principal) { Event event = artefactToEvent(artefact, principal, EventState.CREATED); @@ -133,15 +127,15 @@ private Event artefactToEvent(Artefact artefact, Principal principal, EventState String title = artefact.getName(); String story = artefact.getDescription(); String image = artefact.getIcon(); - return new Event(type, title, story, state, image, userService.getUser(principal)); + final User user = userService.findByUsername(principal.getName()); + return new Event(type, title, story, state, image, user); } public Event createEventForNewMessage(String message, Principal principal) { - User user = userService.getUser(principal); - EventType type = EventType.MESSAGE; - String story = message; - World world = user.getCurrentWorld(); - return checkStoryAndSave(new Event(type, story, world, user)); + final User user = userService.findByUsername(principal.getName()); + final EventType type = EventType.MESSAGE; + final World world = user.getCurrentWorld(); + return checkStoryAndSave(new Event(type, message, world, user)); } public Event createEventForNewMessage(MessageDto messageDto) { @@ -196,10 +190,8 @@ public EventUserDto principalToEvents(Principal principal) { } public Boolean hasUserDto(List userDtos, UserDto userDto) { - Iterator i = userDtos.iterator(); - while (i.hasNext()) { - UserDto dto = i.next(); + for (UserDto dto : userDtos) { if (dto.getId().equals(userDto.getId())) { return true; } @@ -231,17 +223,11 @@ public List get3LatestEvents() { return eventRepository.findFirst3ByOrderByTimestampDesc(); } - public List get10LatestEvents() { - return eventRepository.findFirst10ByOrderByTimestampDesc(); - } - - public boolean checkForUnseenEvents(String username) { + public boolean areUnseenEventsAvailable(String username) { User user = userService.findByUsername(username); if (user.getLastTavernVisit() != null) { List unseenEvents = eventRepository.findAllWithTimestampAfter(user.getLastTavernVisit()); - if(!unseenEvents.isEmpty()) { - return true; - } + return !unseenEvents.isEmpty(); } return false; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java index 898c3633..d9692c42 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java @@ -6,11 +6,10 @@ import com.viadee.sonarquest.externalressources.*; import com.viadee.sonarquest.repositories.StandardTaskRepository; import com.viadee.sonarquest.rules.SonarQubeStatusMapper; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; import org.apache.commons.collections4.ListUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @@ -99,12 +98,12 @@ private StandardTask toTask(final SonarQubeIssue sonarQubeIssue, final World wor final Long gold = standardTaskEvaluationService.evaluateGoldAmount(sonarQubeIssue.getDebt()); final Long xp = standardTaskEvaluationService.evaluateXP(sonarQubeIssue.getSeverity()); final Integer debt = Math.toIntExact(standardTaskEvaluationService.getDebt(sonarQubeIssue.getDebt())); - final SonarQuestStatus status = statusMapper.mapExternalStatus(sonarQubeIssue); + final SonarQuestTaskStatus status = statusMapper.mapExternalStatus(sonarQubeIssue); return loadTask(sonarQubeIssue, world, gold, xp, debt, status); } private StandardTask loadTask(final SonarQubeIssue sonarQubeIssue, final World world, final Long gold, - final Long xp, final Integer debt, final SonarQuestStatus newStatus) { + final Long xp, final Integer debt, final SonarQuestTaskStatus newStatus) { StandardTask savedTask = standardTaskRepository.findByKey(sonarQubeIssue.getKey()); if (savedTask == null) { // new issue from SonarQube: Create new task @@ -113,8 +112,8 @@ private StandardTask loadTask(final SonarQubeIssue sonarQubeIssue, final World w sonarQubeIssue.getType(), debt, sonarQubeIssue.getKey(),sonarQubeIssue.getRule()); } else { - final SonarQuestStatus lastStatus = savedTask.getStatus(); - if (newStatus == SonarQuestStatus.SOLVED && lastStatus == SonarQuestStatus.OPEN) { + final SonarQuestTaskStatus lastStatus = savedTask.getStatus(); + if (newStatus == SonarQuestTaskStatus.SOLVED && lastStatus == SonarQuestTaskStatus.OPEN) { gratificationService.rewardUserForSolvingTask(savedTask); } savedTask.setStatus(newStatus); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java index 9a28334a..7838b5a2 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/LevelService.java @@ -1,11 +1,11 @@ package com.viadee.sonarquest.services; -import org.springframework.beans.factory.annotation.Autowired; +import com.viadee.sonarquest.entities.Level; +import com.viadee.sonarquest.repositories.LevelRepository; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; -import com.viadee.sonarquest.entities.Level; -import com.viadee.sonarquest.repositories.LevelRepository; +import java.util.List; @Service public class LevelService { @@ -16,6 +16,10 @@ public LevelService(LevelRepository levelRepository) { this.levelRepository = levelRepository; } + public List getAllLevels() { + return levelRepository.findAll(); + } + public Level getLevelByUserXp(final Long xp) { // find highest level within users XP return levelRepository.findFirstByMinXpIsLessThanEqualOrderByLevelNumberDesc(xp); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java index 95dd65f0..0e943954 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java @@ -1,48 +1,50 @@ package com.viadee.sonarquest.services; -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - import com.viadee.sonarquest.controllers.WebSocketController; import com.viadee.sonarquest.entities.Participation; import com.viadee.sonarquest.entities.Quest; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.repositories.ParticipationRepository; import com.viadee.sonarquest.repositories.QuestRepository; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; @Service public class ParticipationService { - @Autowired - private QuestRepository questRepository; + private final ParticipationRepository participationRepository; - @Autowired - private ParticipationRepository participationRepository; + private final UserService userService; - @Autowired - private UserService userService; + private final QuestService questService; - @Autowired - private WebSocketController webSocketController; + private final WebSocketController webSocketController; + public ParticipationService(ParticipationRepository participationRepository, UserService userService, QuestService questService, WebSocketController webSocketController) { + this.participationRepository = participationRepository; + this.userService = userService; + this.questService = questService; + this.webSocketController = webSocketController; + } + + @Transactional public Participation findParticipationByQuestIdAndUserId(final Long questId, final Long userId) { - final Quest quest = questRepository.findOne(questId); + final Quest quest = questService.findById(questId); final User user = userService.findById(userId); - if (quest != null && user != null) { - return participationRepository.findByQuestAndUser(quest, user); - } - return null; + return participationRepository.findByQuestAndUser(quest, user); } + @Transactional public List findParticipationByQuestId(final Long questId) { - final Quest foundQuest = questRepository.findOne(questId); + final Quest foundQuest = questService.findById(questId); return participationRepository.findByQuest(foundQuest); } + @Transactional public List findParticipationByUser(final User user) { List participations = new ArrayList<>(); if (user != null) { @@ -51,8 +53,9 @@ public List findParticipationByUser(final User user) { return participations; } - public Participation createParticipation(Principal principal, Long questid) { - final Quest foundQuest = questRepository.findOne(questid); + @Transactional + public Participation createParticipation(Principal principal, Long questId) { + final Quest foundQuest = questService.findById(questId); final String username = principal.getName(); final User user = userService.findByUsername(username); final Participation foundParticipation = participationRepository.findByQuestAndUser(foundQuest, user); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/QuestService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/QuestService.java index c5448bb3..ea886bc1 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/QuestService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/QuestService.java @@ -1,50 +1,59 @@ package com.viadee.sonarquest.services; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - import com.viadee.sonarquest.constants.QuestState; -import com.viadee.sonarquest.entities.Participation; -import com.viadee.sonarquest.entities.Quest; -import com.viadee.sonarquest.entities.Task; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.entities.*; import com.viadee.sonarquest.interfaces.QuestSuggestion; import com.viadee.sonarquest.repositories.ParticipationRepository; import com.viadee.sonarquest.repositories.QuestRepository; import com.viadee.sonarquest.repositories.TaskRepository; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.sql.Date; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; @Service public class QuestService implements QuestSuggestion { - @Autowired - private QuestRepository questRepository; + private final QuestRepository questRepository; - @Autowired - private TaskRepository taskRepository; + private final TaskRepository taskRepository; - @Autowired - private GratificationService gratificationService; + private final GratificationService gratificationService; - @Autowired - private ParticipationRepository participationRepository; - - final Random random = new Random(); + private final ParticipationRepository participationRepository; + + private WorldService worldService; + + private UserService userService; + + private AdventureService adventureService; + private final Random random = new Random(); + + + public QuestService(QuestRepository questRepository, TaskRepository taskRepository, GratificationService gratificationService, ParticipationRepository participationRepository, WorldService worldService, UserService userService, AdventureService adventureService) { + this.questRepository = questRepository; + this.taskRepository = taskRepository; + this.gratificationService = gratificationService; + this.participationRepository = participationRepository; + this.worldService = worldService; + this.userService = userService; + this.adventureService = adventureService; + } + public Quest findById(final Long questId) { - return questRepository.findOne(questId); + return questRepository.findById(questId).orElseThrow(ResourceNotFoundException::new); } @Override public List suggestTasksWithApproxGoldAmount(final World world, final Long goldApprox) { - final List freeTasks = taskRepository.findByWorldAndStatus(world, SonarQuestStatus.OPEN); + final List freeTasks = taskRepository.findByWorldAndStatus(world, SonarQuestTaskStatus.OPEN); final List suggestedTasks = new ArrayList<>(); while ((totalGoldAmountOfTaskList(suggestedTasks) < goldApprox) && (!freeTasks.isEmpty())) { final Task selectedTask = selectRandomTask(freeTasks); @@ -56,7 +65,7 @@ public List suggestTasksWithApproxGoldAmount(final World world, final Long @Override public List suggestTasksWithApproxXpAmount(final World world, final Long xpApprox) { - final List freeTasks = taskRepository.findByWorldAndStatus(world, SonarQuestStatus.OPEN); + final List freeTasks = taskRepository.findByWorldAndStatus(world, SonarQuestTaskStatus.OPEN); final List suggestedTasks = new ArrayList<>(); while ((totalXpAmountOfTaskList(suggestedTasks) < xpApprox) && (!freeTasks.isEmpty())) { final Task selectedTask = selectRandomTask(freeTasks); @@ -68,7 +77,7 @@ public List suggestTasksWithApproxXpAmount(final World world, final Long x private Task selectRandomTask(final List taskList) { - final Integer randomIndex = random.nextInt(taskList.size()); + final int randomIndex = random.nextInt(taskList.size()); return taskList.get(randomIndex); } @@ -80,16 +89,17 @@ private Long totalXpAmountOfTaskList(final List taskList) { return taskList.stream().mapToLong(Task::getXp).sum(); } - public void updateQuests() { + @Transactional + public void checkAllQuestsAndCloseItWhenAllOfItsTasksAreClosed() { final List quests = questRepository.findAll(); - quests.forEach(this::updateQuest); + quests.forEach(this::closeQuestWhenAllOfItsTasksAreClosed); } @Transactional // Quest updates are not to be mixed - public synchronized void updateQuest(final Quest quest) { + public synchronized void closeQuestWhenAllOfItsTasksAreClosed(final Quest quest) { final List tasks = quest.getTasks(); - final List solvedTasks = taskRepository.findByQuestAndStatus(quest, SonarQuestStatus.SOLVED); - final List closedTasks = taskRepository.findByQuestAndStatus(quest, SonarQuestStatus.CLOSED); + final List solvedTasks = taskRepository.findByQuestAndStatus(quest, SonarQuestTaskStatus.SOLVED); + final List closedTasks = taskRepository.findByQuestAndStatus(quest, SonarQuestTaskStatus.CLOSED); if (tasks.size() == (solvedTasks.size() + closedTasks.size())) { gratificationService.rewardUsersForSolvingQuest(quest); quest.setStatus(QuestState.SOLVED); @@ -97,17 +107,82 @@ public synchronized void updateQuest(final Quest quest) { } } - public List> getAllQuestsForWorldAndUser(final World world, final User developer) { - final List participations = participationRepository.findByUser(developer); + @Transactional + public List> getAllQuestsForWorldAndUser(final Long worldId, final User user) { + final World world = worldService.findById(worldId); + final List participations = participationRepository.findByUser(user); final List participatedQuests = participations.stream().map(Participation::getQuest) .filter(quest -> quest.getWorld().equals(world)).collect(Collectors.toList()); final List allQuestsForWorld = questRepository.findByWorld(world); final List> result = new ArrayList<>(); - final List freeQuests = allQuestsForWorld; - freeQuests.removeAll(participatedQuests); + allQuestsForWorld.removeAll(participatedQuests); result.add(participatedQuests); - result.add(freeQuests); + result.add(allQuestsForWorld); return result; } + @Transactional + public List getAllQuests() { + return questRepository.findAll(); + } + + public List getAllQuestsForWorld(final Long worldId) { + final World world = worldService.findById(worldId); + return questRepository.findByWorld(world); + } + + public Quest createQuest(Quest quest, String username) { + final User user = userService.findByUsername(username); + quest.setStartdate(new Date(System.currentTimeMillis())); + quest.setStatus(QuestState.OPEN); + quest.setCreatorName(user.getUsername()); + return questRepository.save(quest); + } + + public Quest updateQuest(Long questId, Quest questInput) { + Quest quest = questRepository.findById(questId).orElseThrow(ResourceNotFoundException::new); + quest.setTitle(questInput.getTitle()); + quest.setGold(questInput.getGold()); + quest.setXp(questInput.getXp()); + quest.setStory(questInput.getStory()); + quest.setImage(questInput.getImage()); + quest.setVisible(questInput.getVisible()); + quest.setCreatorName(questInput.getCreatorName()); + return questRepository.save(quest); + } + + public void deleteById(Long questId) { + questRepository.deleteById(questId); + } + + public Quest solveQuest(Long questId) { + Quest quest = questRepository.findById(questId).orElseThrow(ResourceNotFoundException::new); + quest.setEnddate(new Date(System.currentTimeMillis())); + quest.setStatus(QuestState.SOLVED); + return questRepository.save(quest); + } + + public Quest addQuestToWorld(final Long questId, final Long worldId) { + final Quest quest = findById(questId); + final World world = worldService.findById(worldId); + quest.setWorld(world); + return questRepository.save(quest); + } + + public void removeQuestFromWorld(final Long questId) { + Quest quest = findById(questId); + quest.setWorld(null); + } + + public Quest addQuestToAdventure(final Long questId, final Long adventureId) { + final Quest quest = findById(questId); + final Adventure adventure = adventureService.findById(adventureId); + quest.setAdventure(adventure); + return questRepository.save(quest); + } + + public void removeQuestFromAdventure(final Long questId) { + Quest quest = findById(questId); + quest.setAdventure(null); + } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java index 79f7b965..4c273904 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RestTemplateService.java @@ -1,26 +1,24 @@ package com.viadee.sonarquest.services; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; - +import com.viadee.sonarquest.entities.SonarConfig; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; -import com.viadee.sonarquest.entities.SonarConfig; +import javax.net.ssl.SSLContext; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; +import java.util.function.Supplier; @Service public class RestTemplateService { @@ -45,7 +43,7 @@ public RestTemplate getRestTemplate(final SonarConfig sonarConfig) { } } - private ClientHttpRequestFactory requestFactory() { + private Supplier requestFactory() { final TrustStrategy acceptingTrustStrategy = (final X509Certificate[] chain, final String authType) -> true; final SSLContext sslContext = createSslContext(acceptingTrustStrategy); @@ -57,7 +55,7 @@ private ClientHttpRequestFactory requestFactory() { final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); - return requestFactory; + return () -> requestFactory; } private SSLContext createSslContext(final TrustStrategy acceptingTrustStrategy) { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java index 79fdb7fd..ad099ea7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java @@ -12,8 +12,11 @@ @Service public class RoleService { - @Autowired - private RoleRepository roleRepository; + private final RoleRepository roleRepository; + + public RoleService(RoleRepository roleRepository) { + this.roleRepository = roleRepository; + } public Role findByName(final RoleName name) { return roleRepository.findByName(name); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java index 4c110b46..f278c803 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java @@ -18,11 +18,11 @@ public class SkillService { private final SkillRepository skillRepository; - private final ArtefactRepository artefactRepository; + private final ArtefactService artefactService; - public SkillService(SkillRepository skillRepository, ArtefactRepository artefactRepository) { + public SkillService(SkillRepository skillRepository, ArtefactService artefactService) { this.skillRepository = skillRepository; - this.artefactRepository = artefactRepository; + this.artefactService = artefactService; } @Transactional @@ -34,15 +34,32 @@ public Skill createSkill(final Skill skillDto) { return skillRepository.save(skill); } - public List getSkillsForArtefact(final Artefact a) { - return artefactRepository.findById(a.getId()).orElseThrow(ResourceNotFoundException::new).getSkills(); + @Transactional + public List getSkillsForArtefact(final Long artefactId) { + return artefactService.getArtefact(artefactId).getSkills(); + } + + @Transactional + public void deleteSkillById(final Long skillId) { + skillRepository.deleteById(skillId); + } + + @Transactional + public List getAllSkills() { + return skillRepository.findAll(); } @Transactional - public void deleteSkill(final Skill skill) { - if (skill != null) { - skillRepository.delete(skill); - } + public Skill getSkillById(final Long skillId) { + return skillRepository.findById(skillId).orElseThrow(ResourceNotFoundException::new); } + @Transactional + public Skill updateSkill(final Long skillId, final Skill newSkill) { + Skill skill = skillRepository.findById(skillId).orElseThrow(ResourceNotFoundException::new); + skill.setName(newSkill.getName()); + skill.setType(newSkill.getType()); + skill.setValue(newSkill.getValue()); + return skillRepository.save(skill); + } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java index d4c92a23..83b5471f 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java @@ -16,11 +16,14 @@ public class SonarConfigService { private static final Logger LOGGER = LoggerFactory.getLogger(SonarConfigService.class); - @Autowired - private SonarConfigRepository sonarConfigRepository; + private final SonarConfigRepository sonarConfigRepository; - @Autowired - private RestTemplateService restTemplateService; + private final RestTemplateService restTemplateService; + + public SonarConfigService(SonarConfigRepository sonarConfigRepository, RestTemplateService restTemplateService) { + this.sonarConfigRepository = sonarConfigRepository; + this.restTemplateService = restTemplateService; + } public SonarConfig getConfig() { return sonarConfigRepository.findFirstBy(); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java index 8d81541b..82a9b018 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java @@ -1,32 +1,34 @@ package com.viadee.sonarquest.services; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.rest.webmvc.ResourceNotFoundException; -import org.springframework.stereotype.Service; - import com.viadee.sonarquest.entities.SpecialTask; import com.viadee.sonarquest.entities.World; import com.viadee.sonarquest.repositories.SpecialTaskRepository; import com.viadee.sonarquest.repositories.WorldRepository; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.rest.webmvc.ResourceNotFoundException; +import org.springframework.stereotype.Service; + +import java.util.List; @Service public class SpecialTaskService { - @Autowired - private SpecialTaskRepository specialTaskRepository; + private final SpecialTaskRepository specialTaskRepository; + + private final WorldRepository worldRepository; - @Autowired - private WorldRepository worldRepository; + public SpecialTaskService(SpecialTaskRepository specialTaskRepository, WorldRepository worldRepository) { + this.specialTaskRepository = specialTaskRepository; + this.worldRepository = worldRepository; + } public void saveDto(final SpecialTask specialTaskDto) { final World world = worldRepository.findByProject(specialTaskDto.getWorld().getProject()); final SpecialTask sp = new SpecialTask( specialTaskDto.getTitle(), - SonarQuestStatus.OPEN, + SonarQuestTaskStatus.OPEN, specialTaskDto.getGold(), specialTaskDto.getXp(), specialTaskDto.getQuest(), diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/StandardTaskService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/StandardTaskService.java index a2a54f49..704a8ab3 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/StandardTaskService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/StandardTaskService.java @@ -18,7 +18,7 @@ import com.viadee.sonarquest.externalressources.SonarQubeSeverity; import com.viadee.sonarquest.repositories.StandardTaskRepository; import com.viadee.sonarquest.repositories.WorldRepository; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @Service public class StandardTaskService { @@ -49,28 +49,28 @@ public void updateStandardTasks(final World world) { final List externalStandardTasks = externalRessourceService .generateStandardTasksFromSonarQubeIssuesForWorld(world); externalStandardTasks.forEach(this::updateStandardTask); - questService.updateQuests(); + questService.checkAllQuestsAndCloseItWhenAllOfItsTasksAreClosed(); adventureService.updateAdventures(); } @Transactional public StandardTask updateStandardTask(final StandardTask task) { - final SonarQuestStatus oldStatus = getLastState(task); - final SonarQuestStatus newStatus = task.getStatus(); - if (newStatus == SonarQuestStatus.SOLVED && oldStatus == SonarQuestStatus.OPEN) { + final SonarQuestTaskStatus oldStatus = getLastState(task); + final SonarQuestTaskStatus newStatus = task.getStatus(); + if (newStatus == SonarQuestTaskStatus.SOLVED && oldStatus == SonarQuestTaskStatus.OPEN) { gratificationService.rewardUserForSolvingTask(task); } task.setStatus(newStatus); return standardTaskRepository.saveAndFlush(task); } - protected SonarQuestStatus getLastState(final StandardTask task) { + protected SonarQuestTaskStatus getLastState(final StandardTask task) { final SqlParameterSource params = new MapSqlParameterSource().addValue("id", task.getId()); final String sql = "SELECT Status FROM Task WHERE id = :id"; final RowMapper rowmapper = new SingleColumnRowMapper<>(); final List statusTexte = template.query(sql, params, rowmapper); final String statusText = statusTexte.isEmpty() ? null : statusTexte.get(0); - return SonarQuestStatus.fromStatusText(statusText); + return SonarQuestTaskStatus.fromStatusText(statusText); } public void setExternalRessourceService(final ExternalRessourceService externalRessourceService) { @@ -82,7 +82,7 @@ public void save(final StandardTask standardTask) { final World world = worldRepository.findByProject(standardTask.getWorld().getProject()); final StandardTask st = new StandardTask( standardTask.getTitle(), - SonarQuestStatus.OPEN, + SonarQuestTaskStatus.OPEN, standardTask.getGold(), standardTask.getXp(), standardTask.getQuest(), diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java index 4d27a516..5d85b1c9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/TaskService.java @@ -15,7 +15,7 @@ import com.viadee.sonarquest.entities.Task; import com.viadee.sonarquest.entities.World; import com.viadee.sonarquest.repositories.TaskRepository; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @Service public class TaskService { @@ -35,7 +35,7 @@ public class TaskService { private AdventureService adventureService; public List getFreeTasksForWorld(final World world) { - return taskRepository.findByWorldAndStatusAndQuestIsNull(world, SonarQuestStatus.OPEN); + return taskRepository.findByWorldAndStatusAndQuestIsNull(world, SonarQuestTaskStatus.OPEN); } public Task save(final Task task) { @@ -56,12 +56,12 @@ public List findAll() { @Transactional public void solveTaskManually(final Task task) { - if (task != null && task.getStatus() != SonarQuestStatus.SOLVED) { - task.setStatus(SonarQuestStatus.SOLVED); + if (task != null && task.getStatus() != SonarQuestTaskStatus.SOLVED) { + task.setStatus(SonarQuestTaskStatus.SOLVED); task.setEnddate(new Date(System.currentTimeMillis())); save(task); gratificationService.rewardUserForSolvingTask(task); - questService.updateQuest(task.getQuest()); + questService.closeQuestWhenAllOfItsTasksAreClosed(task.getQuest()); adventureService.updateAdventure(task.getQuest().getAdventure()); } } @@ -73,11 +73,11 @@ public void solveAllTasksInQuest(Quest quest) { List tasks = quest.getTasks(); for (Task task : tasks) { gratificationService.rewardUserForSolvingTask(task); - task.setStatus(SonarQuestStatus.SOLVED); + task.setStatus(SonarQuestTaskStatus.SOLVED); task.setEnddate(new Date(System.currentTimeMillis())); save(task); } - questService.updateQuest(quest); + questService.closeQuestWhenAllOfItsTasksAreClosed(quest); adventureService.updateAdventure(quest.getAdventure()); } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java index 41b94b05..91576031 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java @@ -11,8 +11,11 @@ @Service public class UiDesignService { - @Autowired - private UiDesignRepository uiDesignRepository; + private final UiDesignRepository uiDesignRepository; + + public UiDesignService(UiDesignRepository uiDesignRepository) { + this.uiDesignRepository = uiDesignRepository; + } private UiDesign createUiDesign(final User user, final UiDesignName name) { final UiDesign ui = new UiDesign(); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java index 6e762f71..e013903b 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java @@ -12,8 +12,11 @@ @Service public class WizardService { - @Autowired - private WorldService worldService; + private final WorldService worldService; + + public WizardService(WorldService worldService) { + this.worldService = worldService; + } /** * The WizardState keeps solution message key and message key together. These diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java index ed677de2..0df770a2 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java @@ -30,7 +30,7 @@ public World save(final World world) { return worldRepository.save(world); } - public void updateWorlds() { + public void retrieveExternalWorlds() { final List externalWorlds = externalRessourceService.generateWorldsFromSonarQubeProjects(); externalWorlds.forEach(this::saveWorldIfNotExists); } @@ -51,15 +51,13 @@ public World findById(final Long id) throws ResourceNotFoundException { } public World updateWorld(final World world) { - World currentWorld = null; - if (world != null) { - currentWorld = worldRepository.findById(world.getId()).orElseThrow(ResourceNotFoundException::new); - currentWorld.setName(world.getName()); - currentWorld.setActive(world.getActive()); - currentWorld.setUsequestcards(world.getUsequestcards()); - currentWorld = worldRepository.save(currentWorld); - standardTaskService.updateStandardTasks(currentWorld); - } + World currentWorld; + currentWorld = worldRepository.findById(world.getId()).orElseThrow(ResourceNotFoundException::new); + currentWorld.setName(world.getName()); + currentWorld.setActive(world.getActive()); + currentWorld.setUsequestcards(world.getUsequestcards()); + currentWorld = worldRepository.save(currentWorld); + standardTaskService.updateStandardTasks(currentWorld); return currentWorld; } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java index 07b5d49e..e628caba 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java @@ -30,7 +30,7 @@ import com.viadee.sonarquest.repositories.StandardTaskRepository; import com.viadee.sonarquest.repositories.TaskRepository; import com.viadee.sonarquest.repositories.WorldRepository; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; import com.viadee.sonarquest.services.LevelService; import com.viadee.sonarquest.services.RoleService; import com.viadee.sonarquest.services.StandardTaskService; @@ -131,7 +131,7 @@ public void developersCanParticipateInQuestsAndIssues() { assertEquals("user not properly mapped to task participation", USERNAME, taskParticipation.getUser().getUsername()); - coerceDeathOutOfRetirementTask.setStatus(SonarQuestStatus.SOLVED); + coerceDeathOutOfRetirementTask.setStatus(SonarQuestTaskStatus.SOLVED); standardTaskService.updateStandardTask(coerceDeathOutOfRetirementTask); rinceWind = userService.findByUsername(USERNAME); @@ -156,7 +156,7 @@ private StandardTask createTask(final World discWorld, final Quest magicQuest) { task.setTitle("coercing Death out of his impromptu retirement"); task.setWorld(discWorld); task.setQuest(magicQuest); - task.setStatus(SonarQuestStatus.OPEN); + task.setStatus(SonarQuestTaskStatus.OPEN); return taskRepository.save(task); } @@ -203,7 +203,7 @@ public void caseSensitiveTaskKeys() { task.setTitle("coercing Death out of his impromptu retirement"); task.setWorld(discWorld); task.setQuest(magicQuest); - task.setStatus(SonarQuestStatus.OPEN); + task.setStatus(SonarQuestTaskStatus.OPEN); taskRepository.save(task); assertNull("unexpected Task", standardTaskRepository.findByKey("AWc3A2KEoXX3DuVBrVTC")); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java index 2a70607c..c5110498 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java @@ -9,10 +9,6 @@ import org.mockito.InjectMocks; import org.mockito.runners.MockitoJUnitRunner; -import com.viadee.sonarquest.rules.IssueWithStatus; -import com.viadee.sonarquest.rules.SonarQubeStatusMapper; -import com.viadee.sonarquest.rules.SonarQuestStatus; - @RunWith(MockitoJUnitRunner.class) public class SonarQubeStatusMapperTest { @@ -22,44 +18,44 @@ public class SonarQubeStatusMapperTest { @Test public void testMapExternalStatus_Open() throws Exception { IssueWithStatus issueWithStatus = issue("OPEN"); - SonarQuestStatus sonarQuestStatus = mapper.mapExternalStatus(issueWithStatus); - assertSame(SonarQuestStatus.OPEN, sonarQuestStatus); + SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); + assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); } @Test public void testMapExternalStatus_Reopen() throws Exception { IssueWithStatus issueWithStatus = issue("REOPENED"); - SonarQuestStatus sonarQuestStatus = mapper.mapExternalStatus(issueWithStatus); - assertSame(SonarQuestStatus.OPEN, sonarQuestStatus); + SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); + assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); } @Test public void testMapExternalStatus_Confirmed() throws Exception { IssueWithStatus issueWithStatus = issue("CONFIRMED"); - SonarQuestStatus sonarQuestStatus = mapper.mapExternalStatus(issueWithStatus); - assertSame(SonarQuestStatus.OPEN, sonarQuestStatus); + SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); + assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); } @Test public void testMapExternalStatus_Closed() throws Exception { IssueWithStatus issueWithStatus = issue("CLOSED"); - SonarQuestStatus sonarQuestStatus = mapper.mapExternalStatus(issueWithStatus); - assertSame(SonarQuestStatus.SOLVED, sonarQuestStatus); + SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); + assertSame(SonarQuestTaskStatus.SOLVED, sonarQuestTaskStatus); } @Test public void testMapExternalStatus_Resolved_FalsePositive() throws Exception { IssueWithStatus issueWithStatus = issue("RESOLVED"); when(issueWithStatus.getResolution()).thenReturn("FALSE-POSITIVE"); - SonarQuestStatus sonarQuestStatus = mapper.mapExternalStatus(issueWithStatus); - assertSame(SonarQuestStatus.CLOSED, sonarQuestStatus); + SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); + assertSame(SonarQuestTaskStatus.CLOSED, sonarQuestTaskStatus); } @Test public void testMapExternalStatus_Resolved() throws Exception { IssueWithStatus issueWithStatus = issue("RESOLVED"); - SonarQuestStatus sonarQuestStatus = mapper.mapExternalStatus(issueWithStatus); - assertSame(SonarQuestStatus.OPEN, sonarQuestStatus); + SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); + assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); } private IssueWithStatus issue(String sonarQubeStatus) { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestStatusTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestTaskStatusTest.java similarity index 59% rename from sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestStatusTest.java rename to sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestTaskStatusTest.java index f7403c61..da052150 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestStatusTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestTaskStatusTest.java @@ -1,28 +1,26 @@ -package com.viadee.sonarquest.rules; - -import static org.junit.Assert.assertSame; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import com.viadee.sonarquest.rules.SonarQuestStatus; - -public class SonarQuestStatusTest { - - @Rule - public ExpectedException exception = ExpectedException.none(); - - @Test - public void testFromStatusText() throws Exception { - SonarQuestStatus sonarQuestStatus = SonarQuestStatus.fromStatusText("SOLVED"); - assertSame(SonarQuestStatus.SOLVED, sonarQuestStatus); - } - - @Test - public void testFromStatusText_unknownStatusFail() throws Exception { - exception.expect(IllegalArgumentException.class); - SonarQuestStatus.fromStatusText("UNMAPPED_STATUS"); - } - -} +package com.viadee.sonarquest.rules; + +import static org.junit.Assert.assertSame; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class SonarQuestTaskStatusTest { + + @Rule + public ExpectedException exception = ExpectedException.none(); + + @Test + public void testFromStatusText() throws Exception { + SonarQuestTaskStatus sonarQuestTaskStatus = SonarQuestTaskStatus.fromStatusText("SOLVED"); + assertSame(SonarQuestTaskStatus.SOLVED, sonarQuestTaskStatus); + } + + @Test + public void testFromStatusText_unknownStatusFail() throws Exception { + exception.expect(IllegalArgumentException.class); + SonarQuestTaskStatus.fromStatusText("UNMAPPED_STATUS"); + } + +} diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java index cf7bb986..50d8a95c 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java @@ -1,22 +1,22 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - +import com.viadee.sonarquest.entities.Artefact; +import com.viadee.sonarquest.entities.Level; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.repositories.ArtefactRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import com.viadee.sonarquest.entities.Artefact; -import com.viadee.sonarquest.entities.Level; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.repositories.ArtefactRepository; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ArtefactServiceTest { @@ -30,9 +30,6 @@ public class ArtefactServiceTest { @Mock private LevelService levelService; - @Mock - private UserService userService; - private Artefact mockArtefact() { Artefact artefact = new Artefact(); artefact.setName("Mighty staff of fiery doom"); @@ -40,7 +37,7 @@ private Artefact mockArtefact() { } @Test - public void testGetArtefacts() throws Exception { + public void testGetArtefacts() { // given List savedArtefacts = new ArrayList<>(); Artefact artefact = new Artefact(); @@ -53,7 +50,7 @@ public void testGetArtefacts() throws Exception { } @Test - public void testGetArtefactsForMarketplace() throws Exception { + public void testGetArtefactsForMarketplace() { // Given List savedArtefacts = new ArrayList<>(); Artefact artefact = new Artefact(); @@ -66,10 +63,10 @@ public void testGetArtefactsForMarketplace() throws Exception { } @Test - public void testGetArtefact() throws Exception { + public void testGetArtefact() { // given Artefact savedArtefact = new Artefact(); - when(artefactRepository.findOne(1L)).thenReturn(savedArtefact); + when(artefactRepository.findById(1L)).thenReturn(Optional.of(savedArtefact)); // When Artefact artefact = service.getArtefact(1L); // Then @@ -77,7 +74,7 @@ public void testGetArtefact() throws Exception { } @Test - public void testCreateArtefact_minLevelDoesNotYetExist() throws Exception { + public void testCreateArtefact_minLevelDoesNotYetExist() { // given Artefact artefact = mockArtefact(); Level minLevel = mockLevel(1); @@ -91,7 +88,7 @@ public void testCreateArtefact_minLevelDoesNotYetExist() throws Exception { } @Test - public void testCreateArtefact_minLevelAlreadyExists() throws Exception { + public void testCreateArtefact_minLevelAlreadyExists() { Artefact artefact = mockArtefact(); Level minLevel = mockLevel(1); artefact.setMinLevel(minLevel); @@ -116,7 +113,7 @@ private Level mockLevel(int level) { * Result: user has 3 Gold left, Qty is 0 after purchase */ @Test - public void testBuyArtefact_Ok() throws Exception { + public void testBuyArtefact_Ok() { // Given Artefact artefact = mockArtefact(); artefact.setId(69L); @@ -129,7 +126,7 @@ public void testBuyArtefact_Ok() throws Exception { user.setLevel(mockLevel(2)); when(artefactRepository.save(artefact)).thenReturn(artefact); // When - Artefact boughtArtefact = service.buyArtefact(artefact, user); + Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(boughtArtefact, artefact); assertEquals(Long.valueOf(0), boughtArtefact.getQuantity()); @@ -143,7 +140,7 @@ public void testBuyArtefact_Ok() throws Exception { * returned) */ @Test - public void testBuyArtefact_InStock_UserCannotAfford() throws Exception { + public void testBuyArtefact_InStock_UserCannotAfford() { // Given Artefact artefact = mockArtefact(); artefact.setId(69L); @@ -156,7 +153,7 @@ public void testBuyArtefact_InStock_UserCannotAfford() throws Exception { user.setLevel(mockLevel(2)); when(artefactRepository.save(artefact)).thenReturn(artefact); // When - Artefact boughtArtefact = service.buyArtefact(artefact, user); + Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(1), artefact.getQuantity()); @@ -170,7 +167,7 @@ public void testBuyArtefact_InStock_UserCannotAfford() throws Exception { * returned) */ @Test - public void testBuyArtefact_ItemSoldOut() throws Exception { + public void testBuyArtefact_ItemSoldOut() { // Given Artefact artefact = mockArtefact(); artefact.setId(69L); @@ -183,7 +180,7 @@ public void testBuyArtefact_ItemSoldOut() throws Exception { user.setLevel(mockLevel(2)); when(artefactRepository.save(artefact)).thenReturn(artefact); // When - Artefact boughtArtefact = service.buyArtefact(artefact, user); + Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(0), artefact.getQuantity()); @@ -197,7 +194,7 @@ public void testBuyArtefact_ItemSoldOut() throws Exception { * returned) */ @Test - public void testBuyArtefact_userLevelNotHighEnough() throws Exception { + public void testBuyArtefact_userLevelNotHighEnough() { // Given Artefact artefact = mockArtefact(); artefact.setId(69L); @@ -210,7 +207,7 @@ public void testBuyArtefact_userLevelNotHighEnough() throws Exception { user.setLevel(mockLevel(1)); when(artefactRepository.save(artefact)).thenReturn(artefact); // When - Artefact boughtArtefact = service.buyArtefact(artefact, user); + Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(1), artefact.getQuantity()); @@ -224,7 +221,7 @@ public void testBuyArtefact_userLevelNotHighEnough() throws Exception { * returned) */ @Test - public void testBuyArtefact_userAlreadyOwnsArtefact() throws Exception { + public void testBuyArtefact_userAlreadyOwnsArtefact() { // Given Artefact artefact = mockArtefact(); artefact.setId(69L); @@ -238,7 +235,7 @@ public void testBuyArtefact_userAlreadyOwnsArtefact() throws Exception { user.getArtefacts().add(artefact); when(artefactRepository.save(artefact)).thenReturn(artefact); // When - Artefact boughtArtefact = service.buyArtefact(artefact, user); + Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(1), artefact.getQuantity()); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java index f086abde..799cfa34 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java @@ -70,7 +70,7 @@ public void testGetAllQuestsForWorldAndDeveloper() { when(questRepository.findByWorld(mockWorld)).thenReturn(mockQuests); // call method to be tested - final List> result = questService.getAllQuestsForWorldAndUser(mockWorld, mockDeveloper); + final List> result = questService.getAllQuestsForWorldAndUser(mockWorld.getId(), mockDeveloper); // verify result assertTrue(result.get(0).contains(mockQuest1)); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java index 6f35052a..ba8f15b8 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java @@ -19,7 +19,7 @@ import com.viadee.sonarquest.entities.World; import com.viadee.sonarquest.externalressources.SonarQubeSeverity; import com.viadee.sonarquest.repositories.StandardTaskRepository; -import com.viadee.sonarquest.rules.SonarQuestStatus; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @RunWith(MockitoJUnitRunner.class) public class StandardTaskServiceTest { @@ -40,7 +40,7 @@ public class StandardTaskServiceTest { public void testUpdateStandardTask() { StandardTask task = new StandardTask(); task.setKey("Color of Magic!"); - task.setStatus(SonarQuestStatus.OPEN); + task.setStatus(SonarQuestTaskStatus.OPEN); when(standardTaskRepository.save(Matchers.any(StandardTask.class))).thenReturn(task); when(standardTaskRepository.saveAndFlush(Matchers.any(StandardTask.class))).thenReturn(task); when(standardTaskRepository.findByKey(task.getKey())).thenReturn(task); @@ -50,17 +50,17 @@ public void testUpdateStandardTask() { task = standardTaskService.updateStandardTask(task); - assertEquals(SonarQuestStatus.OPEN, task.getStatus()); + assertEquals(SonarQuestTaskStatus.OPEN, task.getStatus()); // case: existing created task -> no external changes final StandardTask createdStandardTask = new StandardTask(); createdStandardTask.setKey("createdStandardTask"); - createdStandardTask.setStatus(SonarQuestStatus.OPEN); + createdStandardTask.setStatus(SonarQuestTaskStatus.OPEN); when(standardTaskRepository.findByKey(createdStandardTask.getKey())).thenReturn(createdStandardTask); standardTaskService.updateStandardTask(createdStandardTask); - assertEquals(SonarQuestStatus.OPEN, createdStandardTask.getStatus()); + assertEquals(SonarQuestTaskStatus.OPEN, createdStandardTask.getStatus()); // case: existing created task -> no external changes } @@ -68,8 +68,8 @@ public void testUpdateStandardTask() { @Test public void testGetLastState() throws Exception { StandardTask task = new StandardTask(); - SonarQuestStatus lastState = standardTaskService.getLastState(task); - assertEquals(SonarQuestStatus.OPEN, lastState); + SonarQuestTaskStatus lastState = standardTaskService.getLastState(task); + assertEquals(SonarQuestTaskStatus.OPEN, lastState); } @Test From 4f5a447060192fae717a1bdaedacced861f129b4 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Wed, 26 Feb 2020 09:33:24 +0100 Subject: [PATCH 06/17] Refactoring of Spring Boot 1 specific code to fit Spring Boot 2 Reworked pom file, reduced dependencies, added lombok --- sonarQuest-backend/pom.xml | 183 +++++------------- .../sonarquest/SonarQuestApplication.java | 3 +- .../configurations/SwaggerConfig.java | 22 --- .../sonarquest/configurations/WebConfig.java | 4 +- .../configurations/WebSocketConfig.java | 4 +- .../controllers/login/UserCredentials.java | 34 +--- .../viadee/sonarquest/entities/Adventure.java | 98 +--------- .../viadee/sonarquest/entities/Artefact.java | 120 +----------- .../sonarquest/entities/AvatarClass.java | 38 +--- .../sonarquest/entities/AvatarRace.java | 29 +-- .../com/viadee/sonarquest/entities/Event.java | 117 +---------- .../viadee/sonarquest/entities/EventDto.java | 93 +-------- .../sonarquest/entities/EventUserDto.java | 35 +--- .../com/viadee/sonarquest/entities/Level.java | 50 +---- .../sonarquest/entities/MessageDto.java | 22 +-- .../sonarquest/entities/Participation.java | 36 +--- .../sonarquest/entities/Permission.java | 35 +--- .../com/viadee/sonarquest/entities/Quest.java | 124 +----------- .../com/viadee/sonarquest/entities/Role.java | 27 +-- .../com/viadee/sonarquest/entities/Skill.java | 42 +--- .../sonarquest/entities/SpecialTask.java | 10 +- .../sonarquest/entities/StandardTask.java | 51 +---- .../com/viadee/sonarquest/entities/Task.java | 91 +-------- .../viadee/sonarquest/entities/UiDesign.java | 28 +-- .../com/viadee/sonarquest/entities/User.java | 37 +--- .../viadee/sonarquest/entities/UserDto.java | 110 +---------- .../sonarquest/entities/UserToWorldDto.java | 36 +--- .../sonarquest/entities/WizardMessage.java | 19 +- .../com/viadee/sonarquest/entities/World.java | 108 +---------- .../security/UsernameAndAuthorities.java | 20 +- .../security/WebSecurityConfiguration.java | 14 +- .../src/main/resources/application.properties | 4 +- ...erIT.java => AdventureControllerTest.java} | 110 +++++------ .../controllers/UserControllerTest.java | 31 ++- .../login/LoginControllerIntegrationTest.java | 11 +- .../sonarquest/entities/EventDtoTest.java | 6 +- .../viadee/sonarquest/entities/QuestTest.java | 15 +- .../sonarquest/entities/UserDtoTest.java | 18 +- .../viadee/sonarquest/entities/UserTest.java | 12 +- .../SonarQubeApiCallIT.java | 25 ++- .../SonarQubeSeverityTest.java | 7 +- .../integration/IntegrationTests.java | 13 -- .../integration/SonarQuestApplicationIT.java | 144 +++++++------- .../integration/UserManagementIT.java | 16 +- .../rules/SonarQubeStatusMapperTest.java | 26 +-- .../rules/SonarQuestTaskStatusTest.java | 18 +- .../services/AdventureServiceTest.java | 30 ++- .../services/ArtefactServiceIT.java | 18 +- .../services/ArtefactServiceTest.java | 12 +- .../sonarquest/services/EventServiceIT.java | 55 ++---- .../ExternalRessourceServiceTest.java | 9 +- .../sonarquest/services/QuestServiceTest.java | 26 ++- .../services/SonarConfigServiceTest.java | 14 +- .../services/StandardTaskServiceTest.java | 47 +++-- .../services/WizardServiceTest.java | 23 +-- sonarQuest-frontend/karma.conf.js | 4 +- 56 files changed, 464 insertions(+), 1870 deletions(-) delete mode 100644 sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/SwaggerConfig.java rename sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/{AdventureControllerIT.java => AdventureControllerTest.java} (68%) delete mode 100644 sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/IntegrationTests.java diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index 36768e64..edb8fef7 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -23,6 +23,8 @@ http://www.viadee.de + https://github.com/viadee/sonarQuest + org.springframework.boot spring-boot-starter-parent @@ -34,33 +36,16 @@ UTF-8 UTF-8 1.8 + Hoxton.SR1 - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework - spring-core - - - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.springframework.security - spring-security-web + spring-boot-starter-actuator - org.springframework.security - spring-security-config + org.springframework.boot + spring-boot-starter-data-jpa org.springframework.boot @@ -74,137 +59,93 @@ org.springframework.boot spring-boot-starter-web - - org.springframework.boot - spring-boot-starter-jdbc - org.springframework.boot spring-boot-starter-websocket - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework - spring-websocket - - - org.springframework - spring-messaging + org.flywaydb + flyway-core - org.springframework.security - spring-security-messaging + org.springframework.cloud + spring-cloud-starter-sleuth - io.jsonwebtoken - jjwt - 0.9.1 + org.springframework.boot + spring-boot-devtools + runtime + true com.h2database h2 runtime + 1.4.199 - mysql - mysql-connector-java - provided - - - org.flywaydb - flyway-core + org.projectlombok + lombok + true org.springframework.boot spring-boot-starter-test test + + + org.junit.vintage + junit-vintage-engine + + - org.mockito - mockito-core + org.springframework.security + spring-security-test test - io.springfox - springfox-swagger2 - 2.7.0 - - - io.springfox - springfox-swagger-ui - 2.7.0 + org.springframework.security + spring-security-messaging org.apache.commons commons-lang3 - 3.7 - - - - net.logstash.logback - logstash-logback-encoder - 4.11 + 3.9 - org.apache.commons commons-collections4 - 4.2 - - - - commons-io - commons-io - 2.6 + 4.4 - - org.springframework.cloud - spring-cloud-starter-sleuth - 2.2.1.RELEASE - - - - net.logstash.logback - logstash-logback-encoder - 4.11 - - - org.springframework.boot - spring-boot-starter-integration - - - javax.xml.bind - jaxb-api - 2.2.11 - - - com.sun.xml.bind - jaxb-core - 2.2.11 - - - com.sun.xml.bind - jaxb-impl - 2.2.11 - - - javax.activation - activation - 1.1.1 + io.jsonwebtoken + jjwt + 0.9.1 org.apache.httpcomponents httpclient 4.5.2 + + commons-io + commons-io + 2.6 + - + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + - ${artifactId} org.springframework.boot @@ -215,32 +156,6 @@ jacoco-maven-plugin 0.8.0 - - org.apache.maven.plugins - maven-surefire-plugin - - -Dspring.profiles.active=dev - - - - - - - - - - - - - - - - - - - - - https://github.com/viadee/sonarQuest \ No newline at end of file diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/SonarQuestApplication.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/SonarQuestApplication.java index e0a2452c..ad87a98d 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/SonarQuestApplication.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/SonarQuestApplication.java @@ -6,7 +6,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication public class SonarQuestApplication implements CommandLineRunner { @@ -22,7 +21,7 @@ public void run(String... strings) { @Bean public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurerAdapter() { + return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("http://localhost:4200") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/SwaggerConfig.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/SwaggerConfig.java deleted file mode 100644 index 20f8d92c..00000000 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/SwaggerConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.viadee.sonarquest.configurations; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableSwagger2 -public class SwaggerConfig { - @Bean - public Docket api() { - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.any()) - .paths(PathSelectors.any()) - .build(); - } -} diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebConfig.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebConfig.java index 1bf39772..4d7064b7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebConfig.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebConfig.java @@ -3,10 +3,10 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -public class WebConfig extends WebMvcConfigurerAdapter { +public class WebConfig implements WebMvcConfigurer { @Value("${cors.header.active:false}") private boolean corsHeaderActive; diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebSocketConfig.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebSocketConfig.java index b3a545fb..b0f22576 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebSocketConfig.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/WebSocketConfig.java @@ -4,13 +4,13 @@ import org.apache.commons.logging.LogFactory; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker -public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { +public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { protected static final Log LOGGER = LogFactory.getLog(WebSocketConfig.class); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/login/UserCredentials.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/login/UserCredentials.java index c4c383a6..b4ecebe3 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/login/UserCredentials.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/login/UserCredentials.java @@ -1,38 +1,10 @@ package com.viadee.sonarquest.controllers.login; -import org.hibernate.validator.constraints.NotBlank; +import lombok.*; +@Data +@AllArgsConstructor public class UserCredentials { - - @NotBlank private String username; - - @NotBlank private String password; - - public UserCredentials() { - super(); - } - - public UserCredentials(final String username, final String password) { - this.setUsername(username); - this.setPassword(password); - } - - public final String getUsername() { - return this.username; - } - - public final void setUsername(final String username) { - this.username = username; - } - - public final String getPassword() { - return this.password; - } - - public final void setPassword(final String password) { - this.password = password; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java index 169294dc..05968cf3 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java @@ -21,7 +21,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.AdventureState; +import lombok.*; +@Data @Entity @Table(name = "Adventure") public class Adventure { @@ -95,71 +97,6 @@ public Adventure(final Long id, final String title, final String story, final Ad this.users = users; } - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getStory() { - return story; - } - - public void setStory(final String story) { - this.story = story; - } - - public AdventureState getStatus() { - return status; - } - - public void setStatus(final AdventureState status) { - this.status = status; - } - - public Long getGold() { - return gold; - } - - public void setGold(final Long gold) { - this.gold = gold; - } - - public Long getXp() { - return xp; - } - - public void setXp(final Long xp) { - this.xp = xp; - } - - public List getQuests() { - return quests; - } - - public void setQuests(final List quests) { - this.quests = quests; - } - - @JsonIgnore - public List getUsers() { - return users; - } - - public void setUsers(final List users) { - this.users = users; - } - public synchronized void addUser(final User user) { if (users == null) { users = new ArrayList<>(); @@ -171,35 +108,4 @@ public synchronized void removeUser(final User user) { users.remove(user); } - public World getWorld() { - return world; - } - - public void setWorld(final World world) { - this.world = world; - } - - public Boolean getVisible() { - return visible; - } - - public void setVisible(Boolean visible) { - this.visible = visible; - } - - public Date getEnddate() { - return enddate; - } - - public void setEnddate(Date enddate) { - this.enddate = enddate; - } - - public Date getStartdate() { - return startdate; - } - - public void setStartdate(Date startdate) { - this.startdate = startdate; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java index 3283fd0e..412b8575 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java @@ -14,7 +14,9 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.*; +@Data @Entity @Table(name = "Artefact") public class Artefact { @@ -112,122 +114,4 @@ public Artefact(final Long id, final String name, final String icon, final Long this.onMarketplace = true; } - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getIcon() { - return icon; - } - - public void setIcon(final String icon) { - this.icon = icon; - } - - public List getSkills() { - return skills; - } - - public void setSkills(final List skills) { - this.skills = skills; - } - - public List getUsers() { - return users; - } - - public void setUsers(final List users) { - this.users = users; - } - - public Long getPrice() { - return price; - } - - public void setPrice(final Long price) { - this.price = price; - } - - public Level getMinLevel() { - return minLevel; - } - - public void setMinLevel(final Level minLevel) { - this.minLevel = minLevel; - } - - public Long getQuantity() { - return quantity; - } - - public void setQuantity(final Long quantity) { - this.quantity = quantity; - } - - public String getDescription() { - return description; - } - - public void setDescription(final String description) { - this.description = description; - } - - public boolean isOnMarketplace() { - return onMarketplace; - } - - public void setOnMarketplace(boolean onMarketplace) { - this.onMarketplace = onMarketplace; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Artefact other = (Artefact) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java index 939b2bb2..eeb885cc 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java @@ -14,7 +14,10 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.*; +@Data +@NoArgsConstructor @Entity @Table(name = "Avatar_Class") public class AvatarClass { @@ -34,9 +37,6 @@ public class AvatarClass { @JoinTable(name = "Avatar_Class_Skill", joinColumns = @JoinColumn(name = "avatar_class_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "skill_id", referencedColumnName = "id")) private List skills; - public AvatarClass() { - } - public AvatarClass(final String name) { this.name = name; } @@ -46,36 +46,4 @@ public AvatarClass(final String name, final List users, final List this.users = users; this.skills = skills; } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public List getUsers() { - return users; - } - - public void setDevelopers(final List users) { - this.users = users; - } - - public List getSkills() { - return skills; - } - - public void setSkills(final List skills) { - this.skills = skills; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java index 06601617..0d3864db 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java @@ -11,7 +11,10 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.*; +@NoArgsConstructor +@Data @Entity @Table(name = "Avatar_Race") public class AvatarRace { @@ -27,9 +30,6 @@ public class AvatarRace { @OneToMany(mappedBy = "avatarRace", cascade = CascadeType.ALL) private List users; - public AvatarRace() { - } - public AvatarRace(final String name) { this.name = name; } @@ -39,27 +39,4 @@ public AvatarRace(final String name, final List users) { this.users = users; } - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public List getUsers() { - return users; - } - - public void setUsers(final List users) { - this.users = users; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java index 3d629160..eb33d319 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java @@ -12,8 +12,11 @@ import com.viadee.sonarquest.constants.EventState; import com.viadee.sonarquest.constants.EventType; +import lombok.*; +@Data @Entity +@NoArgsConstructor @Table(name = "Event") public class Event { @@ -50,9 +53,6 @@ public class Event { @Column(name = "timestamp") private Timestamp timestamp; - public Event() { - } - public Event(String title) { this.title = title; } @@ -111,115 +111,4 @@ public Event(EventType type, String title, String story, EventState state, Strin this.user = user; world = null; } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - - public EventType getType() { - return type; - } - - public void setType(EventType type) { - this.type = type; - } - - public String getStory() { - return story; - } - - public void setStory(String story) { - this.story = story; - } - - public EventState getState() { - return state; - } - - public void setState(EventState state) { - this.state = state; - } - - public String getImage() { - return image; - } - - public void setImage(String image) { - this.image = image; - } - - public World getWorld() { - return world; - } - - public void setWorld(World world) { - this.world = world; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } - - public String getHeadline() { - return headline; - } - - public void setHeadline(String headline) { - this.headline = headline; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((title == null) ? 0 : title.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Event other = (Event) obj; - if (title == null) { - if (other.title != null) { - return false; - } - } else if (!title.equals(other.title)) { - return false; - } - return true; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventDto.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventDto.java index e9887fb0..a5cfb09c 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventDto.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventDto.java @@ -4,7 +4,15 @@ import com.viadee.sonarquest.constants.EventState; import com.viadee.sonarquest.constants.EventType; - +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@ToString +@Setter +@Getter +@NoArgsConstructor public class EventDto { private Long id; @@ -18,9 +26,6 @@ public class EventDto { private Long userId; private Timestamp timestamp; - public EventDto() { - } - public EventDto(Event event) { if (event.getUser() != null) { this.userId = event.getUser().getId(); @@ -44,84 +49,4 @@ public EventDto(Event event) { this.timestamp = event.getTimestamp(); } - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public EventType getType() { - return type; - } - - public void setType(EventType type) { - this.type = type; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getStory() { - return story; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public EventState getState() { - return state; - } - - public void setStory(String story) { - this.story = story; - } - - public void setState(EventState state) { - this.state = state; - } - - public void setHeadline(String headline) { - this.headline = headline; - } - - public String getHeadline() { - return headline; - } - - public void setWorldId(Long worldId) { - this.worldId = worldId; - } - - public Long getWorldId() { - return worldId; - } - - public void setImage(String image) { - this.image = image; - } - - public String getImage() { - return image; - } - - public Timestamp getTimestamp() { - return timestamp; - } - - public void setTimestamp(Timestamp timestamp) { - this.timestamp = timestamp; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventUserDto.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventUserDto.java index e654ab45..23346461 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventUserDto.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/EventUserDto.java @@ -1,34 +1,17 @@ package com.viadee.sonarquest.entities; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.util.List; +@AllArgsConstructor +@NoArgsConstructor +@Getter +@Setter public class EventUserDto { - private List userDtos; private List eventDtos; - - public EventUserDto() { - } - - public EventUserDto(List userDtos, List eventDtos) { - this.userDtos = userDtos; - this.eventDtos = eventDtos; - } - - public List getUserDtos() { - return userDtos; - } - - public void setUserDtos(List userDtos) { - this.userDtos = userDtos; - } - - public List getEventDtos() { - return eventDtos; - } - - public void setEventDtos(List eventDtos) { - this.eventDtos = eventDtos; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java index db07bd4e..00cc89b9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java @@ -10,7 +10,9 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; +@Data @Entity @Table(name = "SQLevel") public class Level { @@ -54,52 +56,4 @@ public Level(final Long min, final Long max, final List users, final List< public Level(final Long minLevel) { minXp = minLevel; } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public Long getMinXp() { - return minXp; - } - - public void setMinXp(final Long min) { - minXp = min; - } - - public Long getMaxXp() { - return maxXp; - } - - public void setMaxXp(final Long max) { - maxXp = max; - } - - public List getUsers() { - return users; - } - - public void setUsers(final List users) { - this.users = users; - } - - public List getArtefacts() { - return artefacts; - } - - public void setArtefacts(final List artefacts) { - this.artefacts = artefacts; - } - - public int getLevelNumber() { - return levelNumber; - } - - public void setLevelNumber(int level) { - levelNumber = level; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/MessageDto.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/MessageDto.java index 104856f2..a1e41fd7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/MessageDto.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/MessageDto.java @@ -1,5 +1,10 @@ package com.viadee.sonarquest.entities; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter public class MessageDto { private String message; private Long userId; @@ -11,21 +16,4 @@ public MessageDto(String message, Long userId) { this.message = message; this.userId = userId; } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java index 1362c78e..3384435b 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java @@ -1,5 +1,7 @@ package com.viadee.sonarquest.entities; +import lombok.Data; + import java.util.List; import javax.persistence.CascadeType; @@ -11,6 +13,7 @@ import javax.persistence.OneToMany; import javax.persistence.Table; +@Data @Entity @Table(name = "Participation") public class Participation { @@ -44,37 +47,4 @@ public Participation(final Long id, final List tasks, final Quest quest, f this.quest = quest; this.user = user; } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public List getTasks() { - return tasks; - } - - public void setTasks(final List tasks) { - this.tasks = tasks; - } - - public Quest getQuest() { - return quest; - } - - public void setQuest(final Quest quest) { - this.quest = quest; - } - - public User getUser() { - return user; - } - - public void setUser(final User user) { - this.user = user; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java index e81394a6..9d6b2e57 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java @@ -16,7 +16,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.PermissionType; +import lombok.Data; +@Data @Entity @Table(name = "Permission") public class Permission { @@ -37,37 +39,4 @@ public class Permission { @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "Role_To_Permission", joinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) private List roles; - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public PermissionType getType() { - return type; - } - - public void setType(final PermissionType type) { - this.type = type; - } - - public String getPermission() { - return permission; - } - - public void setPermission(final String permission) { - this.permission = permission; - } - - public List getRoles() { - return roles; - } - - public void setRoles(final List roles) { - this.roles = roles; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java index d69b7e30..29eef6c7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java @@ -19,7 +19,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.QuestState; +import lombok.Data; +@Data @Entity @Table(name = "Quest") public class Quest { @@ -44,7 +46,7 @@ public class Quest { private String story; @Column(name = "creator_name") - private String creatorname; + private String creatorName; @Column(name = "status") @Enumerated(EnumType.STRING) @@ -106,94 +108,6 @@ public Quest(final String title, final String story, final QuestState status, fi this.image = image; } - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public String getStory() { - return story; - } - - public void setStory(final String story) { - this.story = story; - } - - public QuestState getStatus() { - return status; - } - - public void setStatus(final QuestState status) { - this.status = status; - } - - public Long getGold() { - return gold; - } - - public void setGold(final Long gold) { - this.gold = gold; - } - - public Long getXp() { - return xp; - } - - public void setXp(final Long xp) { - this.xp = xp; - } - - public String getImage() { - return image; - } - - public void setImage(final String image) { - this.image = image; - } - - public World getWorld() { - return world; - } - - public void setWorld(final World world) { - this.world = world; - } - - public Adventure getAdventure() { - return adventure; - } - - public void setAdventure(final Adventure adventure) { - this.adventure = adventure; - } - - public List getTasks() { - return tasks; - } - - public void setTasks(final List tasks) { - this.tasks = tasks; - } - - public List getParticipations() { - return participations; - } - - public void setParticipations(final List participations) { - this.participations = participations; - } - /** * Looks up the usernames of all participants in this quests and returns them in a list. */ @@ -205,36 +119,4 @@ public List getParticipants() { return new ArrayList<>(); } } - - public Boolean getVisible() { - return visible; - } - - public void setVisible(Boolean visible) { - this.visible = visible; - } - - public Date getEnddate() { - return enddate; - } - - public void setEnddate(Date enddate) { - this.enddate = enddate; - } - - public Date getStartdate() { - return startdate; - } - - public void setStartdate(Date startdate) { - this.startdate = startdate; - } - - public String getCreatorName() { - return creatorname; - } - - public void setCreatorName(String creatorname) { - this.creatorname = creatorname; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java index 1240e581..7991cdc3 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java @@ -15,7 +15,9 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; +@Data @Entity @Table(name = "Role") public class Role { @@ -33,29 +35,4 @@ public class Role { @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "Role_To_Permission", joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "permission_id", referencedColumnName = "id")) private List permissions; - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public RoleName getName() { - return name; - } - - public void setName(final RoleName name) { - this.name = name; - } - - public List getPermissions() { - return permissions; - } - - public void setPermissions(final List permissions) { - this.permissions = permissions; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java index 5533fcb6..26a86781 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java @@ -14,7 +14,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.SkillType; +import lombok.Data; +@Data @Entity @Table(name = "Skill") public class Skill { @@ -52,44 +54,4 @@ public Skill(final String name, final SkillType type, final Long value, final Li this.value = value; this.avatarClasses = avatarClasses; } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public SkillType getType() { - return type; - } - - public void setType(final SkillType type) { - this.type = type; - } - - public Long getValue() { - return value; - } - - public void setValue(final Long value) { - this.value = value; - } - - public List getAvatarClasses() { - return avatarClasses; - } - - public void setAvatarClasses(final List avatarClasses) { - this.avatarClasses = avatarClasses; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java index 43d55557..8c7393fa 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java @@ -5,7 +5,9 @@ import javax.persistence.Entity; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import lombok.Data; +@Data @Entity @DiscriminatorValue("SPECIAL") public class SpecialTask extends Task { @@ -27,12 +29,4 @@ public SpecialTask(final String title, final SonarQuestTaskStatus status, final this.message = message; this.setWorld(world); } - - public String getMessage() { - return message; - } - - public void setMessage(final String message) { - this.message = message; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java index 5a979861..3c5993f7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java @@ -5,7 +5,9 @@ import javax.persistence.Entity; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import lombok.Data; +@Data @Entity @DiscriminatorValue("STANDARD") public class StandardTask extends Task { @@ -50,53 +52,4 @@ public StandardTask(final String title, final SonarQuestTaskStatus status, final this.issueKey = issueKey; this.issueRule = issueRule; } - - public String getComponent() { - return component; - } - - public void setComponent(final String component) { - this.component = component; - } - - public String getSeverity() { - return severity; - } - - public void setSeverity(final String severity) { - this.severity = severity; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } - - public Integer getDebt() { - return debt; - } - - public void setDebt(final Integer debt) { - this.debt = debt; - } - - public String getIssueKey() { - return issueKey; - } - - public void setIssueKey(final String issueKey) { - this.issueKey = issueKey; - } - - public String getIssueRule() { - return issueRule; - } - - public void setIssueRule(String issueRule) { - this.issueRule = issueRule; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java index 9a38f3d7..2e8570b7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java @@ -18,7 +18,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import lombok.Data; +@Data @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "task_type") @@ -64,93 +66,4 @@ public class Task { @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "participation_id") private Participation participation; - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(final String title) { - this.title = title; - } - - public SonarQuestTaskStatus getStatus() { - return status; - } - - public void setStatus(SonarQuestTaskStatus status) { - this.status = status; - } - - public Long getGold() { - return gold; - } - - public void setGold(final Long gold) { - this.gold = gold; - } - - public Long getXp() { - return xp; - } - - public void setXp(final Long xp) { - this.xp = xp; - } - - public Quest getQuest() { - return quest; - } - - public void setQuest(final Quest quest) { - this.quest = quest; - } - - public Participation getParticipation() { - return participation; - } - - public void setParticipation(final Participation participation) { - this.participation = participation; - } - - public World getWorld() { - return world; - } - - public void setWorld(final World world) { - this.world = world; - } - - public String getKey() { - return key; - } - - public void setKey(final String key) { - this.key = key; - } - - public Date getStartdate() { - return startdate; - } - - public void setStartdate(Date startdate) { - this.startdate = startdate; - } - - public Date getEnddate() { - return enddate; - } - - public void setEnddate(Date enddate) { - this.enddate = enddate; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java index ed662865..a64640b4 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java @@ -11,7 +11,10 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; +import lombok.EqualsAndHashCode; +@Data @Entity @Table(name = "Ui_Design") public class UiDesign { @@ -28,29 +31,4 @@ public class UiDesign { @OneToOne @JoinColumn(name = "user_id") private User user; - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public UiDesignName getName() { - return name; - } - - public void setName(final UiDesignName name) { - this.name = name; - } - - public User getUser() { - return user; - } - - public void setUser(final User user) { - this.user = user; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java index 2476fe36..8875dcaa 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java @@ -1,28 +1,16 @@ package com.viadee.sonarquest.entities; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.EqualsAndHashCode; +import org.apache.commons.lang3.Validate; + +import javax.persistence.*; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.Table; - -import org.apache.commons.lang3.Validate; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.base.Objects; - +@EqualsAndHashCode @Entity @Table(name = "SQUser") public class User { @@ -313,17 +301,4 @@ public List getJoinedWorlds() { return new ArrayList<>(); } } - - @Override - public int hashCode() { - return this.getId() == null ? super.hashCode() : Objects.hashCode(this.getId()); - } - - @Override - public boolean equals(final Object that) { - return this.getId() == null ? this == that - : that != null && this.getClass().isInstance(that) - && Objects.equal(this.getId(), ((User) that).getId()); - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserDto.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserDto.java index 6f27071f..3dffa4b9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserDto.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserDto.java @@ -1,7 +1,12 @@ package com.viadee.sonarquest.entities; +import lombok.Getter; +import lombok.Setter; + import java.sql.Timestamp; +@Getter +@Setter public class UserDto { private Long id; @@ -42,109 +47,4 @@ public UserDto(User user) { this.lastLogin = user.getLastLogin(); this.picture = user.getPicture(); } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getMail() { - return mail; - } - - public void setMail(String mail) { - this.mail = mail; - } - - public Role getRole() { - return role; - } - - public void setRole(Role role) { - this.role = role; - } - - public String getPicture() { - return picture; - } - - public void setPicture(String picture) { - this.picture = picture; - } - - public String getAboutMe() { - return aboutMe; - } - - public void setAboutMe(String aboutMe) { - this.aboutMe = aboutMe; - } - - public AvatarClass getAvatarClass() { - return avatarClass; - } - - public void setAvatarClass(AvatarClass avatarClass) { - this.avatarClass = avatarClass; - } - - public AvatarRace getAvatarRace() { - return avatarRace; - } - - public void setAvatarRace(AvatarRace avatarRace) { - this.avatarRace = avatarRace; - } - - public Long getGold() { - return gold; - } - - public void setGold(Long gold) { - this.gold = gold; - } - - public Long getXp() { - return xp; - } - - public void setXp(Long xp) { - this.xp = xp; - } - - public Level getLevel() { - return level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public Long getCurrentWorldId() { - return currentWorldId; - } - - public void setCurrentWorldId(Long currentWorldId) { - this.currentWorldId = currentWorldId; - } - - public Timestamp getLastLogin() { - return lastLogin; - } - - public void setLastLogin(Timestamp lastLogin) { - this.lastLogin = lastLogin; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldDto.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldDto.java index 3f4d8f38..ca51ea5e 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldDto.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldDto.java @@ -1,41 +1,11 @@ package com.viadee.sonarquest.entities; +import lombok.Data; + +@Data public class UserToWorldDto { private Long userId; private Long worldId; private String worldName; private Boolean joined; - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public Long getWorldId() { - return worldId; - } - - public void setWorldId(Long worldId) { - this.worldId = worldId; - } - - public String getWorldName() { - return worldName; - } - - public void setWorldName(String worldName) { - this.worldName = worldName; - } - - public Boolean getJoined() { - return joined; - } - - public void setJoined(Boolean joined) { - this.joined = joined; - } - } \ No newline at end of file diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/WizardMessage.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/WizardMessage.java index 3d299f31..acfb257d 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/WizardMessage.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/WizardMessage.java @@ -1,5 +1,7 @@ package com.viadee.sonarquest.entities; +import lombok.Data; + /** * Entity for WizardMessages (not persistant). It contains a message that usually points to a problem, as well as a * solution advice. @@ -7,25 +9,10 @@ * @author MeC * */ +@Data public class WizardMessage { private String message; private String solution; - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getSolution() { - return solution; - } - - public void setSolution(String solution) { - this.solution = solution; - } } \ No newline at end of file diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java index 646efd40..6d9fb479 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java @@ -1,21 +1,12 @@ package com.viadee.sonarquest.entities; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.OneToMany; -import javax.persistence.Table; - import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.base.Objects; +import lombok.Data; +import javax.persistence.*; +import java.util.List; + +@Data @Entity @Table(name = "World") public class World { @@ -65,93 +56,4 @@ public World(final String name, final String project, final Boolean active, fina this.active = active; this.usequestcards = usequestcards; } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getProject() { - return project; - } - - public void setProject(final String project) { - this.project = project; - } - - public List getQuests() { - return quests; - } - - public void setQuests(final List quests) { - this.quests = quests; - } - - public Boolean getActive() { - return active; - } - - public void setActive(final Boolean active) { - this.active = active; - } - - public Boolean getUsequestcards() { - return usequestcards; - } - - public void setUsequestcards(Boolean usequestcards) { - this.usequestcards = usequestcards; - } - - public List getTasks() { - return tasks; - } - - public void setTasks(final List tasks) { - this.tasks = tasks; - } - - public String getImage() { - return image; - } - - public void setImage(final String image) { - this.image = image; - } - - public List getUsers() { - return users; - } - - public void setUsers(final List users) { - this.users = users; - } - - public boolean hasQuests() { - return !getQuests().isEmpty(); - } - - @Override - public int hashCode() { - return getId() == null ? super.hashCode() : Objects.hashCode(getId()); - } - - @Override - public boolean equals(final Object that) { - return getId() == null ? this == that - : that != null && this.getClass().isInstance(that) - && Objects.equal(getId(), ((World) that).getId()); - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/UsernameAndAuthorities.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/UsernameAndAuthorities.java index f38a943a..e34e6dab 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/UsernameAndAuthorities.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/UsernameAndAuthorities.java @@ -2,25 +2,13 @@ import java.util.Collection; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.springframework.security.core.GrantedAuthority; +@Getter +@AllArgsConstructor public class UsernameAndAuthorities { - private final String username; - private final Collection authorities; - - public UsernameAndAuthorities(final String username, final Collection authorities) { - this.username = username; - this.authorities = authorities; - } - - public String getUsername() { - return username; - } - - public Collection getAuthorities() { - return authorities; - } - } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/WebSecurityConfiguration.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/WebSecurityConfiguration.java index dc0f5892..b60cb321 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/WebSecurityConfiguration.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/WebSecurityConfiguration.java @@ -1,5 +1,6 @@ package com.viadee.sonarquest.security; +import com.viadee.sonarquest.services.UserService; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; @@ -19,7 +20,8 @@ import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.Collections; @EnableGlobalMethodSecurity(prePostEnabled = true) @EnableWebSecurity @@ -34,13 +36,13 @@ public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Value("${cors.header.active:false}") private boolean corsHeaderActive; - public WebSecurityConfiguration(final UserDetailsService userDetailsService, final JwtHelper jwtHelper) { + public WebSecurityConfiguration(final UserService userDetailsService, final JwtHelper jwtHelper) { this.userDetailsService = userDetailsService; this.jwtHelper = jwtHelper; } @Override - protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + protected void configure(final AuthenticationManagerBuilder auth) { auth.authenticationProvider(getAuthenticationProvider()); } @@ -95,10 +97,10 @@ protected void configure(final HttpSecurity http) throws Exception { @Bean public CorsConfigurationSource corsConfigurationSource() { final CorsConfiguration configuration = new CorsConfiguration(); - configuration.setAllowedOrigins(ImmutableList.of("http://localhost:4200")); - configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")); + configuration.setAllowedOrigins(Collections.unmodifiableList(Collections.singletonList("http://localhost:4200"))); + configuration.setAllowedMethods(Collections.unmodifiableList(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"))); configuration.setAllowCredentials(true); - configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type")); + configuration.setAllowedHeaders(Collections.unmodifiableList(Arrays.asList("Authorization", "Cache-Control", "Content-Type"))); final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; diff --git a/sonarQuest-backend/src/main/resources/application.properties b/sonarQuest-backend/src/main/resources/application.properties index 5758080a..d2670f5d 100644 --- a/sonarQuest-backend/src/main/resources/application.properties +++ b/sonarQuest-backend/src/main/resources/application.properties @@ -4,7 +4,7 @@ # Verwendeter Algorithmus security.jwt.algorithm=HS512 # Gütligkeit eines JWTs in Millisekunden -security.jwt.validity=7200000 +security.jwt.validity=7200000 # ======================================== # CORS-HEADER @@ -21,7 +21,7 @@ avatar.directory=/avatar/ # ======================================== # DATASOURCE # ======================================== -spring.datasource.url=jdbc:h2:file:./target/classes/db/sonarQuest +spring.datasource.url=jdbc:h2:file:./target/classes/db/sonarQuest;AUTO_SERVER=TRUE spring.datasource.platform=h2 spring.datasource.driverClassName=org.h2.Driver spring.jpa.database-platform=org.hibernate.dialect.H2Dialect diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java similarity index 68% rename from sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerIT.java rename to sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java index 868ebe59..919f6569 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java @@ -1,59 +1,51 @@ -package com.viadee.sonarquest.controllers; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.security.Principal; - -import javax.transaction.Transactional; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.viadee.sonarquest.constants.AdventureState; -import com.viadee.sonarquest.entities.Adventure; - -@RunWith(SpringRunner.class) -@SpringBootTest -@Transactional -public class AdventureControllerIT { - - @Autowired - private AdventureController adventureController; - - @Test - public void createAdventure() throws Exception { - // Given - String title = "Testadventure"; - String story = "My story"; - long gold = 10L; - long xp = 10L; - Adventure adventure = new Adventure(title, story, AdventureState.OPEN, gold, xp); - // when - Adventure newAdventure = adventureController.createAdventure(createPrincipal(), adventure); - // then - assertNotNull(newAdventure.getId()); - assertTrue(newAdventure.getId() > 0); - assertEquals(title, newAdventure.getTitle()); - assertEquals(story, newAdventure.getStory()); - assertEquals(AdventureState.OPEN, newAdventure.getStatus()); - assertEquals(gold, newAdventure.getGold().longValue()); - assertEquals(xp, newAdventure.getXp().longValue()); - - } - - private Principal createPrincipal() { - return new Principal() { - - @Override - public String getName() { - return "admin"; - } - }; - } - -} +package com.viadee.sonarquest.controllers; + +import com.viadee.sonarquest.constants.AdventureState; +import com.viadee.sonarquest.entities.Adventure; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import javax.transaction.Transactional; +import java.security.Principal; + +import static org.junit.jupiter.api.Assertions.*; + + +@ExtendWith(SpringExtension.class) +@SpringBootTest +@Transactional +public class AdventureControllerTest { + + @Autowired + private AdventureController adventureController; + + @Test + public void createAdventure() { + // Given + String title = "Testadventure"; + String story = "My story"; + long gold = 10L; + long xp = 10L; + Adventure adventure = new Adventure(title, story, AdventureState.OPEN, gold, xp); + // when + Adventure newAdventure = adventureController.createAdventure(createPrincipal(), adventure); + // then + assertNotNull(newAdventure.getId()); + assertTrue(newAdventure.getId() > 0); + assertEquals(title, newAdventure.getTitle()); + assertEquals(story, newAdventure.getStory()); + assertEquals(AdventureState.OPEN, newAdventure.getStatus()); + assertEquals(gold, newAdventure.getGold().longValue()); + assertEquals(xp, newAdventure.getXp().longValue()); + + } + + private Principal createPrincipal() { + return () -> "admin"; + } + +} diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/UserControllerTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/UserControllerTest.java index 4d2f1047..c4c3b6b3 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/UserControllerTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/UserControllerTest.java @@ -1,24 +1,23 @@ package com.viadee.sonarquest.controllers; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.security.Principal; - -import javax.servlet.http.HttpServletResponse; - -import org.junit.Test; -import org.junit.runner.RunWith; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.services.UserService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.services.UserService; +import javax.servlet.http.HttpServletResponse; +import java.security.Principal; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class UserControllerTest { @Mock @@ -28,7 +27,7 @@ public class UserControllerTest { private UserController userController; @Test - public void testAvatar_userServiceFindetUserNicht() throws Exception { + public void testAvatar_userServiceDoesntFindUser() { Principal principal = mock(Principal.class); when(principal.getName()).thenReturn("Aria"); when(userService.findByUsername("Aria")).thenReturn(null); @@ -38,7 +37,7 @@ public void testAvatar_userServiceFindetUserNicht() throws Exception { } @Test - public void testAvatar_userServiceMitUserOhnePicture() throws Exception { + public void testAvatar_userServiceWithUserWithoutAvatar() { Principal principal = mock(Principal.class); when(principal.getName()).thenReturn("Aria"); User user = mock(User.class); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java index 24ec7dc4..5cc0498f 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java @@ -1,14 +1,15 @@ package com.viadee.sonarquest.controllers.login; -import static org.junit.Assert.assertEquals; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -@RunWith(SpringRunner.class) +import static org.junit.jupiter.api.Assertions.assertEquals; + +@ExtendWith(SpringExtension.class) @SpringBootTest public class LoginControllerIntegrationTest { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/EventDtoTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/EventDtoTest.java index 90f69f72..108206d1 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/EventDtoTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/EventDtoTest.java @@ -1,13 +1,13 @@ package com.viadee.sonarquest.entities; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; public class EventDtoTest { @Test - public void testConstructEventDto() throws Exception { + public void testConstructEventDto() { // Given Event event = new Event(); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/QuestTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/QuestTest.java index 8121671b..1c8ef19d 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/QuestTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/QuestTest.java @@ -1,29 +1,26 @@ package com.viadee.sonarquest.entities; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.Test; - -import com.viadee.sonarquest.entities.Participation; -import com.viadee.sonarquest.entities.Quest; -import com.viadee.sonarquest.entities.User; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class QuestTest { @Test - public void testGetParticipants_noParticipants() throws Exception { + public void testGetParticipants_noParticipants() { Quest quest = new Quest(); List participants = quest.getParticipants(); assertEquals(Collections.emptyList(), participants); } @Test - public void testGetParticipants_twoParticipants() throws Exception { + public void testGetParticipants_twoParticipants() { // Given Quest quest = new Quest(); List participations = new ArrayList<>(); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java index 4c288766..89f655fb 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java @@ -1,19 +1,15 @@ package com.viadee.sonarquest.entities; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; +import com.viadee.sonarquest.repositories.UserRepository; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import com.viadee.sonarquest.repositories.UserRepository; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class UserDtoTest { - - @Autowired - private UserRepository userRepository ; - - @Test - public void testConstructUserDto() throws Exception { +public class UserDtoTest { + + @Test + public void testConstructUserDto() { // Given User user = new User(); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserTest.java index 31a76ddc..3f56099a 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserTest.java @@ -1,25 +1,27 @@ package com.viadee.sonarquest.entities; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class UserTest { @Test - public void testGetJoinedWorlds_noWorlds() throws Exception { + public void testGetJoinedWorlds_noWorlds() { User user = new User(); List joinedWorlds = user.getJoinedWorlds(); assertEquals(Collections.emptyList(), joinedWorlds); } @Test - public void testGetJoinedWorlds_twoActiveWorlds() throws Exception { + public void testGetJoinedWorlds_twoActiveWorlds() { // Given User user = new User(); List activeWorlds = new ArrayList<>(); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java index ae880455..ee902d4f 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java @@ -1,26 +1,23 @@ package com.viadee.sonarquest.externalressources; -import static org.junit.Assert.assertEquals; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.viadee.sonarquest.entities.SonarConfig; +import com.viadee.sonarquest.services.RestTemplateService; +import com.viadee.sonarquest.services.SonarConfigService; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; -import com.viadee.sonarquest.entities.SonarConfig; -import com.viadee.sonarquest.externalressources.SonarQubeApiCall; -import com.viadee.sonarquest.externalressources.SonarQubeComponentQualifier; -import com.viadee.sonarquest.externalressources.SonarQubeProjectRessource; -import com.viadee.sonarquest.services.RestTemplateService; -import com.viadee.sonarquest.services.SonarConfigService; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest -@Ignore +@Disabled public class SonarQubeApiCallIT { @Autowired @@ -30,7 +27,7 @@ public class SonarQubeApiCallIT { private SonarConfigService sonarConfigService; @Test - public void searchComponents() throws Exception { + public void searchComponents() { SonarConfig sonarConfig = sonarConfigService.getConfig(); String sonarQubeServerUrl = sonarConfig.getSonarServerUrl(); String projectKey = "assertj"; diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeSeverityTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeSeverityTest.java index 5952d3bf..1a95ac7e 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeSeverityTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeSeverityTest.java @@ -1,13 +1,14 @@ package com.viadee.sonarquest.externalressources; -import static org.junit.Assert.assertSame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertSame; public class SonarQubeSeverityTest { @Test - public void testFromString() throws Exception { + public void testFromString() { SonarQubeSeverity severity = SonarQubeSeverity.fromString("BLOCKER"); assertSame(SonarQubeSeverity.BLOCKER, severity); } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/IntegrationTests.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/IntegrationTests.java deleted file mode 100644 index e7b07a55..00000000 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/IntegrationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.viadee.sonarquest.integration; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - - -@RunWith(Suite.class) -@SuiteClasses({ SonarQuestApplicationIT.class, UserManagementIT.class }) - -public class IntegrationTests { - -} diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java index e628caba..ce2fa8d0 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java @@ -1,42 +1,33 @@ package com.viadee.sonarquest.integration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; import com.viadee.sonarquest.controllers.ParticipationController; import com.viadee.sonarquest.controllers.TaskController; -import com.viadee.sonarquest.entities.Level; -import com.viadee.sonarquest.entities.Participation; -import com.viadee.sonarquest.entities.Quest; -import com.viadee.sonarquest.entities.RoleName; -import com.viadee.sonarquest.entities.StandardTask; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.AvatarClassRepository; -import com.viadee.sonarquest.repositories.AvatarRaceRepository; -import com.viadee.sonarquest.repositories.LevelRepository; -import com.viadee.sonarquest.repositories.QuestRepository; -import com.viadee.sonarquest.repositories.StandardTaskRepository; -import com.viadee.sonarquest.repositories.TaskRepository; -import com.viadee.sonarquest.repositories.WorldRepository; +import com.viadee.sonarquest.entities.*; +import com.viadee.sonarquest.repositories.*; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; import com.viadee.sonarquest.services.LevelService; import com.viadee.sonarquest.services.RoleService; import com.viadee.sonarquest.services.StandardTaskService; import com.viadee.sonarquest.services.UserService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static org.springframework.test.util.AssertionErrors.assertEquals; +import static org.springframework.test.util.AssertionErrors.assertNotNull; +import static org.springframework.test.util.AssertionErrors.assertNull; +import static org.junit.jupiter.api.Assertions.assertTimeout; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest public class SonarQuestApplicationIT { @@ -94,57 +85,61 @@ public class SonarQuestApplicationIT { * environment including a simulated sonar server and database access. */ @Transactional - @Test(timeout = 1000000) // There is hardly any data to fetch - this should be quick, altough there are + @Test // There is hardly any data to fetch - this should be quick, altough there are // write operations included public void developersCanParticipateInQuestsAndIssues() { - final World discWorld = createWorld(); - Quest magicQuest = createQuest(discWorld); - User rinceWind = createUser(discWorld); - createInitialLevel(); - - // XXX add test for adventure-participation - - final Participation epicParticipation = participationController.createParticipation(() -> USERNAME, - magicQuest.getId()); - final List epicParticipations = new ArrayList<>(); - epicParticipations.add(epicParticipation); - magicQuest.setParticipations(epicParticipations); - magicQuest = questRepository.save(magicQuest); - - // User can participate in quest - assertNotNull("quest without any participations", magicQuest.getParticipations()); - final Participation activeParticipation = magicQuest.getParticipations().get(0); - assertNotNull("participation not added to quest", activeParticipation); - assertEquals("quest not properly mapped to quest participation", QUEST_NAME, - activeParticipation.getQuest().getTitle()); - assertEquals("user not properly mapped to participation", USERNAME, - activeParticipation.getUser().getUsername()); - - // User can work on task - StandardTask coerceDeathOutOfRetirementTask = createTask(discWorld, magicQuest); - coerceDeathOutOfRetirementTask = (StandardTask) taskController.addParticipation(() -> USERNAME, - coerceDeathOutOfRetirementTask.getId(), magicQuest.getId()); - - assertNotNull("task without any participations", coerceDeathOutOfRetirementTask.getParticipation()); - final Participation taskParticipation = coerceDeathOutOfRetirementTask.getParticipation(); - assertNotNull("participation not added to task", taskParticipation); - assertEquals("user not properly mapped to task participation", USERNAME, - taskParticipation.getUser().getUsername()); - - coerceDeathOutOfRetirementTask.setStatus(SonarQuestTaskStatus.SOLVED); - standardTaskService.updateStandardTask(coerceDeathOutOfRetirementTask); - - rinceWind = userService.findByUsername(USERNAME); - // since Rincewind is a magician he gets 2 extra gold coins for this task - assertEquals("reward: Gold not awarded to user", Long.valueOf(12l), rinceWind.getGold()); - assertEquals("reward: XP not awarded to user", coerceDeathOutOfRetirementTask.getXp(), rinceWind.getXp()); + assertTimeout(Duration.ofSeconds(1000), () -> { + final World discWorld = createWorld(); + Quest magicQuest = createQuest(discWorld); + User rinceWind; + createUser(discWorld); + createInitialLevel(); + + // XXX add test for adventure-participation + + final Participation epicParticipation = participationController.createParticipation(() -> USERNAME, + magicQuest.getId()); + final List epicParticipations = new ArrayList<>(); + epicParticipations.add(epicParticipation); + magicQuest.setParticipations(epicParticipations); + magicQuest = questRepository.save(magicQuest); + + // User can participate in quest + assertNotNull("quest without any participations", magicQuest.getParticipations()); + final Participation activeParticipation = magicQuest.getParticipations().get(0); + assertNotNull("participation not added to quest", activeParticipation); + assertEquals("quest not properly mapped to quest participation", QUEST_NAME, + activeParticipation.getQuest().getTitle()); + assertEquals("user not properly mapped to participation", USERNAME, + activeParticipation.getUser().getUsername()); + + // User can work on task + StandardTask coerceDeathOutOfRetirementTask = createTask(discWorld, magicQuest); + coerceDeathOutOfRetirementTask = (StandardTask) taskController.addParticipation(() -> USERNAME, + coerceDeathOutOfRetirementTask.getId(), magicQuest.getId()); + + assertNotNull("task without any participations", coerceDeathOutOfRetirementTask.getParticipation()); + final Participation taskParticipation = coerceDeathOutOfRetirementTask.getParticipation(); + assertNotNull("participation not added to task", taskParticipation); + assertEquals("user not properly mapped to task participation", USERNAME, + taskParticipation.getUser().getUsername()); + + coerceDeathOutOfRetirementTask.setStatus(SonarQuestTaskStatus.SOLVED); + standardTaskService.updateStandardTask(coerceDeathOutOfRetirementTask); + + rinceWind = userService.findByUsername(USERNAME); + // since Rincewind is a magician he gets 2 extra gold coins for this task + assertEquals("reward: Gold not awarded to user", 12L, rinceWind.getGold()); + assertEquals("reward: XP not awarded to user", coerceDeathOutOfRetirementTask.getXp(), rinceWind.getXp()); + }); + } private void createInitialLevel() { final Level level = new Level(); level.setLevelNumber(1); - level.setMinXp(0l); - level.setMaxXp(10l); + level.setMinXp(0L); + level.setMaxXp(10L); levelRepository.save(level); } @@ -168,7 +163,7 @@ private User createUser(final World discWorld) { user.setAvatarClass(avatarClassRepository.findByName(USER_AVATAR_CLASS)); user.setAvatarRace(avatarRaceRepository.findByName(USER_AVATAR_RACE)); user.setCurrentWorld(discWorld); - user.setLevel(levelService.getLevelByUserXp(0l)); + user.setLevel(levelService.getLevelByUserXp(0L)); return userService.save(user); } @@ -208,6 +203,7 @@ public void caseSensitiveTaskKeys() { assertNull("unexpected Task", standardTaskRepository.findByKey("AWc3A2KEoXX3DuVBrVTC")); standardTaskRepository.findAll().forEach(t -> System.out.println(">>>" + t.getId() + " " + t.getKey())); - assertNotNull(standardTaskRepository.findByKey("AWc3A2KEoXX3DuVBrVTc")); + Assertions.assertNotNull(standardTaskRepository.findByKey("AWc3A2KEoXX3DuVBrVTc")); + } } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java index 58310f94..0fd5d6f0 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java @@ -1,18 +1,18 @@ package com.viadee.sonarquest.integration; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; import com.viadee.sonarquest.entities.Role; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.services.UserService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.springframework.test.util.AssertionErrors.assertNotNull; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest public class UserManagementIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java index c5110498..6bbb3810 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQubeStatusMapperTest.java @@ -1,50 +1,50 @@ package com.viadee.sonarquest.rules; -import static org.junit.Assert.assertSame; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.runners.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class SonarQubeStatusMapperTest { @InjectMocks private SonarQubeStatusMapper mapper; @Test - public void testMapExternalStatus_Open() throws Exception { + public void testMapExternalStatus_Open() { IssueWithStatus issueWithStatus = issue("OPEN"); SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); } @Test - public void testMapExternalStatus_Reopen() throws Exception { + public void testMapExternalStatus_Reopen() { IssueWithStatus issueWithStatus = issue("REOPENED"); SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); } @Test - public void testMapExternalStatus_Confirmed() throws Exception { + public void testMapExternalStatus_Confirmed() { IssueWithStatus issueWithStatus = issue("CONFIRMED"); SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); } @Test - public void testMapExternalStatus_Closed() throws Exception { + public void testMapExternalStatus_Closed() { IssueWithStatus issueWithStatus = issue("CLOSED"); SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); assertSame(SonarQuestTaskStatus.SOLVED, sonarQuestTaskStatus); } @Test - public void testMapExternalStatus_Resolved_FalsePositive() throws Exception { + public void testMapExternalStatus_Resolved_FalsePositive() { IssueWithStatus issueWithStatus = issue("RESOLVED"); when(issueWithStatus.getResolution()).thenReturn("FALSE-POSITIVE"); SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); @@ -52,7 +52,7 @@ public void testMapExternalStatus_Resolved_FalsePositive() throws Exception { } @Test - public void testMapExternalStatus_Resolved() throws Exception { + public void testMapExternalStatus_Resolved() { IssueWithStatus issueWithStatus = issue("RESOLVED"); SonarQuestTaskStatus sonarQuestTaskStatus = mapper.mapExternalStatus(issueWithStatus); assertSame(SonarQuestTaskStatus.OPEN, sonarQuestTaskStatus); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestTaskStatusTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestTaskStatusTest.java index da052150..da8e9ea2 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestTaskStatusTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/rules/SonarQuestTaskStatusTest.java @@ -1,26 +1,22 @@ package com.viadee.sonarquest.rules; -import static org.junit.Assert.assertSame; +import org.junit.jupiter.api.Test; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; public class SonarQuestTaskStatusTest { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test - public void testFromStatusText() throws Exception { + public void testFromStatusText() { SonarQuestTaskStatus sonarQuestTaskStatus = SonarQuestTaskStatus.fromStatusText("SOLVED"); assertSame(SonarQuestTaskStatus.SOLVED, sonarQuestTaskStatus); } @Test - public void testFromStatusText_unknownStatusFail() throws Exception { - exception.expect(IllegalArgumentException.class); - SonarQuestTaskStatus.fromStatusText("UNMAPPED_STATUS"); + public void testFromStatusText_unknownStatusFail() { + assertThrows(IllegalArgumentException.class, () -> SonarQuestTaskStatus.fromStatusText("UNMAPPED_STATUS")); + } } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java index 6550f170..3805235e 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java @@ -1,33 +1,27 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - import com.viadee.sonarquest.entities.Adventure; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.entities.World; import com.viadee.sonarquest.repositories.AdventureRepository; -import com.viadee.sonarquest.repositories.ParticipationRepository; -import com.viadee.sonarquest.services.AdventureService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.ArrayList; +import java.util.List; -@RunWith(MockitoJUnitRunner.class) +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) public class AdventureServiceTest { @Mock private AdventureRepository adventureRepository; - @Mock - private ParticipationRepository participationRepository; - @InjectMocks private AdventureService adventureService; diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java index a7301a41..49bc9c27 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java @@ -1,19 +1,19 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertNotNull; -import javax.transaction.Transactional; - -import org.junit.Test; -import org.junit.runner.RunWith; +import com.viadee.sonarquest.entities.Artefact; +import com.viadee.sonarquest.entities.Level; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -import com.viadee.sonarquest.entities.Artefact; -import com.viadee.sonarquest.entities.Level; +import javax.transaction.Transactional; + +import static org.junit.jupiter.api.Assertions.assertNotNull; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest @Transactional public class ArtefactServiceIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java index 50d8a95c..4cea5c42 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java @@ -4,21 +4,21 @@ import com.viadee.sonarquest.entities.Level; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.repositories.ArtefactRepository; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ArtefactServiceTest { @InjectMocks diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java index 8b50242d..e5341c7c 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java @@ -1,41 +1,28 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import com.viadee.sonarquest.constants.QuestState; +import com.viadee.sonarquest.entities.*; +import com.viadee.sonarquest.repositories.EventRepository; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import javax.transaction.Transactional; import java.security.Principal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; -import javax.transaction.Transactional; - -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.viadee.sonarquest.constants.QuestState; -import com.viadee.sonarquest.entities.Event; -import com.viadee.sonarquest.entities.EventUserDto; -import com.viadee.sonarquest.entities.MessageDto; -import com.viadee.sonarquest.entities.Quest; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.entities.UserDto; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.EventRepository; -import com.viadee.sonarquest.repositories.UserRepository; +import static org.junit.jupiter.api.Assertions.*; @SpringBootTest -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @Transactional public class EventServiceIT { - - @Autowired - private UserRepository userRepository; @Autowired private EventService eventService; @@ -55,7 +42,7 @@ public void testServiceEvent() { List events1 = eventService.getLatestEvent(); // verify result - assertTrue(events1.get(0).equals(event1)); + assertEquals(events1.get(0), event1); Event event2 = new Event(); event2.setTimestamp(new Timestamp(System.currentTimeMillis())); @@ -84,7 +71,7 @@ public void testServiceEvent() { } @Test - public void testCreateEventForCreatedQuest_shortStory() throws Exception { + public void testCreateEventForCreatedQuest_shortStory() { // Given String longStory = createStoryWithLength(25); Quest quest = createQuest("A new quest in the land of Testiara!", longStory); @@ -98,7 +85,7 @@ public void testCreateEventForCreatedQuest_shortStory() throws Exception { } @Test - public void testCreateEventForCreatedQuest_storyMoreThen255CharsLong() throws Exception { + public void testCreateEventForCreatedQuest_storyMoreThen255CharsLong() { // Given String longStory = createStoryWithLength(300); Quest quest = createQuest("A new quest in the land of Testiara!", longStory); @@ -112,7 +99,7 @@ public void testCreateEventForCreatedQuest_storyMoreThen255CharsLong() throws Ex } @Test - public void testEventToEventUserDto() throws Exception { + public void testEventToEventUserDto() { User user1 = new User(); Event event1 = new Event(); event1.setUser(user1); @@ -190,13 +177,7 @@ private String createStoryWithLength(int storyLength) { } private Principal createPrincipal() { - return new Principal() { - - @Override - public String getName() { - return "admin"; - } - }; + return () -> "admin"; } private Quest createQuest(String title, String story) { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ExternalRessourceServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ExternalRessourceServiceTest.java index 2e101531..3bfe0c96 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ExternalRessourceServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ExternalRessourceServiceTest.java @@ -1,19 +1,22 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertEquals; + import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.StringUtils; -import org.junit.Test; + import com.viadee.sonarquest.externalressources.SonarQubeSeverity; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class ExternalRessourceServiceTest { @Test - public void sonarQubeIssuesWithSeverity_constructUrl() throws Exception { + public void sonarQubeIssuesWithSeverity_constructUrl() { List severities = Arrays.asList(SonarQubeSeverity.BLOCKER, SonarQubeSeverity.CRITICAL, SonarQubeSeverity.MAJOR); String sonarServerUrl = "http://www.fantasyurl.io:8080"; diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java index 799cfa34..5e80a50d 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java @@ -1,26 +1,24 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - import com.viadee.sonarquest.entities.Participation; import com.viadee.sonarquest.entities.Quest; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.entities.World; import com.viadee.sonarquest.repositories.ParticipationRepository; import com.viadee.sonarquest.repositories.QuestRepository; -import com.viadee.sonarquest.services.QuestService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class QuestServiceTest { @Mock diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java index c3b84ccc..82e2b869 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java @@ -1,17 +1,17 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Test; -import org.junit.runner.RunWith; +import com.viadee.sonarquest.entities.SonarConfig; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; -import com.viadee.sonarquest.entities.SonarConfig; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @SpringBootTest public class SonarConfigServiceTest { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java index ba8f15b8..1f11e359 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java @@ -1,35 +1,32 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; +import com.viadee.sonarquest.entities.StandardTask; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.externalressources.SonarQubeSeverity; +import com.viadee.sonarquest.repositories.StandardTaskRepository; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; -import com.viadee.sonarquest.entities.StandardTask; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.externalressources.SonarQubeSeverity; -import com.viadee.sonarquest.repositories.StandardTaskRepository; -import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class StandardTaskServiceTest { @Mock private StandardTaskRepository standardTaskRepository; - @Mock - private GratificationService gratificationService; - @Mock private NamedParameterJdbcTemplate template; @@ -41,12 +38,12 @@ public void testUpdateStandardTask() { StandardTask task = new StandardTask(); task.setKey("Color of Magic!"); task.setStatus(SonarQuestTaskStatus.OPEN); - when(standardTaskRepository.save(Matchers.any(StandardTask.class))).thenReturn(task); - when(standardTaskRepository.saveAndFlush(Matchers.any(StandardTask.class))).thenReturn(task); + when(standardTaskRepository.save(ArgumentMatchers.any(StandardTask.class))).thenReturn(task); + when(standardTaskRepository.saveAndFlush(ArgumentMatchers.any(StandardTask.class))).thenReturn(task); when(standardTaskRepository.findByKey(task.getKey())).thenReturn(task); - when(template.queryForObject(Matchers.anyString(), - Matchers.any(SqlParameterSource.class), - Matchers.>any())).thenReturn("OPEN"); + when(template.queryForObject(ArgumentMatchers.anyString(), + ArgumentMatchers.any(SqlParameterSource.class), + ArgumentMatchers.>any())).thenReturn("OPEN"); task = standardTaskService.updateStandardTask(task); @@ -66,14 +63,14 @@ public void testUpdateStandardTask() { } @Test - public void testGetLastState() throws Exception { + public void testGetLastState() { StandardTask task = new StandardTask(); SonarQuestTaskStatus lastState = standardTaskService.getLastState(task); assertEquals(SonarQuestTaskStatus.OPEN, lastState); } @Test - public void testFindByWorld() throws Exception { + public void testFindByWorld() { // Given World world = new World(); List unsortedTasks = new ArrayList<>(); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/WizardServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/WizardServiceTest.java index b7262976..97a8440c 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/WizardServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/WizardServiceTest.java @@ -1,22 +1,19 @@ package com.viadee.sonarquest.services; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; - -import org.junit.Test; -import org.junit.runner.RunWith; +import com.viadee.sonarquest.entities.WizardMessage; +import com.viadee.sonarquest.entities.World; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import com.viadee.sonarquest.entities.WizardMessage; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.services.WizardService; -import com.viadee.sonarquest.services.WorldService; +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class WizardServiceTest { @InjectMocks diff --git a/sonarQuest-frontend/karma.conf.js b/sonarQuest-frontend/karma.conf.js index 063e6789..10f56135 100644 --- a/sonarQuest-frontend/karma.conf.js +++ b/sonarQuest-frontend/karma.conf.js @@ -19,13 +19,13 @@ module.exports = function (config) { dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, - + reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], - singleRun: false + singleRun: true }); }; From fb4c254825a0012c443dd5641fb1a2d6ddd6466f Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Wed, 26 Feb 2020 12:49:21 +0100 Subject: [PATCH 07/17] Removed unnecessary test extensions --- sonarQuest-backend/pom.xml | 2 +- .../src/main/resources/application-prod.properties | 4 ++-- .../src/main/resources/application.properties | 7 ++++--- .../sonarquest/controllers/AdventureControllerTest.java | 2 -- .../controllers/login/LoginControllerIntegrationTest.java | 2 +- .../sonarquest/externalressources/SonarQubeApiCallIT.java | 1 - .../sonarquest/integration/SonarQuestApplicationIT.java | 1 - .../viadee/sonarquest/integration/UserManagementIT.java | 1 - .../com/viadee/sonarquest/services/ArtefactServiceIT.java | 1 - .../com/viadee/sonarquest/services/EventServiceIT.java | 1 - .../viadee/sonarquest/services/SonarConfigServiceTest.java | 1 - 11 files changed, 8 insertions(+), 15 deletions(-) diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index edb8fef7..14ecddfa 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -81,7 +81,7 @@ com.h2database h2 runtime - 1.4.199 + 1.4.197 org.projectlombok diff --git a/sonarQuest-backend/src/main/resources/application-prod.properties b/sonarQuest-backend/src/main/resources/application-prod.properties index 6849fd45..242a5101 100644 --- a/sonarQuest-backend/src/main/resources/application-prod.properties +++ b/sonarQuest-backend/src/main/resources/application-prod.properties @@ -22,8 +22,8 @@ spring.flyway.enabled=true spring.flyway.validate-on-migrate=true spring.flyway.clean-on-validation-error=false spring.flyway.baseline-on-migrate=true -spring.flyway.locations=db/schema,db/data -spring.flyway.baselineOnMigrate=true +spring.flyway.locations=classpath:db/schema,classpath:db/data +spring.flyway.check-location=false # ======================================== # HIBERNATE diff --git a/sonarQuest-backend/src/main/resources/application.properties b/sonarQuest-backend/src/main/resources/application.properties index d2670f5d..f45e9f9c 100644 --- a/sonarQuest-backend/src/main/resources/application.properties +++ b/sonarQuest-backend/src/main/resources/application.properties @@ -21,7 +21,7 @@ avatar.directory=/avatar/ # ======================================== # DATASOURCE # ======================================== -spring.datasource.url=jdbc:h2:file:./target/classes/db/sonarQuest;AUTO_SERVER=TRUE +spring.datasource.url=jdbc:h2:file:./target/classes/db/sonarQuest spring.datasource.platform=h2 spring.datasource.driverClassName=org.h2.Driver spring.jpa.database-platform=org.hibernate.dialect.H2Dialect @@ -34,8 +34,9 @@ spring.flyway.enabled=true spring.flyway.validate-on-migrate=true spring.flyway.clean-on-validation-error=true spring.flyway.baseline-on-migrate=true -spring.flyway.locations=db/schema,db/data -spring.flyway.baselineOnMigrate=true +spring.flyway.locations=classpath:db/schema,classpath:db/data +spring.flyway.check-location=false +spring.flyway.table=schema_version # ======================================== # HIBERNATE diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java index 919f6569..7fe5dbd0 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java @@ -14,8 +14,6 @@ import static org.junit.jupiter.api.Assertions.*; - -@ExtendWith(SpringExtension.class) @SpringBootTest @Transactional public class AdventureControllerTest { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java index 5cc0498f..baeeae56 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java @@ -9,7 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -@ExtendWith(SpringExtension.class) + @SpringBootTest public class LoginControllerIntegrationTest { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java index ee902d4f..130a3188 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java @@ -15,7 +15,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -@ExtendWith(SpringExtension.class) @SpringBootTest @Disabled public class SonarQubeApiCallIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java index ce2fa8d0..32b4b56d 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java @@ -27,7 +27,6 @@ import static org.springframework.test.util.AssertionErrors.assertNull; import static org.junit.jupiter.api.Assertions.assertTimeout; -@ExtendWith(SpringExtension.class) @SpringBootTest public class SonarQuestApplicationIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java index 0fd5d6f0..5a357b97 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java @@ -12,7 +12,6 @@ import static org.springframework.test.util.AssertionErrors.assertNotNull; -@ExtendWith(SpringExtension.class) @SpringBootTest public class UserManagementIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java index 49bc9c27..83a8b6a1 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java @@ -13,7 +13,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; -@ExtendWith(SpringExtension.class) @SpringBootTest @Transactional public class ArtefactServiceIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java index e5341c7c..de542117 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java @@ -20,7 +20,6 @@ import static org.junit.jupiter.api.Assertions.*; @SpringBootTest -@ExtendWith(SpringExtension.class) @Transactional public class EventServiceIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java index 82e2b869..f4c413ca 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java @@ -11,7 +11,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -@ExtendWith(SpringExtension.class) @SpringBootTest public class SonarConfigServiceTest { From 12444af5e07fc5ab4aaa561946639c053bb563d3 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Wed, 26 Feb 2020 16:43:20 +0100 Subject: [PATCH 08/17] removed unnecessary property --- sonarQuest-backend/src/main/resources/application.properties | 1 - 1 file changed, 1 deletion(-) diff --git a/sonarQuest-backend/src/main/resources/application.properties b/sonarQuest-backend/src/main/resources/application.properties index f45e9f9c..4dbb7fe0 100644 --- a/sonarQuest-backend/src/main/resources/application.properties +++ b/sonarQuest-backend/src/main/resources/application.properties @@ -36,7 +36,6 @@ spring.flyway.clean-on-validation-error=true spring.flyway.baseline-on-migrate=true spring.flyway.locations=classpath:db/schema,classpath:db/data spring.flyway.check-location=false -spring.flyway.table=schema_version # ======================================== # HIBERNATE From dd2bbb4c9644f8cd61d4338d5e26717bfb247d5c Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Wed, 26 Feb 2020 18:07:25 +0100 Subject: [PATCH 09/17] Updated to Flyway 4 --- sonarQuest-backend/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index 6ae71b6c..70e659db 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -116,6 +116,7 @@ org.flywaydb flyway-core + 4.2.0 org.springframework.boot From a47005978cb54943d557380e27736eb8c10b460e Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Fri, 6 Mar 2020 13:07:36 +0100 Subject: [PATCH 10/17] WIP Hibernate Exception --- .../FlywayUpdate3To4Callback.java | 67 +++++++++++++++++++ .../src/main/resources/application.properties | 4 +- .../flyway_upgradeMetaDataTable_V3_to_V4.sql | 7 ++ .../src/test/resources/application.properties | 11 ++- 4 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java create mode 100644 sonarQuest-backend/src/main/resources/db/migration/flyway_upgradeMetaDataTable_V3_to_V4.sql diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java new file mode 100644 index 00000000..5273832b --- /dev/null +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java @@ -0,0 +1,67 @@ +package com.viadee.sonarquest.configurations; + +import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE; + +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.callback.Callback; +import org.flywaydb.core.api.callback.Context; +import org.flywaydb.core.api.callback.Event; +import org.flywaydb.core.api.configuration.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.core.annotation.Order; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.jdbc.datasource.init.ScriptUtils; +import org.springframework.jdbc.support.JdbcUtils; +import org.springframework.jdbc.support.MetaDataAccessException; +import org.springframework.stereotype.Component; + +import lombok.extern.slf4j.Slf4j; + +@Component +@Order(HIGHEST_PRECEDENCE) +@Slf4j +public class FlywayUpdate3To4Callback implements Callback { + private final Flyway flyway; + + public FlywayUpdate3To4Callback(@Lazy Flyway flyway) { + this.flyway = flyway; + } + + private boolean checkColumnExists(Configuration flywayConfiguration) throws MetaDataAccessException { + return (boolean) JdbcUtils.extractDatabaseMetaData(flywayConfiguration.getDataSource(), + callback -> callback + .getColumns(null, null, flywayConfiguration.getTable(), "version_rank") + .next()); + } + + @Override + public boolean supports(Event event, Context context) { + return event == Event.BEFORE_VALIDATE; + } + + @Override + public boolean canHandleInTransaction(Event event, Context context) { + return false; + } + + @Override + public void handle(Event event, Context context) { + boolean versionRankColumnExists = false; + try { + versionRankColumnExists = checkColumnExists(context.getConfiguration()); + } catch (MetaDataAccessException e) { + log.error("Cannot obtain flyway metadata"); + return; + } + if (versionRankColumnExists) { + log.info("Upgrading metadata table the Flyway 4.0 format ..."); + Resource resource = new ClassPathResource("db/migration/flyway_upgradeMetaDataTable_V3_to_V4.sql", + Thread.currentThread().getContextClassLoader()); + ScriptUtils.executeSqlScript(context.getConnection(), resource); + log.info("Flyway metadata table updated successfully."); + // recalculate checksums + flyway.repair(); + } + } +} diff --git a/sonarQuest-backend/src/main/resources/application.properties b/sonarQuest-backend/src/main/resources/application.properties index 4dbb7fe0..bcf0d852 100644 --- a/sonarQuest-backend/src/main/resources/application.properties +++ b/sonarQuest-backend/src/main/resources/application.properties @@ -30,16 +30,18 @@ spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # ======================================== # FLYWAY # ======================================== -spring.flyway.enabled=true +spring.flyway.enabled=false spring.flyway.validate-on-migrate=true spring.flyway.clean-on-validation-error=true spring.flyway.baseline-on-migrate=true spring.flyway.locations=classpath:db/schema,classpath:db/data spring.flyway.check-location=false +spring.flyway.table=schema_version # ======================================== # HIBERNATE # ======================================== +spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=validate spring.jpa.properties.hibernate.show_sql=false spring.jpa.properties.hibernate.use_sql_comments=false diff --git a/sonarQuest-backend/src/main/resources/db/migration/flyway_upgradeMetaDataTable_V3_to_V4.sql b/sonarQuest-backend/src/main/resources/db/migration/flyway_upgradeMetaDataTable_V3_to_V4.sql new file mode 100644 index 00000000..ee2b8eb1 --- /dev/null +++ b/sonarQuest-backend/src/main/resources/db/migration/flyway_upgradeMetaDataTable_V3_to_V4.sql @@ -0,0 +1,7 @@ +DROP INDEX "${schema}"."${table}_vr_idx"; +DROP INDEX "${schema}"."${table}_ir_idx"; +ALTER TABLE "${schema}"."${table}" DROP COLUMN "version_rank"; +ALTER TABLE "${schema}"."${table}" DROP CONSTRAINT "${table}_pk"; +ALTER TABLE "${schema}"."${table}" ALTER COLUMN "version" SET NULL; +ALTER TABLE "${schema}"."${table}" ADD CONSTRAINT "${table}_pk" PRIMARY KEY ("installed_rank"); +UPDATE "${schema}"."${table}" SET "type"='BASELINE' WHERE "type"='INIT'; \ No newline at end of file diff --git a/sonarQuest-backend/src/test/resources/application.properties b/sonarQuest-backend/src/test/resources/application.properties index 4f40d55f..5bb05552 100644 --- a/sonarQuest-backend/src/test/resources/application.properties +++ b/sonarQuest-backend/src/test/resources/application.properties @@ -29,12 +29,11 @@ spring.jpa.database-platform=org.hibernate.dialect.H2Dialect # ======================================== # FLYWAY # ======================================== -flyway.enabled=true -flyway.validate-on-migrate=true -flyway.clean-on-validation-error=true -flyway.baseline-on-migrate=true -flyway.locations=db/schema,db/data -flyway.baselineOnMigrate=true +spring.flyway.enabled=true +spring.flyway.validate-on-migrate=true +spring.flyway.clean-on-validation-error=true +spring.flyway.baseline-on-migrate=true +spring.flyway.locations=classpath:db/schema,classpath:db/data # ======================================== # HIBERNATE From 4e058b85ffbac704d7a84eca7710ef19e85b9fd8 Mon Sep 17 00:00:00 2001 From: Brown Date: Fri, 6 Mar 2020 16:29:07 +0100 Subject: [PATCH 11/17] Update Sonarquest Backend to Spring Boot 2.2.5 and Java 11. --- sonarQuest-backend/pom.xml | 12 +- .../FlywayUpdate3To4Callback.java | 14 +- .../controllers/ArtefactController.java | 7 +- .../controllers/AvatarClassController.java | 5 +- .../controllers/AvatarRaceController.java | 5 +- .../controllers/LevelController.java | 7 +- .../controllers/SkillController.java | 20 +- .../controllers/SonarConfigController.java | 3 +- .../controllers/UiDesignController.java | 3 +- .../controllers/UserToWorldController.java | 31 +- .../controllers/WizardController.java | 27 +- .../controllers/WorldController.java | 34 +- .../viadee/sonarquest/entities/Adventure.java | 7 +- .../viadee/sonarquest/entities/Artefact.java | 6 +- .../sonarquest/entities/AvatarClass.java | 7 +- .../sonarquest/entities/AvatarRace.java | 7 +- .../com/viadee/sonarquest/entities/Event.java | 23 +- .../com/viadee/sonarquest/entities/Level.java | 4 +- .../sonarquest/entities/Participation.java | 7 +- .../sonarquest/entities/Permission.java | 4 +- .../com/viadee/sonarquest/entities/Quest.java | 4 +- .../com/viadee/sonarquest/entities/Role.java | 4 +- .../com/viadee/sonarquest/entities/Skill.java | 4 +- .../sonarquest/entities/SonarConfig.java | 3 +- .../sonarquest/entities/SpecialTask.java | 7 +- .../sonarquest/entities/StandardTask.java | 9 +- .../com/viadee/sonarquest/entities/Task.java | 4 +- .../viadee/sonarquest/entities/UiDesign.java | 5 +- .../com/viadee/sonarquest/entities/User.java | 35 +- .../entities/UserToWorldConnection.java | 10 + .../com/viadee/sonarquest/entities/World.java | 22 +- .../externalressources/SonarQubeApiCall.java | 41 +- .../repositories/AdventureRepository.java | 3 - .../viadee/sonarquest/security/JwtHelper.java | 10 +- .../sonarquest/services/AdventureService.java | 44 +- .../sonarquest/services/EventService.java | 155 +++---- .../services/ExternalRessourceService.java | 52 ++- .../services/ParticipationService.java | 23 +- .../sonarquest/services/RoleService.java | 3 +- .../sonarquest/services/SkillService.java | 7 +- .../services/SonarConfigService.java | 10 +- .../services/SpecialTaskService.java | 12 +- .../sonarquest/services/UiDesignService.java | 3 +- .../sonarquest/services/UserService.java | 398 +++++++++--------- .../sonarquest/services/WizardService.java | 19 +- .../sonarquest/services/WorldService.java | 23 +- .../src/main/resources/application.properties | 7 +- .../controllers/AdventureControllerTest.java | 29 +- .../login/LoginControllerIntegrationTest.java | 7 +- .../sonarquest/entities/UserDtoTest.java | 14 +- .../SonarQubeApiCallIT.java | 20 +- .../integration/SonarQuestApplicationIT.java | 58 +-- .../integration/UserManagementIT.java | 10 +- .../services/AdventureServiceTest.java | 21 +- .../services/ArtefactServiceIT.java | 25 +- .../sonarquest/services/EventServiceIT.java | 129 +++--- .../services/SonarConfigServiceTest.java | 8 +- .../services/StandardTaskServiceTest.java | 36 +- .../src/app/services/world.service.ts | 20 +- 59 files changed, 818 insertions(+), 709 deletions(-) create mode 100644 sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldConnection.java diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index 6dadccdc..7db0a8e2 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -28,14 +28,14 @@ org.springframework.boot spring-boot-starter-parent - 2.2.4.RELEASE + 2.2.5.RELEASE UTF-8 UTF-8 - 1.8 + 1.11 Hoxton.SR1 @@ -72,12 +72,6 @@ org.springframework.cloud spring-cloud-starter-sleuth - - org.springframework.boot - spring-boot-devtools - runtime - true - com.h2database h2 @@ -112,7 +106,6 @@ org.apache.commons commons-lang3 - 3.9 org.apache.commons @@ -127,7 +120,6 @@ org.apache.httpcomponents httpclient - 4.5.2 commons-io diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java index 5273832b..96861291 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/configurations/FlywayUpdate3To4Callback.java @@ -24,11 +24,11 @@ public class FlywayUpdate3To4Callback implements Callback { private final Flyway flyway; - public FlywayUpdate3To4Callback(@Lazy Flyway flyway) { + public FlywayUpdate3To4Callback(@Lazy final Flyway flyway) { this.flyway = flyway; } - private boolean checkColumnExists(Configuration flywayConfiguration) throws MetaDataAccessException { + private boolean checkColumnExists(final Configuration flywayConfiguration) throws MetaDataAccessException { return (boolean) JdbcUtils.extractDatabaseMetaData(flywayConfiguration.getDataSource(), callback -> callback .getColumns(null, null, flywayConfiguration.getTable(), "version_rank") @@ -36,27 +36,27 @@ private boolean checkColumnExists(Configuration flywayConfiguration) throws Meta } @Override - public boolean supports(Event event, Context context) { + public boolean supports(final Event event, final Context context) { return event == Event.BEFORE_VALIDATE; } @Override - public boolean canHandleInTransaction(Event event, Context context) { + public boolean canHandleInTransaction(final Event event, final Context context) { return false; } @Override - public void handle(Event event, Context context) { + public void handle(final Event event, final Context context) { boolean versionRankColumnExists = false; try { versionRankColumnExists = checkColumnExists(context.getConfiguration()); - } catch (MetaDataAccessException e) { + } catch (final MetaDataAccessException e) { log.error("Cannot obtain flyway metadata"); return; } if (versionRankColumnExists) { log.info("Upgrading metadata table the Flyway 4.0 format ..."); - Resource resource = new ClassPathResource("db/migration/flyway_upgradeMetaDataTable_V3_to_V4.sql", + final Resource resource = new ClassPathResource("db/migration/flyway_upgradeMetaDataTable_V3_to_V4.sql", Thread.currentThread().getContextClassLoader()); ScriptUtils.executeSqlScript(context.getConnection(), resource); log.info("Flyway metadata table updated successfully."); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java index 8ae0ace9..bf662b9f 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/ArtefactController.java @@ -3,8 +3,6 @@ import java.security.Principal; import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; @@ -18,7 +16,6 @@ import com.viadee.sonarquest.entities.Artefact; import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.repositories.ArtefactRepository; import com.viadee.sonarquest.services.ArtefactService; import com.viadee.sonarquest.services.UserService; @@ -32,7 +29,7 @@ public class ArtefactController { private final WebSocketController webSocketController; - public ArtefactController(ArtefactService artefactService, UserService userService, WebSocketController webSocketController) { + public ArtefactController(final ArtefactService artefactService, final UserService userService, final WebSocketController webSocketController) { this.artefactService = artefactService; this.userService = userService; this.webSocketController = webSocketController; @@ -62,7 +59,7 @@ public Artefact createArtefact(final Principal principal, @RequestBody final Art @PutMapping(value = "/{artefactId}") public Artefact updateArtefact(final Principal principal, @PathVariable(value = "artefactId") final Long artefactId, @RequestBody final Artefact artefact) { - Artefact savedArtefact = artefactService.updateArtefact(artefactId, artefact); + final Artefact savedArtefact = artefactService.updateArtefact(artefactId, artefact); webSocketController.onUpdateArtefact(artefact, principal); return savedArtefact; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java index 71e53c56..0a4882ed 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarClassController.java @@ -2,7 +2,6 @@ import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; @@ -24,7 +23,7 @@ public class AvatarClassController { private final AvatarClassRepository avatarClassRepository; - public AvatarClassController(AvatarClassRepository avatarClassRepository) { + public AvatarClassController(final AvatarClassRepository avatarClassRepository) { this.avatarClassRepository = avatarClassRepository; } @@ -48,7 +47,7 @@ public AvatarClass createAvatarClass(@RequestBody final AvatarClass avatarClass) @PutMapping(value = "/{id}") public AvatarClass updateAvatarClass(@PathVariable(value = "id") final Long avatarClassId, @RequestBody final AvatarClass avatarClassInput) { - AvatarClass avatarClass = avatarClassRepository.findById(avatarClassId).orElseThrow(ResourceNotFoundException::new); + final AvatarClass avatarClass = avatarClassRepository.findById(avatarClassId).orElseThrow(ResourceNotFoundException::new); avatarClass.setName(avatarClassInput.getName()); avatarClass.setSkills(avatarClassInput.getSkills()); return avatarClassRepository.save(avatarClass); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java index fcdcc5ce..8a1e4dd8 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/AvatarRaceController.java @@ -2,7 +2,6 @@ import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; @@ -24,7 +23,7 @@ public class AvatarRaceController { private final AvatarRaceRepository avatarRaceRepository; - public AvatarRaceController(AvatarRaceRepository avatarRaceRepository) { + public AvatarRaceController(final AvatarRaceRepository avatarRaceRepository) { this.avatarRaceRepository = avatarRaceRepository; } @@ -47,7 +46,7 @@ public AvatarRace createAvatarRace(@RequestBody final AvatarRace avatarRace) { @PutMapping(value = "/{id}") public AvatarRace updateAvatarRace(@PathVariable(value = "id") final Long avatarRaceId, @RequestBody final AvatarRace avatarRaceInput) { - AvatarRace avatarRace = avatarRaceRepository.findById(avatarRaceId).orElseThrow(ResourceNotFoundException::new); + final AvatarRace avatarRace = avatarRaceRepository.findById(avatarRaceId).orElseThrow(ResourceNotFoundException::new); avatarRace.setName(avatarRaceInput.getName()); return avatarRaceRepository.save(avatarRace); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java index d802f7af..9345d07d 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/LevelController.java @@ -2,22 +2,21 @@ import java.util.List; -import com.viadee.sonarquest.services.LevelService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.viadee.sonarquest.entities.Level; -import com.viadee.sonarquest.repositories.LevelRepository; +import com.viadee.sonarquest.services.LevelService; @RestController @RequestMapping("/level") public class LevelController { - private LevelService levelService; + private final LevelService levelService; - public LevelController(LevelService levelService) { + public LevelController(final LevelService levelService) { this.levelService = levelService; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java index 352684a2..b0c0a7a2 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SkillController.java @@ -1,12 +1,20 @@ package com.viadee.sonarquest.controllers; -import com.viadee.sonarquest.entities.Skill; -import com.viadee.sonarquest.services.ArtefactService; -import com.viadee.sonarquest.services.SkillService; +import java.util.List; + import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; +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.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; -import java.util.List; +import com.viadee.sonarquest.entities.Skill; +import com.viadee.sonarquest.services.SkillService; @RestController @RequestMapping("/skill") @@ -14,7 +22,7 @@ public class SkillController { private final SkillService skillService; - public SkillController(SkillService skillService) { + public SkillController(final SkillService skillService) { this.skillService = skillService; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java index ed6612a7..16123e95 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/SonarConfigController.java @@ -2,7 +2,6 @@ import javax.validation.Valid; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -18,7 +17,7 @@ public class SonarConfigController { private final SonarConfigService sonarConfigService; - public SonarConfigController(SonarConfigService sonarConfigService) { + public SonarConfigController(final SonarConfigService sonarConfigService) { this.sonarConfigService = sonarConfigService; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java index 1ef8ebb9..c41eb27a 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UiDesignController.java @@ -2,7 +2,6 @@ import java.security.Principal; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -26,7 +25,7 @@ public class UiDesignController { private final UiDesignRepository uiDesignRepository; - public UiDesignController(UiDesignService uiDesignService, UserService userService, UiDesignRepository uiDesignRepository) { + public UiDesignController(final UiDesignService uiDesignService, final UserService userService, final UiDesignRepository uiDesignRepository) { this.uiDesignService = uiDesignService; this.userService = userService; this.uiDesignRepository = uiDesignRepository; diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UserToWorldController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UserToWorldController.java index 91d5d2fd..34d8a14a 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UserToWorldController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/UserToWorldController.java @@ -1,27 +1,48 @@ package com.viadee.sonarquest.controllers; import java.util.List; +import java.util.stream.Collectors; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.viadee.sonarquest.entities.UserToWorldConnection; import com.viadee.sonarquest.entities.UserToWorldDto; import com.viadee.sonarquest.services.UserService; +import com.viadee.sonarquest.services.WorldService; @RestController @RequestMapping("/user_to_world") public class UserToWorldController { - @Autowired - private UserService userService; - + private final UserService userService; + + private final WorldService worldService; + + public UserToWorldController(final UserService userService, final WorldService worldService) { + this.userService = userService; + this.worldService = worldService; + } + @PreAuthorize("hasAuthority('USER_WORLD_ASSIGNMENT')") @PutMapping(value = "/update") public Boolean updateUserToWorld(@RequestBody final List userToWorlds) { - return userService.updateUserToWorld(userToWorlds); + final List userToWorldConnections = userToWorlds.stream() + .map(this::toUserToWorldConnection) + .collect(Collectors.toList()); + userService.updateUserToWorld(userToWorldConnections); + // TODO Prüfen, warum ein Boolean erwartet wird + return true; + } + + private UserToWorldConnection toUserToWorldConnection(final UserToWorldDto userToWorldDto) { + final UserToWorldConnection connection = new UserToWorldConnection(); + connection.setJoined(userToWorldDto.getJoined()); + connection.setUser(userService.findById(userToWorldDto.getUserId())); + connection.setWorld(worldService.findById(userToWorldDto.getWorldId())); + return connection; } } \ No newline at end of file diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java index 65f1450b..dd88c70e 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WizardController.java @@ -1,34 +1,29 @@ package com.viadee.sonarquest.controllers; -import java.util.Optional; - -import com.viadee.sonarquest.services.WorldService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.viadee.sonarquest.entities.WizardMessage; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.WorldRepository; import com.viadee.sonarquest.services.WizardService; +import com.viadee.sonarquest.services.WorldService; @RestController @RequestMapping("/wizard") public class WizardController { - private final WizardService wizardService; + private final WizardService wizardService; - private final WorldService worldService; + private final WorldService worldService; - public WizardController(WizardService wizardService, WorldService worldService) { - this.wizardService = wizardService; - this.worldService = worldService; - } + public WizardController(final WizardService wizardService, final WorldService worldService) { + this.wizardService = wizardService; + this.worldService = worldService; + } - @GetMapping(value = { "/world/{id}", "/world" }) - public WizardMessage getWizardMessageForWorld(@PathVariable(value = "id") final Long worldId) { - return wizardService.getMostImportantMessageFor(worldService.findById(worldId)); - } + @GetMapping(value = { "/world/{id}", "/world" }) + public WizardMessage getWizardMessageForWorld(@PathVariable(value = "id", required = false) final Long worldId) { + return wizardService.getMostImportantMessageFor(worldService.findById(worldId)); + } } \ No newline at end of file diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java index f276afe7..794cc8e0 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/controllers/WorldController.java @@ -3,7 +3,6 @@ import java.security.Principal; import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -15,6 +14,8 @@ import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.services.ExternalRessourceService; +import com.viadee.sonarquest.services.StandardTaskService; import com.viadee.sonarquest.services.UserService; import com.viadee.sonarquest.services.WorldService; @@ -22,11 +23,21 @@ @RequestMapping("/world") public class WorldController { - @Autowired - private UserService userService; + private final UserService userService; - @Autowired - private WorldService worldService; + private final WorldService worldService; + + private final StandardTaskService standardTaskService; + + private final ExternalRessourceService externalRessourceService; + + public WorldController(final UserService userService, final WorldService worldService, + final StandardTaskService standardTaskService, final ExternalRessourceService externalRessourceService) { + this.userService = userService; + this.worldService = worldService; + this.standardTaskService = standardTaskService; + this.externalRessourceService = externalRessourceService; + } @GetMapping(value = "/current") public World getCurrentWorld(final Principal principal) { @@ -37,7 +48,10 @@ public World getCurrentWorld(final Principal principal) { @PostMapping(value = "/current") public World setCurrentWorld(final Principal principal, @RequestBody final World world) { final User user = userService.findByUsername(principal.getName()); - return userService.updateUsersCurrentWorld(user, world.getId()); + final World currentWorld = worldService.findById(world.getId()); + user.setCurrentWorld(currentWorld); + user.setLastTavernVisit(null); + return userService.updateUser(user).getCurrentWorld(); } @GetMapping(value = "/worlds") @@ -66,7 +80,10 @@ public World getWorldById(@PathVariable(value = "id") final Long id) { @PreAuthorize("hasAuthority('FULL_WORLD_ACCESS')") @PostMapping(value = "/world") public World updateWorld(@RequestBody final World data) { - return worldService.updateWorld(data); + final World world = worldService.updateWorld(data); + // TODO Der Name ist recht unpassend + standardTaskService.updateStandardTasks(world); + return world; } @PreAuthorize("hasAuthority('ACTIVE_WORLD_ACCESS')") @@ -83,7 +100,8 @@ public World updateBackground(@PathVariable(value = "id") final Long id, @Reques @PreAuthorize("hasAuthority('FULL_WORLD_ACCESS')") @GetMapping(value = "/generate") public List generateWorlds() { - worldService.retrieveExternalWorlds(); + final List externalWorlds = externalRessourceService.generateWorldsFromSonarQubeProjects(); + worldService.saveWorlds(externalWorlds); return worldService.findAll(); } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java index 05968cf3..f2a214f8 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java @@ -10,6 +10,7 @@ import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; @@ -17,11 +18,11 @@ import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; -import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.AdventureState; -import lombok.*; + +import lombok.Data; @Data @Entity @@ -29,7 +30,7 @@ public class Adventure { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "startdate") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java index 412b8575..57a38f3b 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Artefact.java @@ -6,6 +6,7 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; @@ -14,7 +15,8 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.*; + +import lombok.Data; @Data @Entity @@ -22,7 +24,7 @@ public class Artefact { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java index eeb885cc..ab6096ae 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarClass.java @@ -6,6 +6,7 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; @@ -14,7 +15,9 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.*; + +import lombok.Data; +import lombok.NoArgsConstructor; @Data @NoArgsConstructor @@ -23,7 +26,7 @@ public class AvatarClass { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java index 0d3864db..ccb67610 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/AvatarRace.java @@ -6,12 +6,15 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.*; + +import lombok.Data; +import lombok.NoArgsConstructor; @NoArgsConstructor @Data @@ -20,7 +23,7 @@ public class AvatarRace { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java index eb33d319..70ecb28a 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Event.java @@ -5,6 +5,7 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @@ -12,7 +13,9 @@ import com.viadee.sonarquest.constants.EventState; import com.viadee.sonarquest.constants.EventType; -import lombok.*; + +import lombok.Data; +import lombok.NoArgsConstructor; @Data @Entity @@ -21,7 +24,7 @@ public class Event { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "type") @@ -53,12 +56,12 @@ public class Event { @Column(name = "timestamp") private Timestamp timestamp; - public Event(String title) { + public Event(final String title) { this.title = title; } - public Event(EventType type, String title, String story, EventState state, String image, World world, - String headline) { + public Event(final EventType type, final String title, final String story, final EventState state, final String image, final World world, + final String headline) { this.type = type; this.title = title; this.story = story; @@ -69,8 +72,8 @@ public Event(EventType type, String title, String story, EventState state, Strin this.headline = headline; } - public Event(EventType type, String title, String story, EventState state, String image, World world, - String headline, User user) { + public Event(final EventType type, final String title, final String story, final EventState state, final String image, final World world, + final String headline, final User user) { this.type = type; this.title = title; this.story = story; @@ -82,7 +85,7 @@ public Event(EventType type, String title, String story, EventState state, Strin this.user = user; } - public Event(EventType type, String title, String story, EventState state, World world, String headline) { + public Event(final EventType type, final String title, final String story, final EventState state, final World world, final String headline) { this.type = type; this.title = title; this.story = story; @@ -92,7 +95,7 @@ public Event(EventType type, String title, String story, EventState state, World this.headline = headline; } - public Event(EventType type, String story, World world, User user) { + public Event(final EventType type, final String story, final World world, final User user) { this.type = type; this.story = story; this.world = world; @@ -101,7 +104,7 @@ public Event(EventType type, String story, World world, User user) { timestamp = new Timestamp(System.currentTimeMillis()); } - public Event(EventType type, String title, String story, EventState state, String image, User user) { + public Event(final EventType type, final String title, final String story, final EventState state, final String image, final User user) { this.type = type; this.story = story; this.title = title; diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java index 00cc89b9..b8f9a433 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Level.java @@ -5,11 +5,13 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; + import lombok.Data; @Data @@ -18,7 +20,7 @@ public class Level { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "sqlevel") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java index 3384435b..01e8864d 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Participation.java @@ -1,25 +1,26 @@ package com.viadee.sonarquest.entities; -import lombok.Data; - import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; +import lombok.Data; + @Data @Entity @Table(name = "Participation") public class Participation { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy = "participation", cascade = CascadeType.ALL) diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java index 9d6b2e57..0edc153c 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Permission.java @@ -8,6 +8,7 @@ import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; @@ -16,6 +17,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.PermissionType; + import lombok.Data; @Data @@ -25,7 +27,7 @@ public class Permission { @JsonIgnore @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(EnumType.STRING) diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java index 29eef6c7..e8006308 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Quest.java @@ -11,6 +11,7 @@ import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @@ -19,6 +20,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.QuestState; + import lombok.Data; @Data @@ -27,7 +29,7 @@ public class Quest { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "startdate") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java index 7991cdc3..094e0d19 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Role.java @@ -8,6 +8,7 @@ import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; @@ -15,6 +16,7 @@ import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; + import lombok.Data; @Data @@ -24,7 +26,7 @@ public class Role { @JsonIgnore @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(EnumType.STRING) diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java index 26a86781..2e692e47 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Skill.java @@ -8,12 +8,14 @@ import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.constants.SkillType; + import lombok.Data; @Data @@ -22,7 +24,7 @@ public class Skill { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SonarConfig.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SonarConfig.java index 311de6ce..a9244384 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SonarConfig.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SonarConfig.java @@ -3,6 +3,7 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; @@ -17,7 +18,7 @@ public class SonarConfig { @JsonIgnore @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java index 8c7393fa..8115192a 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/SpecialTask.java @@ -5,9 +5,12 @@ import javax.persistence.Entity; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; -import lombok.Data; -@Data +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter @Entity @DiscriminatorValue("SPECIAL") public class SpecialTask extends Task { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java index 3c5993f7..6dc6dd5e 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/StandardTask.java @@ -5,9 +5,12 @@ import javax.persistence.Entity; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; -import lombok.Data; -@Data +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter @Entity @DiscriminatorValue("STANDARD") public class StandardTask extends Task { @@ -37,7 +40,7 @@ public StandardTask(final String title, final SonarQuestTaskStatus status, final final Quest quest, final World world, final String key, final String component, final String severity, final String type, final Integer debt, - final String issueKey, String issueRule) { + final String issueKey, final String issueRule) { setTitle(title); setStatus(status); setGold(gold); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java index 2e8570b7..894d882d 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Task.java @@ -9,6 +9,7 @@ import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; @@ -18,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; + import lombok.Data; @Data @@ -28,7 +30,7 @@ public class Task { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "startdate") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java index a64640b4..ddbc4fa9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UiDesign.java @@ -5,14 +5,15 @@ import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; + import lombok.Data; -import lombok.EqualsAndHashCode; @Data @Entity @@ -20,7 +21,7 @@ public class UiDesign { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Enumerated(EnumType.STRING) diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java index 8875dcaa..024577b4 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/User.java @@ -1,22 +1,37 @@ package com.viadee.sonarquest.entities; -import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.EqualsAndHashCode; -import org.apache.commons.lang3.Validate; - -import javax.persistence.*; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +import org.apache.commons.lang3.Validate; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import lombok.EqualsAndHashCode; + @EqualsAndHashCode @Entity @Table(name = "SQUser") public class User { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "username") @@ -109,7 +124,7 @@ public String getMail() { return mail; } - public void setMail(String mail) { + public void setMail(final String mail) { this.mail = mail; } @@ -179,7 +194,7 @@ public void setXp(final Long xp) { /** * Adds the specified amount of gold. - * + * * @param gold * the amount to add, must be positive or zero. */ @@ -190,7 +205,7 @@ public void addGold(final long gold) { /** * Adds the specified amount of XPerience Points. - * + * * @param xp * the amount to add, must be positive or zero. */ @@ -287,7 +302,7 @@ public Timestamp getLastTavernVisit() { return lastTavernVisit; } - public void setLastTavernVisit(Timestamp lastTavernVisit) { + public void setLastTavernVisit(final Timestamp lastTavernVisit) { this.lastTavernVisit = lastTavernVisit; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldConnection.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldConnection.java new file mode 100644 index 00000000..39d8e326 --- /dev/null +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/UserToWorldConnection.java @@ -0,0 +1,10 @@ +package com.viadee.sonarquest.entities; + +import lombok.Data; + +@Data +public class UserToWorldConnection { + private Boolean joined; + private User user; + private World world; +} diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java index 6d9fb479..67c6e590 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/World.java @@ -1,10 +1,22 @@ package com.viadee.sonarquest.entities; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.OneToMany; +import javax.persistence.Table; + import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.Data; -import javax.persistence.*; -import java.util.List; +import lombok.Data; @Data @Entity @@ -12,13 +24,13 @@ public class World { @Id - @GeneratedValue + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; - @Column(name = "project") + @Column(name = "project", unique = true) private String project; @Column(name = "image") diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java index aab623bd..33a81853 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/externalressources/SonarQubeApiCall.java @@ -15,7 +15,7 @@ public class SonarQubeApiCall { private String sonarQubeRestApiCall; - private void appendSearchParameter(String parameter) { + private void appendSearchParameter(final String parameter) { if (!sonarQubeRestApiCall.endsWith("?")) { sonarQubeRestApiCall += "&"; } @@ -25,12 +25,13 @@ private void appendSearchParameter(String parameter) { /** * Initializes a new Ressources Object (all values reset) and sets the server URL as a basis for a new REST API * Call. - * - * @param sonarQubeServerUrl THe URL of the Sonar Qube server to be contacted + * + * @param sonarQubeServerUrl + * THe URL of the Sonar Qube server to be contacted * @return the new instance */ - public static SonarQubeApiCall onServer(String sonarQubeServerUrl) { - SonarQubeApiCall ressource = new SonarQubeApiCall(); + public static SonarQubeApiCall onServer(final String sonarQubeServerUrl) { + final SonarQubeApiCall ressource = new SonarQubeApiCall(); ressource.sonarQubeRestApiCall = sonarQubeServerUrl; return ressource; } @@ -38,7 +39,7 @@ public static SonarQubeApiCall onServer(String sonarQubeServerUrl) { /** * Appends the call for the search issues function (e.g. /api/issues/search? ) in the SonarQube REST API to the * sonarQubeRestApiCall. - * + * * @see https://sonarcloud.io/web_api/api/issues */ public SonarQubeApiCall searchIssues() { @@ -49,13 +50,13 @@ public SonarQubeApiCall searchIssues() { /** * Appends the call for the search components function (e.g. /api/components/search? ) in the SonarQube REST API to * the sonarQubeRestApiCall. - * + * * @param qualifier * _required_ - the Qualifier to search for (e.g. TRK for "projects") - * + * * @see https://sonarcloud.io/web_api/api/components */ - public SonarQubeApiCall searchComponents(SonarQubeComponentQualifier qualifier) { + public SonarQubeApiCall searchComponents(final SonarQubeComponentQualifier qualifier) { sonarQubeRestApiCall += "/api/components/search?"; withQualifiers(qualifier); return this; @@ -64,7 +65,7 @@ public SonarQubeApiCall searchComponents(SonarQubeComponentQualifier qualifier) /** * Appends the parameter "componentKeys" with the value projectKey to the sonarQubeRestApiCall. */ - public SonarQubeApiCall withComponentKeys(String projectKey) { + public SonarQubeApiCall withComponentKeys(final String projectKey) { appendSearchParameter("componentKeys=" + projectKey); return this; } @@ -72,7 +73,7 @@ public SonarQubeApiCall withComponentKeys(String projectKey) { /** * Appends the parameter "types" with the value issueType to the sonarQubeRestApiCall. */ - public SonarQubeApiCall withTypes(SonarQubeIssueType issueType) { + public SonarQubeApiCall withTypes(final SonarQubeIssueType issueType) { appendSearchParameter("types=" + issueType); return this; } @@ -80,7 +81,7 @@ public SonarQubeApiCall withTypes(SonarQubeIssueType issueType) { /** * Appends the parameter "qualifiers" with the single value qualifier to the sonarQubeRestApiCall. */ - private SonarQubeApiCall withQualifiers(SonarQubeComponentQualifier qualifier) { + private SonarQubeApiCall withQualifiers(final SonarQubeComponentQualifier qualifier) { appendSearchParameter("qualifiers=" + qualifier); return this; } @@ -88,7 +89,7 @@ private SonarQubeApiCall withQualifiers(SonarQubeComponentQualifier qualifier) { /** * Appends the parameter "q" (Query) as a text-based simple search param to the sonarQubeRestApiCall. */ - public SonarQubeApiCall withQuery(String query) { + public SonarQubeApiCall withQuery(final String query) { appendSearchParameter("q=" + query); return this; } @@ -96,15 +97,23 @@ public SonarQubeApiCall withQuery(String query) { /** * Appends the parameter "severities" with the values in the severities-List to the sonarQubeRestApiCall. */ - public SonarQubeApiCall withSeverities(List severities) { + public SonarQubeApiCall withSeverities(final List severities) { appendSearchParameter("severities=" + StringUtils.join(severities, ",")); return this; } + /** + * Appends the parameter "organization" with the values in the severities-List to the sonarQubeRestApiCall. + */ + public SonarQubeApiCall withOrganization(final String organization) { + appendSearchParameter("organization=" + organization); + return this; + } + /** * Appends the parameter "pageSize" with the value maxNumberOfIssuesOnPage to the sonarQubeRestApiCall. */ - public SonarQubeApiCall pageSize(int maxNumberOfIssuesOnPage) { + public SonarQubeApiCall pageSize(final int maxNumberOfIssuesOnPage) { appendSearchParameter("pageSize=" + maxNumberOfIssuesOnPage); return this; } @@ -112,7 +121,7 @@ public SonarQubeApiCall pageSize(int maxNumberOfIssuesOnPage) { /** * Appends the parameter "pageIndex" with the value startIndex to the sonarQubeRestApiCall. Paging starts here. */ - public SonarQubeApiCall pageIndex(int startIndex) { + public SonarQubeApiCall pageIndex(final int startIndex) { appendSearchParameter("pageIndex=" + startIndex); return this; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/AdventureRepository.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/AdventureRepository.java index fda3ab86..d4db1987 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/AdventureRepository.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/repositories/AdventureRepository.java @@ -5,12 +5,9 @@ import org.springframework.data.jpa.repository.JpaRepository; import com.viadee.sonarquest.entities.Adventure; -import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.entities.World; public interface AdventureRepository extends JpaRepository { List findByWorld(World world); - - List findByUsersAndWorld(List users, World world); } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/JwtHelper.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/JwtHelper.java index 27f89e39..4b6652c9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/JwtHelper.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/security/JwtHelper.java @@ -1,6 +1,5 @@ package com.viadee.sonarquest.security; -import java.security.SecureRandom; import java.util.Collection; import java.util.Date; import java.util.HashMap; @@ -22,9 +21,11 @@ @Component public class JwtHelper { + private static final String AUTHORITIES = "authorities"; - private final byte[] key = generateKey(); + @Value("${security.jwt.privatekey}") + private String key; @Value("${security.jwt.algorithm}") private String algorithm; @@ -66,9 +67,4 @@ public final UsernameAndAuthorities getUsernameWithAuthorities(final String jwt) return new UsernameAndAuthorities(username, authorities); } - private static byte[] generateKey() { - byte[] generatedKey = new byte[64]; - new SecureRandom().nextBytes(generatedKey); - return generatedKey; - } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java index 24a2fcaa..d9c17eef 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java @@ -1,10 +1,8 @@ package com.viadee.sonarquest.services; -import java.util.ArrayList; import java.util.List; -import java.util.Optional; +import java.util.stream.Collectors; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -18,8 +16,6 @@ import com.viadee.sonarquest.repositories.AdventureRepository; import com.viadee.sonarquest.repositories.QuestRepository; -import javax.persistence.EntityNotFoundException; - @Service public class AdventureService { @@ -31,7 +27,8 @@ public class AdventureService { private final UserService userService; - public AdventureService(AdventureRepository adventureRepository, QuestRepository questRepository, GratificationService gratificationService, UserService userService) { + public AdventureService(final AdventureRepository adventureRepository, final QuestRepository questRepository, + final GratificationService gratificationService, final UserService userService) { this.adventureRepository = adventureRepository; this.questRepository = questRepository; this.gratificationService = gratificationService; @@ -61,23 +58,21 @@ public Adventure findById(final Long adventureId) { } /** - * expects a developer object and the current world and returns the adventures - * that the developer has already joined. + * expects a developer object and the current world and returns the adventures that the developer has already + * joined. * * @param world * @param user * @return allAdventuresForDeveloper */ public List getJoinedAdventuresForUserInWorld(final World world, final User user) { - final List users = new ArrayList<>(); - users.add(user); - - return adventureRepository.findByUsersAndWorld(users, world); + return adventureRepository.findByWorld(world).stream() + .filter(w -> w.getUsers().contains(user)) + .collect(Collectors.toList()); } /** - * expects a developer object and the current world and returns the adventures - * that the developer can still enter. + * expects a developer object and the current world and returns the adventures that the developer can still enter. * * @param world * @param user @@ -93,12 +88,16 @@ public List getFreeAdventuresForUserInWorld(final World world, final /** * Removes the developer from adventure * - * @param adventureId The ID of the adventure to which a developer should be added - * @param userId The user ID of the developer to be added + * @param adventureId + * The ID of the adventure to which a developer should be added + * @param userId + * The user ID of the developer to be added * @return adventure */ - public Adventure removeUserFromAdventure(final long adventureId, final long userId) throws ResourceNotFoundException { - final Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); + public Adventure removeUserFromAdventure(final long adventureId, final long userId) + throws ResourceNotFoundException { + final Adventure adventure = adventureRepository.findById(adventureId) + .orElseThrow(ResourceNotFoundException::new); final User user = userService.findById(userId); adventure.removeUser(user); return adventureRepository.save(adventure); @@ -107,12 +106,15 @@ public Adventure removeUserFromAdventure(final long adventureId, final long user /** * Add a developer to adventure * - * @param adventureId The ID of the adventure from which a developer should be removed - * @param userId The user ID of the developer to be removed + * @param adventureId + * The ID of the adventure from which a developer should be removed + * @param userId + * The user ID of the developer to be removed * @return adventure */ public Adventure addUserToAdventure(final long adventureId, final long userId) { - final Adventure adventure = adventureRepository.findById(adventureId).orElseThrow(ResourceNotFoundException::new); + final Adventure adventure = adventureRepository.findById(adventureId) + .orElseThrow(ResourceNotFoundException::new); final User user = userService.findById(userId); final List userList = adventure.getUsers(); if (!userList.contains(user)) { diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java index ced453f4..596907b7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/EventService.java @@ -1,18 +1,27 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.constants.EventState; -import com.viadee.sonarquest.constants.EventType; -import com.viadee.sonarquest.entities.*; -import com.viadee.sonarquest.repositories.EventRepository; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; + import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Service; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import com.viadee.sonarquest.constants.EventState; +import com.viadee.sonarquest.constants.EventType; +import com.viadee.sonarquest.entities.Adventure; +import com.viadee.sonarquest.entities.Artefact; +import com.viadee.sonarquest.entities.Event; +import com.viadee.sonarquest.entities.EventDto; +import com.viadee.sonarquest.entities.EventUserDto; +import com.viadee.sonarquest.entities.MessageDto; +import com.viadee.sonarquest.entities.Quest; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.entities.UserDto; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.repositories.EventRepository; @Service public class EventService { @@ -25,7 +34,7 @@ public class EventService { private final UserService userService; - public EventService(EventRepository eventRepository, UserService userService) { + public EventService(final EventRepository eventRepository, final UserService userService) { this.eventRepository = eventRepository; this.userService = userService; } @@ -34,67 +43,67 @@ public List getAllEvents() { return eventRepository.findAll(); } - public List getEventsForWorld(Principal principal) { - User user = userService.findByUsername(principal.getName()); - World currentWorld = user.getCurrentWorld(); + public List getEventsForWorld(final Principal principal) { + final User user = userService.findByUsername(principal.getName()); + final World currentWorld = user.getCurrentWorld(); return eventRepository.findByWorldOrWorldIsNull(currentWorld); } - public Event createEventForSolvedAdventure(Adventure adventure, Principal principal) { - Event event = adventureToEvent(adventure, principal, EventState.SOLVED); + public Event createEventForSolvedAdventure(final Adventure adventure, final Principal principal) { + final Event event = adventureToEvent(adventure, principal, EventState.SOLVED); LOGGER.info(String.format("New event because of a solved adventure '%s'", adventure.getTitle())); return checkStoryAndSave(event); } - public Event createEventForDeletedAdventure(Adventure adventure, Principal principal) { - Event event = adventureToEvent(adventure, principal, EventState.DELETED); + public Event createEventForDeletedAdventure(final Adventure adventure, final Principal principal) { + final Event event = adventureToEvent(adventure, principal, EventState.DELETED); LOGGER.info(String.format("New event because of deleted adventure '%s'", adventure.getTitle())); return checkStoryAndSave(event); } - public Event createEventForCreatedAdventure(Adventure adventure, Principal principal) { - Event event = adventureToEvent(adventure, principal, EventState.CREATED); + public Event createEventForCreatedAdventure(final Adventure adventure, final Principal principal) { + final Event event = adventureToEvent(adventure, principal, EventState.CREATED); LOGGER.info(String.format("New event because of a newly created adventure '%s'", adventure.getTitle())); return checkStoryAndSave(event); } - private Event adventureToEvent(Adventure adventure, Principal principal, EventState state) { - EventType type = EventType.ADVENTURE; - String title = adventure.getTitle(); - String story = adventure.getStory(); - String image = StringUtils.EMPTY; - World world = adventure.getWorld(); - String head = StringUtils.EMPTY; - User user = userService.findByUsername(principal.getName()); + private Event adventureToEvent(final Adventure adventure, final Principal principal, final EventState state) { + final EventType type = EventType.ADVENTURE; + final String title = adventure.getTitle(); + final String story = adventure.getStory(); + final String image = StringUtils.EMPTY; + final World world = adventure.getWorld(); + final String head = StringUtils.EMPTY; + final User user = userService.findByUsername(principal.getName()); return new Event(type, title, story, state, image, world, head, user); } - public Event createEventForSolvedQuest(Quest quest, Principal principal) { - Event event = questToEvent(quest, principal, EventState.SOLVED); + public Event createEventForSolvedQuest(final Quest quest, final Principal principal) { + final Event event = questToEvent(quest, principal, EventState.SOLVED); LOGGER.info(String.format("New event because of a solved quest '%s'", quest.getTitle())); return checkStoryAndSave(event); } - public Event createEventForCreatedQuest(Quest quest, Principal principal) { - Event event = questToEvent(quest, principal, EventState.CREATED); + public Event createEventForCreatedQuest(final Quest quest, final Principal principal) { + final Event event = questToEvent(quest, principal, EventState.CREATED); LOGGER.info(String.format("New event because of a newly created quest '%s'", quest.getTitle())); return checkStoryAndSave(event); } - public Event createEventForDeletedQuest(Quest quest, Principal principal) { - Event event = questToEvent(quest, principal, EventState.DELETED); + public Event createEventForDeletedQuest(final Quest quest, final Principal principal) { + final Event event = questToEvent(quest, principal, EventState.DELETED); LOGGER.info(String.format("New event because of a deleted quest '%s'", quest.getTitle())); return checkStoryAndSave(event); } - public Event createEventForUpdatedQuest(Quest quest, Principal principal) { - Event event = questToEvent(quest, principal, EventState.UPDATED); + public Event createEventForUpdatedQuest(final Quest quest, final Principal principal) { + final Event event = questToEvent(quest, principal, EventState.UPDATED); LOGGER.info(String.format("New event because of a updated quest '%s'", quest.getTitle())); return checkStoryAndSave(event); } - public Event createEventForUserJoinQuest(Quest quest, Principal principal, User user) { - Event event = questToEvent(quest, principal, EventState.NEW_MEMBER); + public Event createEventForUserJoinQuest(final Quest quest, final Principal principal, final User user) { + final Event event = questToEvent(quest, principal, EventState.NEW_MEMBER); LOGGER.info("New Event because UserId " + user.getId() + " joined Quest " + quest.getId()); return checkStoryAndSave(event); } - private Event questToEvent(Quest quest, Principal principal, EventState state) { + private Event questToEvent(final Quest quest, final Principal principal, final EventState state) { final EventType type = EventType.QUEST; final String title = quest.getTitle(); final String story = quest.getStory(); @@ -104,57 +113,57 @@ private Event questToEvent(Quest quest, Principal principal, EventState state) { final User user = userService.findByUsername(principal.getName()); return new Event(type, title, story, state, image, world, head, user); } - public Event createEventForCreatedArtefact(Artefact artefact, Principal principal) { - Event event = artefactToEvent(artefact, principal, EventState.CREATED); + public Event createEventForCreatedArtefact(final Artefact artefact, final Principal principal) { + final Event event = artefactToEvent(artefact, principal, EventState.CREATED); LOGGER.info(String.format("New Event because of a created artefact '%s'", artefact.getName())); return checkStoryAndSave(event); } - public Event createEventForDeletedArtefact(Artefact artefact, Principal principal) { - Event event = artefactToEvent(artefact, principal, EventState.DELETED); + public Event createEventForDeletedArtefact(final Artefact artefact, final Principal principal) { + final Event event = artefactToEvent(artefact, principal, EventState.DELETED); LOGGER.info(String.format("New Event because of a deleted artefact '%s'", artefact.getName())); return checkStoryAndSave(event); } - public Event createEventForUpdatedArtefact(Artefact artefact, Principal principal) { - Event event = artefactToEvent(artefact, principal, EventState.UPDATED); + public Event createEventForUpdatedArtefact(final Artefact artefact, final Principal principal) { + final Event event = artefactToEvent(artefact, principal, EventState.UPDATED); LOGGER.info(String.format("New Event because of an updated artefact '%s'", artefact.getName())); return checkStoryAndSave(event); } - - private Event artefactToEvent(Artefact artefact, Principal principal, EventState state) { - EventType type = EventType.ARTEFACT; - String title = artefact.getName(); - String story = artefact.getDescription(); - String image = artefact.getIcon(); + + private Event artefactToEvent(final Artefact artefact, final Principal principal, final EventState state) { + final EventType type = EventType.ARTEFACT; + final String title = artefact.getName(); + final String story = artefact.getDescription(); + final String image = artefact.getIcon(); final User user = userService.findByUsername(principal.getName()); return new Event(type, title, story, state, image, user); } - public Event createEventForNewMessage(String message, Principal principal) { + public Event createEventForNewMessage(final String message, final Principal principal) { final User user = userService.findByUsername(principal.getName()); final EventType type = EventType.MESSAGE; final World world = user.getCurrentWorld(); return checkStoryAndSave(new Event(type, message, world, user)); } - public Event createEventForNewMessage(MessageDto messageDto) { - User user = userService.findById(messageDto.getUserId()); - EventType type = EventType.MESSAGE; - String story = messageDto.getMessage(); - World world = user.getCurrentWorld(); + public Event createEventForNewMessage(final MessageDto messageDto) { + final User user = userService.findById(messageDto.getUserId()); + final EventType type = EventType.MESSAGE; + final String story = messageDto.getMessage(); + final World world = user.getCurrentWorld(); return checkStoryAndSave(new Event(type, story, world, user)); } - public EventUserDto eventToEventUserDto(Event event) { - List eventDtos = new ArrayList<>(); - List userDtos = new ArrayList<>(); + public EventUserDto eventToEventUserDto(final Event event) { + final List eventDtos = new ArrayList<>(); + final List userDtos = new ArrayList<>(); eventDtos.add(new EventDto(event)); if (event.getUser() != null) { - UserDto userDto = new UserDto(event.getUser()); + final UserDto userDto = new UserDto(event.getUser()); if (!hasUserDto(userDtos, userDto)) { userDtos.add(userDto); } @@ -163,13 +172,13 @@ public EventUserDto eventToEventUserDto(Event event) { return new EventUserDto(userDtos, eventDtos); } - public EventUserDto eventsToEventUserDto(List events) { - List eventDtos = new ArrayList<>(); - List userDtos = new ArrayList<>(); + public EventUserDto eventsToEventUserDto(final List events) { + final List eventDtos = new ArrayList<>(); + final List userDtos = new ArrayList<>(); events.forEach(event -> { - EventUserDto eventUserDto = eventToEventUserDto(event); + final EventUserDto eventUserDto = eventToEventUserDto(event); if (!eventUserDto.getEventDtos().isEmpty() && eventDtos.stream() .noneMatch(dto -> dto.getId().equals(eventUserDto.getEventDtos().get(0).getId()))) { eventDtos.add(eventUserDto.getEventDtos().get(0)); @@ -184,14 +193,14 @@ public EventUserDto eventsToEventUserDto(List events) { return new EventUserDto(userDtos, eventDtos); } - public EventUserDto principalToEvents(Principal principal) { - List events = getEventsForWorld(principal); + public EventUserDto principalToEvents(final Principal principal) { + final List events = getEventsForWorld(principal); return eventsToEventUserDto(events); } - public Boolean hasUserDto(List userDtos, UserDto userDto) { + public Boolean hasUserDto(final List userDtos, final UserDto userDto) { - for (UserDto dto : userDtos) { + for (final UserDto dto : userDtos) { if (dto.getId().equals(userDto.getId())) { return true; } @@ -204,9 +213,9 @@ public Boolean hasUserDto(List userDtos, UserDto userDto) { * Since the "story" field of events may be shorter then the story of external * events, it is cut to "story..." in case it exceeds the max length. */ - private Event checkStoryAndSave(Event event) { - String story = event.getStory(); - String cutStory = StringUtils.abbreviate(story, EVENT_STORY_MAX_LENGTH); + private Event checkStoryAndSave(final Event event) { + final String story = event.getStory(); + final String cutStory = StringUtils.abbreviate(story, EVENT_STORY_MAX_LENGTH); event.setStory(cutStory); return eventRepository.save(event); } @@ -223,10 +232,10 @@ public List get3LatestEvents() { return eventRepository.findFirst3ByOrderByTimestampDesc(); } - public boolean areUnseenEventsAvailable(String username) { - User user = userService.findByUsername(username); + public boolean areUnseenEventsAvailable(final String username) { + final User user = userService.findByUsername(username); if (user.getLastTavernVisit() != null) { - List unseenEvents = eventRepository.findAllWithTimestampAfter(user.getLastTavernVisit()); + final List unseenEvents = eventRepository.findAllWithTimestampAfter(user.getLastTavernVisit()); return !unseenEvents.isEmpty(); } return false; diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java index d9692c42..41e751d9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ExternalRessourceService.java @@ -1,12 +1,10 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.SonarConfig; -import com.viadee.sonarquest.entities.StandardTask; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.externalressources.*; -import com.viadee.sonarquest.repositories.StandardTaskRepository; -import com.viadee.sonarquest.rules.SonarQubeStatusMapper; -import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import java.net.ConnectException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + import org.apache.commons.collections4.ListUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -16,10 +14,21 @@ import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; -import java.net.ConnectException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; +import com.viadee.sonarquest.entities.SonarConfig; +import com.viadee.sonarquest.entities.StandardTask; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.externalressources.SonarQubeApiCall; +import com.viadee.sonarquest.externalressources.SonarQubeComponentQualifier; +import com.viadee.sonarquest.externalressources.SonarQubeIssue; +import com.viadee.sonarquest.externalressources.SonarQubeIssueRessource; +import com.viadee.sonarquest.externalressources.SonarQubeIssueType; +import com.viadee.sonarquest.externalressources.SonarQubePaging; +import com.viadee.sonarquest.externalressources.SonarQubeProject; +import com.viadee.sonarquest.externalressources.SonarQubeProjectRessource; +import com.viadee.sonarquest.externalressources.SonarQubeSeverity; +import com.viadee.sonarquest.repositories.StandardTaskRepository; +import com.viadee.sonarquest.rules.SonarQubeStatusMapper; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; /** * Service to access SonarQube server. @@ -52,7 +61,10 @@ public class ExternalRessourceService { @Value("#{'${issue.severities}'.split(',')}") private List issueSeverities; - public ExternalRessourceService(StandardTaskEvaluationService standardTaskEvaluationService, SonarQubeStatusMapper statusMapper, StandardTaskRepository standardTaskRepository, SonarConfigService sonarConfigService, RestTemplateService restTemplateService, GratificationService gratificationService) { + @Value("${sonarqube.organization_key}") + private String organizationKey; + + public ExternalRessourceService(final StandardTaskEvaluationService standardTaskEvaluationService, final SonarQubeStatusMapper statusMapper, final StandardTaskRepository standardTaskRepository, final SonarConfigService sonarConfigService, final RestTemplateService restTemplateService, final GratificationService gratificationService) { this.standardTaskEvaluationService = standardTaskEvaluationService; this.statusMapper = statusMapper; this.standardTaskRepository = standardTaskRepository; @@ -72,17 +84,17 @@ private World toWorld(final SonarQubeProject sonarQubeProject) { public List generateStandardTasksFromSonarQubeIssuesForWorld(final World world) { final List standardTasks; final List sonarQubeIssues = getIssuesForSonarQubeProject(world.getProject()); - int numberOfIssues = sonarQubeIssues.size(); + final int numberOfIssues = sonarQubeIssues.size(); LOGGER.info("Mapping {} issues to SonarQuest tasks - this may take a while...", numberOfIssues); if (numberOfIssues > issueProcessingBatchSize) { standardTasks = new ArrayList<>(); - List> partitions = ListUtils.partition(sonarQubeIssues, issueProcessingBatchSize); + final List> partitions = ListUtils.partition(sonarQubeIssues, issueProcessingBatchSize); LOGGER.info("Processing {} partitions with a size of {} issues each", partitions.size(), issueProcessingBatchSize); int partitionNumber = 1; - for (List partition : partitions) { + for (final List partition : partitions) { LOGGER.info("Mapping partition number: {}", partitionNumber++); - List tasksForThisPartition = partition.stream() + final List tasksForThisPartition = partition.stream() .map(sonarQubeIssue -> toTask(sonarQubeIssue, world)).collect(Collectors.toList()); standardTasks.addAll(tasksForThisPartition); } @@ -148,7 +160,7 @@ private List getIssuesForSonarQubeProject(final String projectKe issueSeverities, projectKey); final SonarConfig sonarConfig = sonarConfigService.getConfig(); final RestTemplate restTemplate = restTemplateService.getRestTemplate(sonarConfig); - SonarQubeIssueRessource sonarQubeIssueRessource = getSonarQubeIssuesWithDefaultSeverities(restTemplate, + final SonarQubeIssueRessource sonarQubeIssueRessource = getSonarQubeIssuesWithDefaultSeverities(restTemplate, sonarConfig.getSonarServerUrl(), projectKey); final List sonarQubeIssueList = new ArrayList<>(sonarQubeIssueRessource.getIssues()); LOGGER.info("Retrieved {} SonarQube issues in total for projectKey {}", @@ -169,12 +181,13 @@ private int determinePagesOfExternalRessourcesToBeRequested(final SonarQubePagin private SonarQubeIssueRessource getSonarQubeIssuesWithDefaultSeverities(final RestTemplate restTemplate, final String sonarQubeServerUrl, final String projectKey) { // @formatter: off - SonarQubeApiCall sonarQubeApiCall = SonarQubeApiCall + final SonarQubeApiCall sonarQubeApiCall = SonarQubeApiCall .onServer(sonarQubeServerUrl) .searchIssues() .withComponentKeys(projectKey) .withTypes(SonarQubeIssueType.CODE_SMELL) .withSeverities(issueSeverities) + .withOrganization(organizationKey) .pageSize(maxNumberOfIssuesOnPage) .pageIndex(1) .build(); @@ -188,11 +201,12 @@ private SonarQubeProjectRessource getSonarQubeProjectRessourceForPageIndex(final final int pageIndex) { final RestTemplate restTemplate = restTemplateService.getRestTemplate(sonarConfig); // @formatter: off - SonarQubeApiCall sonarQubeApiCall = SonarQubeApiCall + final SonarQubeApiCall sonarQubeApiCall = SonarQubeApiCall .onServer(sonarConfig.getSonarServerUrl()) .searchComponents(SonarQubeComponentQualifier.TRK) .pageSize(maxNumberOfIssuesOnPage) .pageIndex(pageIndex) + .withOrganization(organizationKey) .build(); // @formatter: on final ResponseEntity response = restTemplate diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java index 0e943954..e1a33aa9 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/ParticipationService.java @@ -1,17 +1,18 @@ package com.viadee.sonarquest.services; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; + +import javax.transaction.Transactional; + +import org.springframework.stereotype.Service; + import com.viadee.sonarquest.controllers.WebSocketController; import com.viadee.sonarquest.entities.Participation; import com.viadee.sonarquest.entities.Quest; import com.viadee.sonarquest.entities.User; import com.viadee.sonarquest.repositories.ParticipationRepository; -import com.viadee.sonarquest.repositories.QuestRepository; -import org.springframework.stereotype.Service; - -import javax.transaction.Transactional; -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; @Service public class ParticipationService { @@ -21,10 +22,10 @@ public class ParticipationService { private final UserService userService; private final QuestService questService; - + private final WebSocketController webSocketController; - public ParticipationService(ParticipationRepository participationRepository, UserService userService, QuestService questService, WebSocketController webSocketController) { + public ParticipationService(final ParticipationRepository participationRepository, final UserService userService, final QuestService questService, final WebSocketController webSocketController) { this.participationRepository = participationRepository; this.userService = userService; this.questService = questService; @@ -54,13 +55,13 @@ public List findParticipationByUser(final User user) { } @Transactional - public Participation createParticipation(Principal principal, Long questId) { + public Participation createParticipation(final Principal principal, final Long questId) { final Quest foundQuest = questService.findById(questId); final String username = principal.getName(); final User user = userService.findByUsername(username); final Participation foundParticipation = participationRepository.findByQuestAndUser(foundQuest, user); Participation participation = null; - if ((foundQuest != null) && (user != null) && (foundParticipation == null)) { + if (foundQuest != null && user != null && foundParticipation == null) { participation = new Participation(foundQuest, user); participation = participationRepository.save(participation); // Create Event for User join Quest diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java index ad099ea7..faded537 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/RoleService.java @@ -2,7 +2,6 @@ import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.viadee.sonarquest.entities.Role; @@ -14,7 +13,7 @@ public class RoleService { private final RoleRepository roleRepository; - public RoleService(RoleRepository roleRepository) { + public RoleService(final RoleRepository roleRepository) { this.roleRepository = roleRepository; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java index f278c803..1c275e44 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SkillService.java @@ -4,13 +4,10 @@ import javax.transaction.Transactional; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; -import com.viadee.sonarquest.entities.Artefact; import com.viadee.sonarquest.entities.Skill; -import com.viadee.sonarquest.repositories.ArtefactRepository; import com.viadee.sonarquest.repositories.SkillRepository; @Service @@ -20,7 +17,7 @@ public class SkillService { private final ArtefactService artefactService; - public SkillService(SkillRepository skillRepository, ArtefactService artefactService) { + public SkillService(final SkillRepository skillRepository, final ArtefactService artefactService) { this.skillRepository = skillRepository; this.artefactService = artefactService; } @@ -56,7 +53,7 @@ public Skill getSkillById(final Long skillId) { @Transactional public Skill updateSkill(final Long skillId, final Skill newSkill) { - Skill skill = skillRepository.findById(skillId).orElseThrow(ResourceNotFoundException::new); + final Skill skill = skillRepository.findById(skillId).orElseThrow(ResourceNotFoundException::new); skill.setName(newSkill.getName()); skill.setType(newSkill.getType()); skill.setValue(newSkill.getValue()); diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java index 83b5471f..8f850f0e 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SonarConfigService.java @@ -1,16 +1,16 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.SonarConfig; -import com.viadee.sonarquest.externalressources.SonarQubeApiResponse; -import com.viadee.sonarquest.repositories.SonarConfigRepository; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; +import com.viadee.sonarquest.entities.SonarConfig; +import com.viadee.sonarquest.externalressources.SonarQubeApiResponse; +import com.viadee.sonarquest.repositories.SonarConfigRepository; + @Service public class SonarConfigService { @@ -20,7 +20,7 @@ public class SonarConfigService { private final RestTemplateService restTemplateService; - public SonarConfigService(SonarConfigRepository sonarConfigRepository, RestTemplateService restTemplateService) { + public SonarConfigService(final SonarConfigRepository sonarConfigRepository, final RestTemplateService restTemplateService) { this.sonarConfigRepository = sonarConfigRepository; this.restTemplateService = restTemplateService; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java index 82a9b018..4c6a5a6e 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/SpecialTaskService.java @@ -1,15 +1,15 @@ package com.viadee.sonarquest.services; +import java.util.List; + +import org.springframework.data.rest.webmvc.ResourceNotFoundException; +import org.springframework.stereotype.Service; + import com.viadee.sonarquest.entities.SpecialTask; import com.viadee.sonarquest.entities.World; import com.viadee.sonarquest.repositories.SpecialTaskRepository; import com.viadee.sonarquest.repositories.WorldRepository; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.rest.webmvc.ResourceNotFoundException; -import org.springframework.stereotype.Service; - -import java.util.List; @Service public class SpecialTaskService { @@ -18,7 +18,7 @@ public class SpecialTaskService { private final WorldRepository worldRepository; - public SpecialTaskService(SpecialTaskRepository specialTaskRepository, WorldRepository worldRepository) { + public SpecialTaskService(final SpecialTaskRepository specialTaskRepository, final WorldRepository worldRepository) { this.specialTaskRepository = specialTaskRepository; this.worldRepository = worldRepository; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java index 91576031..9d0e4de7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UiDesignService.java @@ -1,6 +1,5 @@ package com.viadee.sonarquest.services; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.viadee.sonarquest.entities.UiDesign; @@ -13,7 +12,7 @@ public class UiDesignService { private final UiDesignRepository uiDesignRepository; - public UiDesignService(UiDesignRepository uiDesignRepository) { + public UiDesignService(final UiDesignRepository uiDesignRepository) { this.uiDesignRepository = uiDesignRepository; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java index e29e7338..a5dcdf9b 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/UserService.java @@ -1,8 +1,14 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.*; -import com.viadee.sonarquest.repositories.UserRepository; -import com.viadee.sonarquest.repositories.WorldRepository; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.transaction.Transactional; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.data.rest.webmvc.ResourceNotFoundException; @@ -13,212 +19,194 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; -import javax.transaction.Transactional; -import javax.validation.constraints.NotNull; -import java.sql.Timestamp; -import java.time.LocalDateTime; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; +import com.viadee.sonarquest.entities.Permission; +import com.viadee.sonarquest.entities.Role; +import com.viadee.sonarquest.entities.RoleName; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.entities.UserToWorldConnection; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.repositories.UserRepository; @Service public class UserService implements UserDetailsService { private static final Log LOGGER = LogFactory.getLog(UserService.class); - private final RoleService roleService; - - private final UserRepository userRepository; - - private final WorldService worldService; - - private final LevelService levelService; - - private final PermissionService permissionService; - - private final WorldRepository worldRepository; - - public UserService(RoleService roleService, UserRepository userRepository, WorldService worldService, LevelService levelService, PermissionService permissionService, WorldRepository worldRepository) { - this.roleService = roleService; - this.userRepository = userRepository; - this.worldService = worldService; - this.levelService = levelService; - this.permissionService = permissionService; - this.worldRepository = worldRepository; - } - - @Override - public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { - final User user = findByUsername(username); - final Set permissions = permissionService.getAccessPermissions(user); - - final List authorities = permissions.stream() - .map(berechtigung -> new SimpleGrantedAuthority(berechtigung.getPermission())) - .collect(Collectors.toList()); - - return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, - true, true, true, authorities); - } - - public User findByUsername(final String username) { - return userRepository.findByUsername(username); - } - - private User findById(final Long id) throws ResourceNotFoundException{ - return userRepository.findById(id).orElseThrow(ResourceNotFoundException::new); - } - - public World updateUsersCurrentWorld(final User user, final Long worldId) { - final World world = worldService.findById(worldId); - user.setLastTavernVisit(null); - user.setCurrentWorld(world); - userRepository.saveAndFlush(user); - return user.getCurrentWorld(); - } - - @Transactional - public synchronized User save(final User user) { - User toBeSaved; - final String username = user.getUsername(); - final String mail = user.getMail(); - final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); - if (user.getId() == null) { - // Only the password hash needs to be saved - final String password = encoder.encode(user.getPassword()); - final Role role = user.getRole(); - final RoleName roleName = role.getName(); - final Role userRole = roleService.findByName(roleName); - toBeSaved = usernameFree(username) ? user : null; - if (toBeSaved != null) { - setMail(toBeSaved, mail); - toBeSaved.setPassword(password); - toBeSaved.setRole(userRole); - toBeSaved.setCurrentWorld(user.getCurrentWorld()); - toBeSaved.setGold(0L); - toBeSaved.setXp(0L); - toBeSaved.setLevel(levelService.getLevelByUserXp(0L)); - } - } else { - toBeSaved = findById(user.getId()); - if (toBeSaved != null) { - final Role role = user.getRole(); - final RoleName roleName = role.getName(); - final Role userRole = roleService.findByName(roleName); - setUsername(toBeSaved, username); - setMail(toBeSaved, mail); - setPassword(user, toBeSaved, encoder); - toBeSaved.setRole(userRole); - toBeSaved.setAboutMe(user.getAboutMe()); - toBeSaved.setPicture(user.getPicture()); - toBeSaved.setCurrentWorld(user.getCurrentWorld()); - toBeSaved.setWorlds(user.getWorlds()); - toBeSaved.setGold(user.getGold()); - toBeSaved.setXp(user.getXp()); - toBeSaved.setLevel(levelService.getLevelByUserXp(user.getXp())); - toBeSaved.setAdventures(user.getAdventures()); - toBeSaved.setArtefacts(user.getArtefacts()); - toBeSaved.setAvatarClass(user.getAvatarClass()); - toBeSaved.setParticipations(user.getParticipations()); - toBeSaved.setUiDesign(user.getUiDesign()); - } - } - - return toBeSaved != null ? userRepository.saveAndFlush(toBeSaved) : null; - } - - private void setUsername(User toBeSaved, final String username) { - if (!username.equals(toBeSaved.getUsername()) && usernameFree(username)) { - toBeSaved.setUsername(username); - } - } - - private void setMail(User toBeSaved, final String mail) { - if (toBeSaved.getMail() != null) { - if (!mail.equals(toBeSaved.getMail()) && mailFree(mail)) { - toBeSaved.setMail(mail); - } - } else if (mailFree(mail)) { - toBeSaved.setMail(mail); - } - - } - - private void setPassword(final User user, User toBeSaved, final BCryptPasswordEncoder encoder) { - // if there are identical hashes in the pw fields, do not touch them - if (!toBeSaved.getPassword().equals(user.getPassword())) { - // change password only if it differs from the old one - final String oldPassHash = toBeSaved.getPassword(); - if (!oldPassHash.equals(user.getPassword()) || !encoder.matches(user.getPassword(), oldPassHash)) { - final String password = encoder.encode(user.getPassword()); - toBeSaved.setPassword(password); - LOGGER.info("The password for user " + user.getUsername() + " (id: " + user.getId() - + ") has been changed."); - } - } - } - - private boolean usernameFree(final String username) { - return userRepository.findByUsername(username) == null; - } - - private boolean mailFree(final String mail) { - return userRepository.findByMail(mail) == null; - } - - public void delete(final Long userId) { - final User user = findById(userId); - userRepository.delete(user); - } - - @NotNull - public User findById(final long userId) throws ResourceNotFoundException { - return userRepository.findById(userId).orElseThrow(ResourceNotFoundException::new); - } - - public List findAll() { - return userRepository.findAll(); - } - - public List findByRole(final RoleName roleName) { - return findAll().stream().filter(user -> user.getRole().getName() == roleName).collect(Collectors.toList()); - } - - public Level getLevel(final long xp) { - return levelService.getLevelByUserXp(xp); - } - - @Transactional - public void updateLastLogin(final String username) { - final User user = findByUsername(username); - user.setLastLogin(Timestamp.valueOf(LocalDateTime.now())); - save(user); - } - - public Boolean updateUserToWorld(List userToWorlds) throws ResourceNotFoundException { - userToWorlds.forEach(userToWorld -> { - User user = userRepository.findById(userToWorld.getUserId()).orElseThrow(ResourceNotFoundException::new); - if (userToWorld.getJoined()) { - World world = worldRepository.findById(userToWorld.getWorldId()).orElseThrow(ResourceNotFoundException::new); - user.addWorld(world); - } else { - if (user.getCurrentWorld() != null && user.getCurrentWorld().getId().equals(userToWorld.getWorldId())) { - user.setCurrentWorld(null); - } - user.removeWorld(worldRepository.findById(userToWorld.getWorldId()).orElseThrow(ResourceNotFoundException::new)); - } - - userRepository.save(user); - }); - - return true; - } - - public void updateLastTavernVisit(String username, Timestamp lastVisit) { - User user = userRepository.findByUsername(username); - if (user != null) { - user.setLastTavernVisit(lastVisit); - userRepository.save(user); - } - - } + private final RoleService roleService; + + private final UserRepository userRepository; + + private final LevelService levelService; + + private final PermissionService permissionService; + + final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); + + public UserService(final RoleService roleService, final UserRepository userRepository, + final LevelService levelService, final PermissionService permissionService) { + this.roleService = roleService; + this.userRepository = userRepository; + this.levelService = levelService; + this.permissionService = permissionService; + } + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + final User user = findByUsername(username); + final Set permissions = permissionService.getAccessPermissions(user); + + final List authorities = permissions.stream() + .map(berechtigung -> new SimpleGrantedAuthority(berechtigung.getPermission())) + .collect(Collectors.toList()); + + return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, + true, true, true, authorities); + } + + public User findByUsername(final String username) { + return userRepository.findByUsername(username); + } + + private User findById(final Long id) throws ResourceNotFoundException { + return userRepository.findById(id).orElseThrow(ResourceNotFoundException::new); + } + + public User updateUser(final User user) { + return userRepository.saveAndFlush(user); + } + + @Transactional + public synchronized User save(final User user) { + User toBeSaved; + final String username = user.getUsername(); + final String mail = user.getMail(); + + if (user.getId() == null) { + // Only the password hash needs to be saved + final String password = encoder.encode(user.getPassword()); + final Role role = user.getRole(); + final RoleName roleName = role.getName(); + final Role userRole = roleService.findByName(roleName); + toBeSaved = isUsernameAvailable(username) ? user : null; + if (toBeSaved != null) { + setMail(toBeSaved, mail); + toBeSaved.setPassword(password); + toBeSaved.setRole(userRole); + toBeSaved.setCurrentWorld(user.getCurrentWorld()); + toBeSaved.setGold(0L); + toBeSaved.setXp(0L); + toBeSaved.setLevel(levelService.getLevelByUserXp(0L)); + } + } else { + toBeSaved = findById(user.getId()); + if (toBeSaved != null) { + final Role role = user.getRole(); + final RoleName roleName = role.getName(); + final Role userRole = roleService.findByName(roleName); + setUsername(toBeSaved, username); + setMail(toBeSaved, mail); + setPassword(user, toBeSaved); + toBeSaved.setRole(userRole); + toBeSaved.setAboutMe(user.getAboutMe()); + toBeSaved.setPicture(user.getPicture()); + toBeSaved.setCurrentWorld(user.getCurrentWorld()); + toBeSaved.setWorlds(user.getWorlds()); + toBeSaved.setGold(user.getGold()); + toBeSaved.setXp(user.getXp()); + toBeSaved.setLevel(levelService.getLevelByUserXp(user.getXp())); + toBeSaved.setAdventures(user.getAdventures()); + toBeSaved.setArtefacts(user.getArtefacts()); + toBeSaved.setAvatarClass(user.getAvatarClass()); + toBeSaved.setParticipations(user.getParticipations()); + toBeSaved.setUiDesign(user.getUiDesign()); + } + } + + return toBeSaved != null ? userRepository.saveAndFlush(toBeSaved) : null; + } + + private void setUsername(final User toBeSaved, final String username) { + if (!username.equals(toBeSaved.getUsername()) && isUsernameAvailable(username)) { + toBeSaved.setUsername(username); + } + } + + private void setMail(final User toBeSaved, final String mail) { + if (toBeSaved.getMail() != null) { + if (!mail.equals(toBeSaved.getMail()) && isUserEmailAvailable(mail)) { + toBeSaved.setMail(mail); + } + } else if (isUserEmailAvailable(mail)) { + toBeSaved.setMail(mail); + } + + } + + private void setPassword(final User user, final User toBeSaved) { + // if there are identical hashes in the pw fields, do not touch them + if (!toBeSaved.getPassword().equals(user.getPassword())) { + // change password only if it differs from the old one + final String oldPassHash = toBeSaved.getPassword(); + if (!oldPassHash.equals(user.getPassword()) || !encoder.matches(user.getPassword(), oldPassHash)) { + final String password = encoder.encode(user.getPassword()); + toBeSaved.setPassword(password); + LOGGER.info("The password for user " + user.getUsername() + " (id: " + user.getId() + + ") has been changed."); + } + } + } + + private boolean isUsernameAvailable(final String username) { + return userRepository.findByUsername(username) == null; + } + + private boolean isUserEmailAvailable(final String mail) { + return userRepository.findByMail(mail) == null; + } + + public void delete(final Long userId) { + final User user = findById(userId); + userRepository.delete(user); + } + + public User findById(final long userId) throws ResourceNotFoundException { + return userRepository.findById(userId).orElseThrow(ResourceNotFoundException::new); + } + + public List findAll() { + return userRepository.findAll(); + } + + @Transactional + public void updateLastLogin(final String username) { + final User user = findByUsername(username); + user.setLastLogin(Timestamp.valueOf(LocalDateTime.now())); + save(user); + } + + public void updateUserToWorld(final List userToWorldConnections) { + userToWorldConnections.forEach(this::updateUserWorldConnection); + } + + private User updateUserWorldConnection(final UserToWorldConnection userToWorld) { + final User user = userToWorld.getUser(); + final World world = userToWorld.getWorld(); + if (userToWorld.getJoined()) { + user.addWorld(world); + } else { + user.removeWorld(world); + if (user.getCurrentWorld() != null && Objects.equals(user.getCurrentWorld(), world)) { + user.setCurrentWorld(null); + } + } + return userRepository.save(user); + } + + public void updateLastTavernVisit(final String username, final Timestamp lastVisit) { + final User user = userRepository.findByUsername(username); + if (user != null) { + user.setLastTavernVisit(lastVisit); + userRepository.save(user); + } + } } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java index e013903b..e987aeb2 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WizardService.java @@ -2,7 +2,6 @@ import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.viadee.sonarquest.entities.User; @@ -14,7 +13,7 @@ public class WizardService { private final WorldService worldService; - public WizardService(WorldService worldService) { + public WizardService(final WorldService worldService) { this.worldService = worldService; } @@ -36,13 +35,13 @@ private enum WizardState { private String solutionKey; - private WizardState(String messageKey, String solutionKey) { + private WizardState(final String messageKey, final String solutionKey) { this.messageKey = messageKey; this.solutionKey = solutionKey; } public WizardMessage toWizardMessage() { - WizardMessage wm = new WizardMessage(); + final WizardMessage wm = new WizardMessage(); wm.setMessage(messageKey); wm.setSolution(solutionKey); return wm; @@ -68,20 +67,20 @@ public WizardMessage toWizardMessage() { * quest with tasks *
  • NO_WORLD_SELECTED If no world is selected => show a hint
  • * - * + * * @param world * if the id of world is set, a current world has been selected in * the UI. Only retrieve messages for this world then. */ - public WizardMessage getMostImportantMessageFor(World world) { - WizardState state = determineGameState(world); - return (state == WizardState.NO_MESSAGES ? null : state.toWizardMessage()); + public WizardMessage getMostImportantMessageFor(final World world) { + final WizardState state = determineGameState(world); + return state == WizardState.NO_MESSAGES ? null : state.toWizardMessage(); } - private WizardState determineGameState(World selectedWorld) { + private WizardState determineGameState(final World selectedWorld) { // no active world if (selectedWorld.getId() == null) { - List allWorlds = worldService.findAll(); + final List allWorlds = worldService.findAll(); if (allWorlds.isEmpty()) { return WizardState.NO_WORLDS_FOUND; } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java index 0df770a2..6f350ce7 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/WorldService.java @@ -1,25 +1,20 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.WorldRepository; +import java.util.List; + import org.springframework.data.rest.webmvc.ResourceNotFoundException; import org.springframework.stereotype.Service; -import java.util.List; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.repositories.WorldRepository; @Service public class WorldService { - private final ExternalRessourceService externalRessourceService; - private final WorldRepository worldRepository; - private final StandardTaskService standardTaskService; - - public WorldService(ExternalRessourceService externalRessourceService, WorldRepository worldRepository, StandardTaskService standardTaskService) { - this.externalRessourceService = externalRessourceService; + public WorldService(final WorldRepository worldRepository) { this.worldRepository = worldRepository; - this.standardTaskService = standardTaskService; } public List findAll() { @@ -30,9 +25,8 @@ public World save(final World world) { return worldRepository.save(world); } - public void retrieveExternalWorlds() { - final List externalWorlds = externalRessourceService.generateWorldsFromSonarQubeProjects(); - externalWorlds.forEach(this::saveWorldIfNotExists); + public void saveWorlds(final List worlds) { + worlds.forEach(this::saveWorldIfNotExists); } private void saveWorldIfNotExists(final World externalWorld) { @@ -46,7 +40,7 @@ public List findAllActiveWorlds() { return worldRepository.findByActiveTrue(); } - public World findById(final Long id) throws ResourceNotFoundException { + public World findById(final Long id) { return worldRepository.findById(id).orElseThrow(ResourceNotFoundException::new); } @@ -57,7 +51,6 @@ public World updateWorld(final World world) { currentWorld.setActive(world.getActive()); currentWorld.setUsequestcards(world.getUsequestcards()); currentWorld = worldRepository.save(currentWorld); - standardTaskService.updateStandardTasks(currentWorld); return currentWorld; } diff --git a/sonarQuest-backend/src/main/resources/application.properties b/sonarQuest-backend/src/main/resources/application.properties index bcf0d852..f54e5d66 100644 --- a/sonarQuest-backend/src/main/resources/application.properties +++ b/sonarQuest-backend/src/main/resources/application.properties @@ -5,6 +5,8 @@ security.jwt.algorithm=HS512 # Gütligkeit eines JWTs in Millisekunden security.jwt.validity=7200000 +# Private Key +security.jwt.privatekey=please_change_this_key_in_production # ======================================== # CORS-HEADER @@ -17,6 +19,7 @@ cors.header.active=true spring.application.name=sQ resourceEndpoint=http://localhost:3000 avatar.directory=/avatar/ +sonarqube.organization_key=viadee # ======================================== # DATASOURCE @@ -26,11 +29,10 @@ spring.datasource.platform=h2 spring.datasource.driverClassName=org.h2.Driver spring.jpa.database-platform=org.hibernate.dialect.H2Dialect - # ======================================== # FLYWAY # ======================================== -spring.flyway.enabled=false +spring.flyway.enabled=true spring.flyway.validate-on-migrate=true spring.flyway.clean-on-validation-error=true spring.flyway.baseline-on-migrate=true @@ -41,7 +43,6 @@ spring.flyway.table=schema_version # ======================================== # HIBERNATE # ======================================== -spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=validate spring.jpa.properties.hibernate.show_sql=false spring.jpa.properties.hibernate.use_sql_comments=false diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java index 7fe5dbd0..a82699a1 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/AdventureControllerTest.java @@ -1,18 +1,19 @@ package com.viadee.sonarquest.controllers; -import com.viadee.sonarquest.constants.AdventureState; -import com.viadee.sonarquest.entities.Adventure; +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.security.Principal; + +import javax.transaction.Transactional; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import javax.transaction.Transactional; -import java.security.Principal; - -import static org.junit.jupiter.api.Assertions.*; +import com.viadee.sonarquest.constants.AdventureState; +import com.viadee.sonarquest.entities.Adventure; @SpringBootTest @Transactional @@ -24,13 +25,13 @@ public class AdventureControllerTest { @Test public void createAdventure() { // Given - String title = "Testadventure"; - String story = "My story"; - long gold = 10L; - long xp = 10L; - Adventure adventure = new Adventure(title, story, AdventureState.OPEN, gold, xp); + final String title = "Testadventure"; + final String story = "My story"; + final long gold = 10L; + final long xp = 10L; + final Adventure adventure = new Adventure(title, story, AdventureState.OPEN, gold, xp); // when - Adventure newAdventure = adventureController.createAdventure(createPrincipal(), adventure); + final Adventure newAdventure = adventureController.createAdventure(createPrincipal(), adventure); // then assertNotNull(newAdventure.getId()); assertTrue(newAdventure.getId() > 0); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java index baeeae56..9af28664 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java @@ -1,13 +1,10 @@ package com.viadee.sonarquest.controllers.login; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest @@ -18,7 +15,7 @@ public class LoginControllerIntegrationTest { @Test public void testInfo() { - String info = controller.info(); + final String info = controller.info(); assertEquals("Dies ist eine Login Seite", info); } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java index 89f655fb..7cb6b347 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/entities/UserDtoTest.java @@ -1,23 +1,21 @@ package com.viadee.sonarquest.entities; -import com.viadee.sonarquest.repositories.UserRepository; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class UserDtoTest { @Test public void testConstructUserDto() { // Given - User user = new User(); - + final User user = new User(); + // When - UserDto userDto = new UserDto(user); + final UserDto userDto = new UserDto(user); // Then assertEquals(userDto.getId(), user.getId()); } - + } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java index 130a3188..af9c0da0 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/externalressources/SonarQubeApiCallIT.java @@ -1,19 +1,17 @@ package com.viadee.sonarquest.externalressources; +import static org.junit.jupiter.api.Assertions.assertEquals; -import com.viadee.sonarquest.entities.SonarConfig; -import com.viadee.sonarquest.services.RestTemplateService; -import com.viadee.sonarquest.services.SonarConfigService; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; -import static org.junit.jupiter.api.Assertions.assertEquals; +import com.viadee.sonarquest.entities.SonarConfig; +import com.viadee.sonarquest.services.RestTemplateService; +import com.viadee.sonarquest.services.SonarConfigService; @SpringBootTest @Disabled @@ -27,15 +25,15 @@ public class SonarQubeApiCallIT { @Test public void searchComponents() { - SonarConfig sonarConfig = sonarConfigService.getConfig(); - String sonarQubeServerUrl = sonarConfig.getSonarServerUrl(); - String projectKey = "assertj"; - SonarQubeApiCall apiCall = SonarQubeApiCall + final SonarConfig sonarConfig = sonarConfigService.getConfig(); + final String sonarQubeServerUrl = sonarConfig.getSonarServerUrl(); + final String projectKey = "assertj"; + final SonarQubeApiCall apiCall = SonarQubeApiCall .onServer(sonarQubeServerUrl) .searchComponents(SonarQubeComponentQualifier.TRK) .withQuery(projectKey) .build(); - RestTemplate restTemplate = restTemplateService.getRestTemplate(sonarConfig); + final RestTemplate restTemplate = restTemplateService.getRestTemplate(sonarConfig); final ResponseEntity response = restTemplate.getForEntity( apiCall.asString(), diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java index 32b4b56d..2ea7d2cc 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/SonarQuestApplicationIT.java @@ -1,31 +1,41 @@ package com.viadee.sonarquest.integration; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.springframework.test.util.AssertionErrors.assertEquals; +import static org.springframework.test.util.AssertionErrors.assertNotNull; +import static org.springframework.test.util.AssertionErrors.assertNull; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; import com.viadee.sonarquest.controllers.ParticipationController; import com.viadee.sonarquest.controllers.TaskController; -import com.viadee.sonarquest.entities.*; -import com.viadee.sonarquest.repositories.*; +import com.viadee.sonarquest.entities.Level; +import com.viadee.sonarquest.entities.Participation; +import com.viadee.sonarquest.entities.Quest; +import com.viadee.sonarquest.entities.RoleName; +import com.viadee.sonarquest.entities.StandardTask; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.repositories.AvatarClassRepository; +import com.viadee.sonarquest.repositories.AvatarRaceRepository; +import com.viadee.sonarquest.repositories.LevelRepository; +import com.viadee.sonarquest.repositories.QuestRepository; +import com.viadee.sonarquest.repositories.StandardTaskRepository; +import com.viadee.sonarquest.repositories.TaskRepository; +import com.viadee.sonarquest.repositories.WorldRepository; import com.viadee.sonarquest.rules.SonarQuestTaskStatus; import com.viadee.sonarquest.services.LevelService; import com.viadee.sonarquest.services.RoleService; import com.viadee.sonarquest.services.StandardTaskService; import com.viadee.sonarquest.services.UserService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.transaction.annotation.Transactional; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; - -import static org.springframework.test.util.AssertionErrors.assertEquals; -import static org.springframework.test.util.AssertionErrors.assertNotNull; -import static org.springframework.test.util.AssertionErrors.assertNull; -import static org.junit.jupiter.api.Assertions.assertTimeout; @SpringBootTest public class SonarQuestApplicationIT { @@ -78,7 +88,7 @@ public class SonarQuestApplicationIT { @Autowired private StandardTaskRepository standardTaskRepository; - + /** * Walk through the participation on the backend with a developer perspective. This test assumes a spring * environment including a simulated sonar server and database access. @@ -179,17 +189,17 @@ private World createWorld() { world.setActive(true); return worldRepository.save(world); } - + /** * Regression test for issue #162. */ @Test @Transactional public void caseSensitiveTaskKeys() { - + final World discWorld = createWorld(); - Quest magicQuest = createQuest(discWorld); - + final Quest magicQuest = createQuest(discWorld); + final StandardTask task = new StandardTask(); task.setGold(10L); task.setXp(20L); @@ -199,7 +209,7 @@ public void caseSensitiveTaskKeys() { task.setQuest(magicQuest); task.setStatus(SonarQuestTaskStatus.OPEN); taskRepository.save(task); - + assertNull("unexpected Task", standardTaskRepository.findByKey("AWc3A2KEoXX3DuVBrVTC")); standardTaskRepository.findAll().forEach(t -> System.out.println(">>>" + t.getId() + " " + t.getKey())); Assertions.assertNotNull(standardTaskRepository.findByKey("AWc3A2KEoXX3DuVBrVTc")); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java index 5a357b97..7e72de5e 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/integration/UserManagementIT.java @@ -1,16 +1,14 @@ package com.viadee.sonarquest.integration; +import static org.springframework.test.util.AssertionErrors.assertNotNull; -import com.viadee.sonarquest.entities.Role; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.services.UserService; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import static org.springframework.test.util.AssertionErrors.assertNotNull; +import com.viadee.sonarquest.entities.Role; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.services.UserService; @SpringBootTest public class UserManagementIT { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java index 3805235e..741008cf 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java @@ -1,20 +1,21 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.Adventure; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.AdventureRepository; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; +import com.viadee.sonarquest.entities.Adventure; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.repositories.AdventureRepository; @ExtendWith(MockitoExtension.class) public class AdventureServiceTest { @@ -63,7 +64,7 @@ public void testGetAllAdventuresForWorldAndUser() { final List users = new ArrayList<>(); users.add(mockUser1); - when(adventureRepository.findByUsersAndWorld(users, mockWorld)).thenReturn(adventuresByUserAndWorld); +// when(adventureRepository.findByUsersAndWorld(users, mockWorld)).thenReturn(adventuresByUserAndWorld); when(adventureRepository.findByWorld(mockWorld)).thenReturn(adventuresByWorld); // call method to be tested diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java index 83a8b6a1..4b0d814d 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceIT.java @@ -1,22 +1,21 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.Artefact; -import com.viadee.sonarquest.entities.Level; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import javax.transaction.Transactional; + import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import javax.transaction.Transactional; - -import static org.junit.jupiter.api.Assertions.assertNotNull; +import com.viadee.sonarquest.entities.Artefact; +import com.viadee.sonarquest.entities.Level; @SpringBootTest @Transactional public class ArtefactServiceIT { - + @Autowired private ArtefactService service; @@ -25,29 +24,29 @@ public class ArtefactServiceIT { @Test public void createArtefact_newLevel() { - Artefact artefact = new Artefact(); + final Artefact artefact = new Artefact(); artefact.setDescription("Test"); artefact.setIcon("ra-chain"); artefact.setMinLevel(new Level(1L)); artefact.setName("Sword of Ogre Decapitation"); artefact.setPrice(1L); artefact.setQuantity(1L); - Artefact createdArtefact = service.createArtefact(artefact); + final Artefact createdArtefact = service.createArtefact(artefact); assertNotNull(createdArtefact); assertNotNull(createdArtefact.getId()); } @Test public void createArtefact_existingLevel() { - Level level = levelService.findByLevel(1); - Artefact artefact = new Artefact(); + final Level level = levelService.findByLevel(1); + final Artefact artefact = new Artefact(); artefact.setDescription("Test"); artefact.setIcon("ra-chain"); artefact.setMinLevel(level); artefact.setName("Sword of Ogre Decapitation"); artefact.setPrice(1L); artefact.setQuantity(1L); - Artefact createdArtefact = service.createArtefact(artefact); + final Artefact createdArtefact = service.createArtefact(artefact); assertNotNull(createdArtefact); assertNotNull(createdArtefact.getId()); } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java index de542117..9a6291cc 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/EventServiceIT.java @@ -1,23 +1,30 @@ package com.viadee.sonarquest.services; +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 com.viadee.sonarquest.constants.QuestState; -import com.viadee.sonarquest.entities.*; -import com.viadee.sonarquest.repositories.EventRepository; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import javax.transaction.Transactional; import java.security.Principal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; -import static org.junit.jupiter.api.Assertions.*; +import javax.transaction.Transactional; + +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.viadee.sonarquest.constants.QuestState; +import com.viadee.sonarquest.entities.Event; +import com.viadee.sonarquest.entities.EventUserDto; +import com.viadee.sonarquest.entities.MessageDto; +import com.viadee.sonarquest.entities.Quest; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.entities.UserDto; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.repositories.EventRepository; @SpringBootTest @Transactional @@ -32,30 +39,30 @@ public class EventServiceIT { @Test public void testServiceEvent() { - Event event1 = new Event(); + final Event event1 = new Event(); event1.setTimestamp(new Timestamp(System.currentTimeMillis())); event1.setTitle("event1"); eventRepository.save(event1); // get Event lists - List events1 = eventService.getLatestEvent(); + final List events1 = eventService.getLatestEvent(); // verify result assertEquals(events1.get(0), event1); - Event event2 = new Event(); + final Event event2 = new Event(); event2.setTimestamp(new Timestamp(System.currentTimeMillis())); event2.setTitle("event2"); eventRepository.save(event2); - Event event3 = new Event(); + final Event event3 = new Event(); event3.setTimestamp(new Timestamp(System.currentTimeMillis())); event3.setTitle("event3"); eventRepository.save(event3); // get Event lists - List events2 = eventService.get2LatestEvents(); - List events3 = eventService.get3LatestEvents(); + final List events2 = eventService.get2LatestEvents(); + final List events3 = eventService.get3LatestEvents(); // verify result assertTrue(events2.contains(event3)); @@ -72,61 +79,61 @@ public void testServiceEvent() { @Test public void testCreateEventForCreatedQuest_shortStory() { // Given - String longStory = createStoryWithLength(25); - Quest quest = createQuest("A new quest in the land of Testiara!", longStory); - Principal principal = createPrincipal(); + final String longStory = createStoryWithLength(25); + final Quest quest = createQuest("A new quest in the land of Testiara!", longStory); + final Principal principal = createPrincipal(); // When eventService.createEventForCreatedQuest(quest, principal); // Then - List events = eventService.getLatestEvent(); - Event latestEvent = events.get(0); + final List events = eventService.getLatestEvent(); + final Event latestEvent = events.get(0); assertEquals("A new quest in the land of Testiara!", latestEvent.getTitle()); } @Test public void testCreateEventForCreatedQuest_storyMoreThen255CharsLong() { // Given - String longStory = createStoryWithLength(300); - Quest quest = createQuest("A new quest in the land of Testiara!", longStory); - Principal principal = createPrincipal(); + final String longStory = createStoryWithLength(300); + final Quest quest = createQuest("A new quest in the land of Testiara!", longStory); + final Principal principal = createPrincipal(); // When eventService.createEventForCreatedQuest(quest, principal); // Then - List events = eventService.getLatestEvent(); - Event latestEvent = events.get(0); + final List events = eventService.getLatestEvent(); + final Event latestEvent = events.get(0); assertEquals("A new quest in the land of Testiara!", latestEvent.getTitle()); } - + @Test public void testEventToEventUserDto() { - User user1 = new User(); - Event event1 = new Event(); + final User user1 = new User(); + final Event event1 = new Event(); event1.setUser(user1); - + // When - EventUserDto eventUserDto = eventService.eventToEventUserDto(event1); - + final EventUserDto eventUserDto = eventService.eventToEventUserDto(event1); + // Then assertEquals(eventUserDto.getEventDtos().get(0).getId(), event1.getId()); assertEquals(eventUserDto.getEventDtos().get(0).getUserId(), user1.getId()); assertEquals(eventUserDto.getUserDtos().get(0).getId(), user1.getId()); } - + @Test public void testEventsToEventUserDto() { // Given - List events = new ArrayList<>(); - World world = new World(); - User user1 = createUser(1L,world); - User user2 = createUser(2L,world); - User user3 = createUser(3L,world); - - Event event1 = eventService.createEventForNewMessage(new MessageDto("Test Message1",user1.getId())); - Event event2 = eventService.createEventForNewMessage(new MessageDto("Test Message2",user2.getId())); - Event event3 = eventService.createEventForNewMessage(new MessageDto("Test Message3",user3.getId())); - Event event4 = eventService.createEventForNewMessage(new MessageDto("Test Message4",user1.getId())); - Event event5 = eventService.createEventForNewMessage(new MessageDto("Test Message5",user2.getId())); - + final List events = new ArrayList<>(); + final World world = new World(); + final User user1 = createUser(1L,world); + final User user2 = createUser(2L,world); + final User user3 = createUser(3L,world); + + final Event event1 = eventService.createEventForNewMessage(new MessageDto("Test Message1",user1.getId())); + final Event event2 = eventService.createEventForNewMessage(new MessageDto("Test Message2",user2.getId())); + final Event event3 = eventService.createEventForNewMessage(new MessageDto("Test Message3",user3.getId())); + final Event event4 = eventService.createEventForNewMessage(new MessageDto("Test Message4",user1.getId())); + final Event event5 = eventService.createEventForNewMessage(new MessageDto("Test Message5",user2.getId())); + events.add(event1); events.add(event2); events.add(event3); @@ -134,36 +141,36 @@ public void testEventsToEventUserDto() { events.add(event5); // When - EventUserDto eventUserDto = eventService.eventsToEventUserDto(events); - + final EventUserDto eventUserDto = eventService.eventsToEventUserDto(events); + // Then assertEquals(5, eventUserDto.getEventDtos().size()); assertEquals(3, eventUserDto.getUserDtos().size()); } - - private User createUser(Long id, World world) { - User user = new User(); + + private User createUser(final Long id, final World world) { + final User user = new User(); user.setId(id); user.setPicture("pic"); user.setCurrentWorld(world); return user; } - + @Test public void hasUserDto() { // Given - World world = new World(); - User user1 = createUser(1L, world); + final World world = new World(); + final User user1 = createUser(1L, world); eventService.createEventForNewMessage(new MessageDto("Test Message1", user1.getId())); eventService.createEventForNewMessage(new MessageDto("Test Message2", user1.getId())); - List events = eventRepository.findFirst2ByOrderByTimestampDesc(); + final List events = eventRepository.findFirst2ByOrderByTimestampDesc(); - UserDto userDto1 = new UserDto(events.get(0).getUser()); - UserDto userDto2 = new UserDto(events.get(1).getUser()); + final UserDto userDto1 = new UserDto(events.get(0).getUser()); + final UserDto userDto2 = new UserDto(events.get(1).getUser()); // When - List userDtos = new ArrayList<>(); + final List userDtos = new ArrayList<>(); userDtos.add(userDto1); userDtos.add(userDto2); @@ -171,7 +178,7 @@ public void hasUserDto() { assertTrue(eventService.hasUserDto(userDtos, userDto1)); } - private String createStoryWithLength(int storyLength) { + private String createStoryWithLength(final int storyLength) { return RandomStringUtils.randomAlphabetic(storyLength); } @@ -179,7 +186,7 @@ private Principal createPrincipal() { return () -> "admin"; } - private Quest createQuest(String title, String story) { + private Quest createQuest(final String title, final String story) { return new Quest(title, story, QuestState.OPEN, 1L, 1L, null, null, true, null, null, null); } } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java index f4c413ca..346137e5 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/SonarConfigServiceTest.java @@ -1,15 +1,13 @@ package com.viadee.sonarquest.services; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import com.viadee.sonarquest.entities.SonarConfig; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import com.viadee.sonarquest.entities.SonarConfig; @SpringBootTest public class SonarConfigServiceTest { diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java index 1f11e359..f711df37 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java @@ -1,25 +1,25 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.StandardTask; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.externalressources.SonarQubeSeverity; -import com.viadee.sonarquest.repositories.StandardTaskRepository; -import com.viadee.sonarquest.rules.SonarQuestTaskStatus; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.when; +import com.viadee.sonarquest.entities.StandardTask; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.externalressources.SonarQubeSeverity; +import com.viadee.sonarquest.repositories.StandardTaskRepository; +import com.viadee.sonarquest.rules.SonarQuestTaskStatus; @ExtendWith(MockitoExtension.class) public class StandardTaskServiceTest { @@ -64,23 +64,23 @@ public void testUpdateStandardTask() { @Test public void testGetLastState() { - StandardTask task = new StandardTask(); - SonarQuestTaskStatus lastState = standardTaskService.getLastState(task); + final StandardTask task = new StandardTask(); + final SonarQuestTaskStatus lastState = standardTaskService.getLastState(task); assertEquals(SonarQuestTaskStatus.OPEN, lastState); } @Test public void testFindByWorld() { // Given - World world = new World(); - List unsortedTasks = new ArrayList<>(); + final World world = new World(); + final List unsortedTasks = new ArrayList<>(); unsortedTasks.add(mockStandardTask("BLOCKER")); unsortedTasks.add(mockStandardTask("MAJOR")); unsortedTasks.add(mockStandardTask("CRITICAL")); unsortedTasks.add(mockStandardTask("MAJOR")); when(standardTaskService.findByWorld(world)).thenReturn(unsortedTasks); // When - List tasks = standardTaskService.findByWorld(world); + final List tasks = standardTaskService.findByWorld(world); // Then assertEquals(SonarQubeSeverity.BLOCKER.name(), tasks.get(0).getSeverity()); assertEquals(SonarQubeSeverity.CRITICAL.name(), tasks.get(1).getSeverity()); @@ -88,8 +88,8 @@ public void testFindByWorld() { assertEquals(SonarQubeSeverity.MAJOR.name(), tasks.get(3).getSeverity()); } - private StandardTask mockStandardTask(String severity) { - StandardTask task = new StandardTask(); + private StandardTask mockStandardTask(final String severity) { + final StandardTask task = new StandardTask(); task.setSeverity(severity); return task; } diff --git a/sonarQuest-frontend/src/app/services/world.service.ts b/sonarQuest-frontend/src/app/services/world.service.ts index e32ae087..44b0d14e 100644 --- a/sonarQuest-frontend/src/app/services/world.service.ts +++ b/sonarQuest-frontend/src/app/services/world.service.ts @@ -4,7 +4,7 @@ import {World} from '../Interfaces/World'; import {environment} from '../../environments/environment'; import {HttpClient} from '@angular/common/http'; import {UserService} from './user.service'; -import { Subject } from 'rxjs'; +import {Subject} from 'rxjs'; @Injectable() export class WorldService { @@ -22,9 +22,9 @@ export class WorldService { constructor(private http: HttpClient, private userService: UserService) { userService.user$.subscribe(user => { - + this.getWorlds().subscribe(worlds => { - if (user.currentWorld == null){ + if (user.currentWorld == null) { this.setCurrentWorld(worlds[0]) } else { this.currentWorldSubject.next(user.currentWorld) @@ -59,12 +59,14 @@ export class WorldService { } public setCurrentWorld(world: World): Observable { - this.http.post(`${environment.endpoint}/world/current`, world).subscribe( - result => { - this.currentWorldSubject.next(result) - }, - err => this.currentWorldSubject.error(err) - ); + if (world) { + this.http.post(`${environment.endpoint}/world/current`, world).subscribe( + result => { + this.currentWorldSubject.next(result) + }, + err => this.currentWorldSubject.error(err) + ); + } return this.currentWorldSubject; } From 612c5c345e7101e9b52fcb9f7fc430e63dda6fdf Mon Sep 17 00:00:00 2001 From: Brown Date: Fri, 6 Mar 2020 16:39:36 +0100 Subject: [PATCH 12/17] Bugfix: Wrong Java Version in pom.xml --- sonarQuest-backend/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index 7db0a8e2..f8382a76 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -35,7 +35,7 @@ UTF-8 UTF-8 - 1.11 + 11 Hoxton.SR1 From 1abbd285e7f975483642d7f31882d030ab270195 Mon Sep 17 00:00:00 2001 From: Brown Date: Fri, 6 Mar 2020 17:21:44 +0100 Subject: [PATCH 13/17] Test Fixes --- .../viadee/sonarquest/entities/Adventure.java | 7 +- .../sonarquest/services/AdventureService.java | 2 +- .../login/LoginControllerIntegrationTest.java | 22 ---- .../services/AdventureServiceTest.java | 2 +- .../services/ArtefactServiceTest.java | 102 +++++++++--------- .../sonarquest/services/QuestServiceTest.java | 29 ++--- .../services/StandardTaskServiceTest.java | 8 -- .../src/test/resources/application.properties | 3 + 8 files changed, 78 insertions(+), 97 deletions(-) delete mode 100644 sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java index f2a214f8..a6842c72 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/entities/Adventure.java @@ -64,12 +64,12 @@ public class Adventure { private World world; @OneToMany(mappedBy = "adventure", cascade = CascadeType.ALL) - private List quests; + private List quests = new ArrayList<>(); @JsonIgnore @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "Adventure_User", joinColumns = @JoinColumn(name = "adventure_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id")) - private List users; + private List users = new ArrayList<>(); public Adventure() { } @@ -99,9 +99,6 @@ public Adventure(final Long id, final String title, final String story, final Ad } public synchronized void addUser(final User user) { - if (users == null) { - users = new ArrayList<>(); - } users.add(user); } diff --git a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java index d9c17eef..41fc55ed 100644 --- a/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java +++ b/sonarQuest-backend/src/main/java/com/viadee/sonarquest/services/AdventureService.java @@ -67,7 +67,7 @@ public Adventure findById(final Long adventureId) { */ public List getJoinedAdventuresForUserInWorld(final World world, final User user) { return adventureRepository.findByWorld(world).stream() - .filter(w -> w.getUsers().contains(user)) + .filter(adventure -> adventure.getUsers().contains(user)) .collect(Collectors.toList()); } diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java deleted file mode 100644 index 9af28664..00000000 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/controllers/login/LoginControllerIntegrationTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.viadee.sonarquest.controllers.login; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; - - -@SpringBootTest -public class LoginControllerIntegrationTest { - - @Autowired - private LoginController controller; - - @Test - public void testInfo() { - final String info = controller.info(); - assertEquals("Dies ist eine Login Seite", info); - } - -} diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java index 741008cf..89818e47 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/AdventureServiceTest.java @@ -52,6 +52,7 @@ public void testGetAllAdventuresForWorldAndUser() { mockAdventure1.addUser(mockUser1); mockAdventure2.addUser(mockUser1); + // init mock repos final List adventuresByUserAndWorld = new ArrayList<>(); adventuresByUserAndWorld.add(mockAdventure1); @@ -64,7 +65,6 @@ public void testGetAllAdventuresForWorldAndUser() { final List users = new ArrayList<>(); users.add(mockUser1); -// when(adventureRepository.findByUsersAndWorld(users, mockWorld)).thenReturn(adventuresByUserAndWorld); when(adventureRepository.findByWorld(mockWorld)).thenReturn(adventuresByWorld); // call method to be tested diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java index 4cea5c42..303ebdbb 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/ArtefactServiceTest.java @@ -1,22 +1,23 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.Artefact; -import com.viadee.sonarquest.entities.Level; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.repositories.ArtefactRepository; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.mockito.Mockito.when; +import com.viadee.sonarquest.entities.Artefact; +import com.viadee.sonarquest.entities.Level; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.repositories.ArtefactRepository; @ExtendWith(MockitoExtension.class) public class ArtefactServiceTest { @@ -30,8 +31,11 @@ public class ArtefactServiceTest { @Mock private LevelService levelService; + @Mock + private UserService userService; + private Artefact mockArtefact() { - Artefact artefact = new Artefact(); + final Artefact artefact = new Artefact(); artefact.setName("Mighty staff of fiery doom"); return artefact; } @@ -39,12 +43,12 @@ private Artefact mockArtefact() { @Test public void testGetArtefacts() { // given - List savedArtefacts = new ArrayList<>(); - Artefact artefact = new Artefact(); + final List savedArtefacts = new ArrayList<>(); + final Artefact artefact = new Artefact(); savedArtefacts.add(artefact); when(artefactRepository.findAll()).thenReturn(savedArtefacts); // When - List artefacts = service.getArtefacts(); + final List artefacts = service.getArtefacts(); // Then assertEquals(artefact, artefacts.get(0)); } @@ -52,12 +56,12 @@ public void testGetArtefacts() { @Test public void testGetArtefactsForMarketplace() { // Given - List savedArtefacts = new ArrayList<>(); - Artefact artefact = new Artefact(); + final List savedArtefacts = new ArrayList<>(); + final Artefact artefact = new Artefact(); savedArtefacts.add(artefact); when(artefactRepository.findByQuantityIsGreaterThanEqual(1L)).thenReturn(savedArtefacts); // When - List artefactsForMarketplace = service.getArtefactsForMarketplace(); + final List artefactsForMarketplace = service.getArtefactsForMarketplace(); // Then assertEquals(artefact, artefactsForMarketplace.get(0)); } @@ -65,10 +69,10 @@ public void testGetArtefactsForMarketplace() { @Test public void testGetArtefact() { // given - Artefact savedArtefact = new Artefact(); + final Artefact savedArtefact = new Artefact(); when(artefactRepository.findById(1L)).thenReturn(Optional.of(savedArtefact)); // When - Artefact artefact = service.getArtefact(1L); + final Artefact artefact = service.getArtefact(1L); // Then assertSame(savedArtefact, artefact); } @@ -76,33 +80,33 @@ public void testGetArtefact() { @Test public void testCreateArtefact_minLevelDoesNotYetExist() { // given - Artefact artefact = mockArtefact(); - Level minLevel = mockLevel(1); + final Artefact artefact = mockArtefact(); + final Level minLevel = mockLevel(1); artefact.setMinLevel(minLevel); when(levelService.findByLevel(1)).thenReturn(null); when(artefactRepository.save(artefact)).thenReturn(artefact); // when - Artefact newArtefact = service.createArtefact(artefact); + final Artefact newArtefact = service.createArtefact(artefact); // then assertSame(minLevel, newArtefact.getMinLevel()); } @Test public void testCreateArtefact_minLevelAlreadyExists() { - Artefact artefact = mockArtefact(); - Level minLevel = mockLevel(1); + final Artefact artefact = mockArtefact(); + final Level minLevel = mockLevel(1); artefact.setMinLevel(minLevel); - Level savedLevel = mockLevel(1); + final Level savedLevel = mockLevel(1); when(levelService.findByLevel(1)).thenReturn(savedLevel); when(artefactRepository.save(artefact)).thenReturn(artefact); // when - Artefact newArtefact = service.createArtefact(artefact); + final Artefact newArtefact = service.createArtefact(artefact); // then assertSame(savedLevel, newArtefact.getMinLevel()); } - private Level mockLevel(int level) { - Level minLevel = new Level(); + private Level mockLevel(final int level) { + final Level minLevel = new Level(); minLevel.setLevelNumber(level); return minLevel; } @@ -115,18 +119,20 @@ private Level mockLevel(int level) { @Test public void testBuyArtefact_Ok() { // Given - Artefact artefact = mockArtefact(); + final Artefact artefact = mockArtefact(); artefact.setId(69L); artefact.setPrice(7L); artefact.setQuantity(1L); artefact.setMinLevel(mockLevel(1)); - User user = new User(); + final User user = new User(); user.setId(1L); user.setGold(10L); user.setLevel(mockLevel(2)); + when(artefactRepository.findById(69L)).thenReturn(Optional.of(artefact)); when(artefactRepository.save(artefact)).thenReturn(artefact); + when(userService.save(user)).thenReturn(user); // When - Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); + final Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(boughtArtefact, artefact); assertEquals(Long.valueOf(0), boughtArtefact.getQuantity()); @@ -142,18 +148,18 @@ public void testBuyArtefact_Ok() { @Test public void testBuyArtefact_InStock_UserCannotAfford() { // Given - Artefact artefact = mockArtefact(); + final Artefact artefact = mockArtefact(); artefact.setId(69L); artefact.setPrice(19L); artefact.setQuantity(1L); artefact.setMinLevel(mockLevel(1)); - User user = new User(); + final User user = new User(); user.setId(1L); user.setGold(10L); user.setLevel(mockLevel(2)); - when(artefactRepository.save(artefact)).thenReturn(artefact); + when(artefactRepository.findById(69L)).thenReturn(Optional.of(artefact)); // When - Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); + final Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(1), artefact.getQuantity()); @@ -169,18 +175,18 @@ public void testBuyArtefact_InStock_UserCannotAfford() { @Test public void testBuyArtefact_ItemSoldOut() { // Given - Artefact artefact = mockArtefact(); + final Artefact artefact = mockArtefact(); artefact.setId(69L); artefact.setPrice(7L); artefact.setQuantity(0L); artefact.setMinLevel(mockLevel(1)); - User user = new User(); + final User user = new User(); user.setId(1L); user.setGold(10L); user.setLevel(mockLevel(2)); - when(artefactRepository.save(artefact)).thenReturn(artefact); + when(artefactRepository.findById(69L)).thenReturn(Optional.of(artefact)); // When - Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); + final Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(0), artefact.getQuantity()); @@ -196,18 +202,18 @@ public void testBuyArtefact_ItemSoldOut() { @Test public void testBuyArtefact_userLevelNotHighEnough() { // Given - Artefact artefact = mockArtefact(); + final Artefact artefact = mockArtefact(); artefact.setId(69L); artefact.setPrice(7L); artefact.setQuantity(1L); artefact.setMinLevel(mockLevel(2)); - User user = new User(); + final User user = new User(); user.setId(1L); user.setGold(10L); user.setLevel(mockLevel(1)); - when(artefactRepository.save(artefact)).thenReturn(artefact); + when(artefactRepository.findById(69L)).thenReturn(Optional.of(artefact)); // When - Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); + final Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(1), artefact.getQuantity()); @@ -223,19 +229,19 @@ public void testBuyArtefact_userLevelNotHighEnough() { @Test public void testBuyArtefact_userAlreadyOwnsArtefact() { // Given - Artefact artefact = mockArtefact(); + final Artefact artefact = mockArtefact(); artefact.setId(69L); artefact.setPrice(7L); artefact.setQuantity(1L); artefact.setMinLevel(mockLevel(1)); - User user = new User(); + final User user = new User(); user.setId(1L); user.setGold(10L); user.setLevel(mockLevel(2)); user.getArtefacts().add(artefact); - when(artefactRepository.save(artefact)).thenReturn(artefact); + when(artefactRepository.findById(69L)).thenReturn(Optional.of(artefact)); // When - Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); + final Artefact boughtArtefact = service.buyArtefact(artefact.getId(), user); // Then assertSame(null, boughtArtefact); assertEquals(Long.valueOf(1), artefact.getQuantity()); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java index 5e80a50d..ed0407a0 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/QuestServiceTest.java @@ -1,22 +1,24 @@ package com.viadee.sonarquest.services; -import com.viadee.sonarquest.entities.Participation; -import com.viadee.sonarquest.entities.Quest; -import com.viadee.sonarquest.entities.User; -import com.viadee.sonarquest.entities.World; -import com.viadee.sonarquest.repositories.ParticipationRepository; -import com.viadee.sonarquest.repositories.QuestRepository; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.when; +import com.viadee.sonarquest.entities.Participation; +import com.viadee.sonarquest.entities.Quest; +import com.viadee.sonarquest.entities.User; +import com.viadee.sonarquest.entities.World; +import com.viadee.sonarquest.repositories.ParticipationRepository; +import com.viadee.sonarquest.repositories.QuestRepository; @ExtendWith(MockitoExtension.class) public class QuestServiceTest { @@ -27,6 +29,9 @@ public class QuestServiceTest { @Mock private ParticipationRepository participationRepository; + @Mock + private WorldService worldService; + @InjectMocks private QuestService questService; @@ -66,7 +71,7 @@ public void testGetAllQuestsForWorldAndDeveloper() { // init mock repos when(participationRepository.findByUser(mockDeveloper)).thenReturn(mockParticipations); when(questRepository.findByWorld(mockWorld)).thenReturn(mockQuests); - + when(worldService.findById(any())).thenReturn(mockWorld); // call method to be tested final List> result = questService.getAllQuestsForWorldAndUser(mockWorld.getId(), mockDeveloper); diff --git a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java index f711df37..320c1f0f 100644 --- a/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java +++ b/sonarQuest-backend/src/test/java/com/viadee/sonarquest/services/StandardTaskServiceTest.java @@ -13,7 +13,6 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.jdbc.core.namedparam.SqlParameterSource; import com.viadee.sonarquest.entities.StandardTask; import com.viadee.sonarquest.entities.World; @@ -38,12 +37,7 @@ public void testUpdateStandardTask() { StandardTask task = new StandardTask(); task.setKey("Color of Magic!"); task.setStatus(SonarQuestTaskStatus.OPEN); - when(standardTaskRepository.save(ArgumentMatchers.any(StandardTask.class))).thenReturn(task); when(standardTaskRepository.saveAndFlush(ArgumentMatchers.any(StandardTask.class))).thenReturn(task); - when(standardTaskRepository.findByKey(task.getKey())).thenReturn(task); - when(template.queryForObject(ArgumentMatchers.anyString(), - ArgumentMatchers.any(SqlParameterSource.class), - ArgumentMatchers.>any())).thenReturn("OPEN"); task = standardTaskService.updateStandardTask(task); @@ -54,11 +48,9 @@ public void testUpdateStandardTask() { createdStandardTask.setKey("createdStandardTask"); createdStandardTask.setStatus(SonarQuestTaskStatus.OPEN); - when(standardTaskRepository.findByKey(createdStandardTask.getKey())).thenReturn(createdStandardTask); standardTaskService.updateStandardTask(createdStandardTask); assertEquals(SonarQuestTaskStatus.OPEN, createdStandardTask.getStatus()); - // case: existing created task -> no external changes } diff --git a/sonarQuest-backend/src/test/resources/application.properties b/sonarQuest-backend/src/test/resources/application.properties index 5bb05552..eca36afc 100644 --- a/sonarQuest-backend/src/test/resources/application.properties +++ b/sonarQuest-backend/src/test/resources/application.properties @@ -5,6 +5,8 @@ security.jwt.algorithm=HS512 # Gütligkeit eines JWTs in Millisekunden security.jwt.validity=7200000 +# Private Key +security.jwt.privatekey=test_key_4_ever # ======================================== # CORS-HEADER @@ -17,6 +19,7 @@ cors.header.active=true spring.application.name=sQ resourceEndpoint=http://localhost:3000 avatar.directory=./avatar +sonarqube.organization_key=viadee # ======================================== # DATASOURCE From 9d17bbc2918a9a90566cef371857eff2436008ea Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Mon, 9 Mar 2020 21:50:17 +0100 Subject: [PATCH 14/17] java version 13 --- sonarQuest-backend/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index f8382a76..cca7d98d 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -35,7 +35,7 @@ UTF-8 UTF-8 - 11 + 13 Hoxton.SR1 From c0904f6753e2f47a63c1bad2e04e73423343eb78 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Fri, 13 Mar 2020 13:36:09 +0100 Subject: [PATCH 15/17] Set Java version to 11 --- sonarQuest-backend/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sonarQuest-backend/pom.xml b/sonarQuest-backend/pom.xml index cca7d98d..f8382a76 100644 --- a/sonarQuest-backend/pom.xml +++ b/sonarQuest-backend/pom.xml @@ -35,7 +35,7 @@ UTF-8 UTF-8 - 13 + 11 Hoxton.SR1 From 67d731505cfb829148561fcd4f7505c663f55703 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Fri, 13 Mar 2020 13:37:48 +0100 Subject: [PATCH 16/17] Updated travis file to match so new API --- .travis.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8d8aed02..39de6b23 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,8 +5,7 @@ addons: sonarcloud: organization: "viadee" #token is provided by the environment variable SONAR_TOKEN in travis settings - token: - secure: $SONAR_TOKEN + token: $SONAR_TOKEN script: # the following command line builds the project, runs the tests with coverage and then executes the SonarCloud analysis - - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install sonar:sonar \ No newline at end of file + - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install sonar:sonar From 36ecc46d1f9b1ff66bdfa619f57c227389639dd0 Mon Sep 17 00:00:00 2001 From: Michael Landreh Date: Fri, 13 Mar 2020 13:54:36 +0100 Subject: [PATCH 17/17] Added hint to use Lombok plug-in to contribution file --- CONTRIBUTING.md | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85b341d9..3cca1668 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,7 +4,7 @@ First of all: Thanks for your interest in joining us on our journey through the The following is a set of guidelines for contributing to sonarQuest which is hosted by the viadee IT-Unternehmensberatung at GitHub. Guidelines are not meant to be rules. And as this is a community project - feel free to share your thoughts and experiences with the community and propose changes to this document in a pull request. -This project and everyone participating in it is governed by the sonarQuest [Code of Conduct] (https://github.com/viadee/sonarQuest/...). By participating, you are expected to uphold this code. +This project and everyone participating in it is governed by the sonarQuest [Code of Conduct](https://github.com/viadee/sonarQuest/...). By participating, you are expected to uphold this code. ## How Can I Contribute? @@ -31,11 +31,20 @@ sonarQuest aims to be a tool with an active community. So wether if your'e a dev Here are some hints on what helps to get those approved and implemented as quick as possible: * check if it has already been [suggested](https://github.com/search?utf8=%E2%9C%93&q=+is%3Aissue+user%3Aviadee+repository%3AsonarQuest). If there are similar issues a discussion beforehand could make sense. -* Also have a look at our [GitProject] (https://github.com/viadee/sonarQuest/projects) - maybe there are already cards you can turn into an issue. +* Also have a look at our [GitProject](https://github.com/viadee/sonarQuest/projects) - maybe there are already cards you can turn into an issue. * open a new issue and label it as an enhancement -* see how our contribution ist discussed and start writing oder testing code ;) +* see how our contribution ist discussed and start writing oder testing code :wink: -### Coding Guidelines +### Coding + +#### Requirements + + ##### Lombok + This project uses [Lombok](https://projectlombok.org/) to avoid boilerplate code. While IntelliJ IDE users have an integrated support for Lombok (otherwise a plugin can be found in the in `File > Setting > Plugins`), Eclipse users have to install the extension manually. + You can find the installation instructions for you IDE [here](https://projectlombok.org/setup/overview). + Please open an issue, if there are any problems. + +#### Coding Guidelines * styleguide: There are no strict styling rules. However, code should be easy to read as it makes reviewing a lot easier for everyone. * the current state of the code is a good reference to start with @@ -45,15 +54,15 @@ Here are some hints on what helps to get those approved and implemented as quick * there shouldn't be any TSLint warnings in the Angular parts of the code * we embrace Clean Code so when in doubt - take a look at Uncle Bob's book or [blog](http://blog.cleancoder.com/). -### Suggesting Pull Request +#### Suggesting Pull Request When you are adding features or other enhancements please create a pull request with a clear documentation of what you've done and why you have done it. It helps, if you make make sure all of your commits are atomic (one feature per commit). Always include a useful log message for your commits. One-line messages are fine for small changes, but bigger changes should be commitetd with more comments, too. -### Pull Request - Admission tests +#### Pull Request - Admission tests Pull requests will only be merged when all integration tests and all ui tests are green. To ensure this run * the sonarquest-backend in your IDE of choice as Unit-Tests (this includes all integration tests) and * npm test in the folder sonarquest-frontend to run Jasmine/Karme ui tests. -When all this works, submit your PR. \ No newline at end of file +When all this works, submit your PR.