From dcfdc13de5823bc216bbc16c72474cab18c50088 Mon Sep 17 00:00:00 2001 From: Yash Raj <56453897+yesyash@users.noreply.github.com> Date: Sun, 7 Jul 2024 22:03:59 +0530 Subject: [PATCH] change project structure, rewrite skills and endorsements apis & update the db diagram to match the new erd diagram (#135) --- .../UserAuthenticationToken.java | 13 +- .../Endorsement/EndorsementController.java | 88 --- .../skilltree/Endorsement/EndorsementDRO.java | 20 - .../skilltree/Endorsement/EndorsementDTO.java | 36 - .../Endorsement/EndorsementModel.java | 39 - .../Endorsement/EndorsementModelFromJSON.java | 39 - .../Endorsement/EndorsementRepository.java | 13 - .../Endorsement/EndorsementService.java | 21 - .../Endorsement/EndorsementServiceImpl.java | 166 ---- .../Endorsement/EndorsementStatus.java | 25 - .../EndorsementList/EndorsementListDRO.java | 18 - .../EndorsementList/EndorsementListDTO.java | 17 - .../EndorsementList/EndorsementListModel.java | 49 -- .../EndorsementListRepository.java | 8 - .../EndorsementListService.java | 43 - .../EndorsementList/EndorsementType.java | 6 - .../Health/HealthCheckController.java | 28 - .../com/RDS/skilltree/Skill/SkillDRO.java | 29 - .../com/RDS/skilltree/Skill/SkillDTO.java | 41 - .../com/RDS/skilltree/Skill/SkillModel.java | 41 - .../RDS/skilltree/Skill/SkillRepository.java | 15 - .../com/RDS/skilltree/Skill/SkillType.java | 6 - .../RDS/skilltree/Skill/SkillsController.java | 69 -- .../RDS/skilltree/Skill/SkillsService.java | 15 - .../skilltree/Skill/SkillsServiceImpl.java | 57 -- .../com/RDS/skilltree/User/JwtUserModel.java | 14 + .../java/com/RDS/skilltree/User/UserDRO.java | 27 +- .../java/com/RDS/skilltree/User/UserDTO.java | 30 +- .../com/RDS/skilltree/User/UserModel.java | 33 +- .../RDS/skilltree/User/UserRepository.java | 3 +- .../User/{UserRole.java => UserRoleEnum.java} | 12 +- .../com/RDS/skilltree/User/UserService.java | 7 +- .../RDS/skilltree/User/UserServiceImpl.java | 24 +- .../skilltree/User/UserSkillStatusEnum.java | 7 + .../RDS/skilltree/User/UserSkillsModel.java | 35 + .../RDS/skilltree/apis/EndorsementsApi.java | 32 + .../com/RDS/skilltree/apis/HealthApi.java | 25 + .../com/RDS/skilltree/apis/SkillsApi.java | 44 ++ .../{Config => config}/SecurityConfig.java | 12 +- .../{Config => config}/WebMvcConfig.java | 2 +- .../RDS/skilltree/enums/SkillTypeEnum.java | 5 + .../EndorsementNotFoundException.java | 7 + .../EntityAlreadyExistsException.java | 2 +- .../GlobalExceptionHandler.java | 46 +- .../InvalidParameterException.java | 2 +- .../NoEntityException.java | 2 +- .../SelfEndorsementNotAllowedException.java | 7 + .../SkillAlreadyExistsException.java | 7 + .../exceptions/SkillNotFoundException.java | 7 + .../exceptions/UserNotFoundException.java | 7 + .../com/RDS/skilltree/models/Endorsement.java | 35 + .../java/com/RDS/skilltree/models/Skill.java | 36 + .../repositories/EndorsementRepository.java | 10 + .../repositories/SkillRepository.java | 10 + .../services/EndorsementService.java | 15 + .../EndorsementServiceImplementation.java | 95 +++ .../RDS/skilltree/services/MetricService.java | 5 + .../MetricServiceImplementation.java} | 16 +- .../RDS/skilltree/services/SkillService.java | 11 + .../services/SkillServiceImplementation.java | 62 ++ .../Response => utils}/GenericResponse.java | 2 +- .../JWTAuthenticationFilter.java | 3 +- .../skilltree/utils/TrackedProperties.java | 21 +- .../utils/UUIDValidationInterceptor.java | 2 +- .../CreateEndorsementViewModel.java | 18 + .../viewmodels/CreateSkillViewModel.java | 19 + .../viewmodels/EndorsementViewModel.java | 27 + .../skilltree/viewmodels/SkillViewModel.java | 25 + .../UpdateEndorsementViewModel.java | 12 + .../skilltree/viewmodels/UserViewModel.java | 22 + .../main/resources/application-dev.properties | 3 +- .../src/main/resources/application.properties | 2 - .../resources/dummy-data/endorsements.json | 142 ---- .../EndorsementsIntegrationTests.java | 589 -------------- .../SecurityContextIntegrationTest.java | 60 -- .../integration/SkillsIntegrationTests.java | 268 ------- .../integration/TestContainerManager.java | 29 - .../unit/EndorsementListServiceTest.java | 95 --- .../unit/EndorsementServiceTest.java | 746 ------------------ .../RDS/skilltree/unit/HealthCheckTest.java | 38 - .../RDS/skilltree/unit/SkillsServiceTest.java | 90 --- .../utils/UUIDValidationInterceptorTest.java | 7 +- 82 files changed, 724 insertions(+), 3092 deletions(-) delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementController.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModelFromJSON.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementService.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementStatus.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDRO.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDTO.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListModel.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListRepository.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListService.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementType.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Health/HealthCheckController.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillModel.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillType.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsService.java delete mode 100644 skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsServiceImpl.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/User/JwtUserModel.java rename skill-tree/src/main/java/com/RDS/skilltree/User/{UserRole.java => UserRoleEnum.java} (55%) create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillStatusEnum.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillsModel.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/apis/EndorsementsApi.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/apis/HealthApi.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/apis/SkillsApi.java rename skill-tree/src/main/java/com/RDS/skilltree/{Config => config}/SecurityConfig.java (91%) rename skill-tree/src/main/java/com/RDS/skilltree/{Config => config}/WebMvcConfig.java (96%) create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/enums/SkillTypeEnum.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/exceptions/EndorsementNotFoundException.java rename skill-tree/src/main/java/com/RDS/skilltree/{Exceptions => exceptions}/EntityAlreadyExistsException.java (80%) rename skill-tree/src/main/java/com/RDS/skilltree/{utils => exceptions}/GlobalExceptionHandler.java (70%) rename skill-tree/src/main/java/com/RDS/skilltree/{Exceptions => exceptions}/InvalidParameterException.java (85%) rename skill-tree/src/main/java/com/RDS/skilltree/{Exceptions => exceptions}/NoEntityException.java (89%) create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/exceptions/SelfEndorsementNotAllowedException.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillAlreadyExistsException.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillNotFoundException.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/exceptions/UserNotFoundException.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/models/Endorsement.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/models/Skill.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/repositories/EndorsementRepository.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/repositories/SkillRepository.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementService.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementServiceImplementation.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/services/MetricService.java rename skill-tree/src/main/java/com/RDS/skilltree/{metrics/MetricService.java => services/MetricServiceImplementation.java} (57%) create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/services/SkillService.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/services/SkillServiceImplementation.java rename skill-tree/src/main/java/com/RDS/skilltree/{Common/Response => utils}/GenericResponse.java (89%) rename skill-tree/src/main/java/com/RDS/skilltree/{Filters => utils}/JWTAuthenticationFilter.java (96%) create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateEndorsementViewModel.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateSkillViewModel.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/viewmodels/EndorsementViewModel.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/viewmodels/SkillViewModel.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UpdateEndorsementViewModel.java create mode 100644 skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UserViewModel.java delete mode 100644 skill-tree/src/main/resources/dummy-data/endorsements.json delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/integration/EndorsementsIntegrationTests.java delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/integration/SecurityContextIntegrationTest.java delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/integration/SkillsIntegrationTests.java delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/integration/TestContainerManager.java delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementListServiceTest.java delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementServiceTest.java delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/unit/HealthCheckTest.java delete mode 100644 skill-tree/src/test/java/com/RDS/skilltree/unit/SkillsServiceTest.java diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java b/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java index e2efea72..5799bfc8 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/Authentication/UserAuthenticationToken.java @@ -1,7 +1,7 @@ package com.RDS.skilltree.Authentication; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRole; +import com.RDS.skilltree.User.JwtUserModel; +import com.RDS.skilltree.User.UserRoleEnum; import java.util.List; import javax.security.auth.Subject; import org.springframework.security.authentication.AbstractAuthenticationToken; @@ -9,11 +9,12 @@ public class UserAuthenticationToken extends AbstractAuthenticationToken { - private final UserModel user; + private final JwtUserModel user; public UserAuthenticationToken(String role, String rdsUserId) { - super(List.of(new SimpleGrantedAuthority(UserRole.fromString(role).name()))); - this.user = UserModel.builder().rdsUserId(rdsUserId).role(UserRole.fromString(role)).build(); + super(List.of(new SimpleGrantedAuthority(UserRoleEnum.fromString(role).name()))); + + this.user = new JwtUserModel(rdsUserId, UserRoleEnum.fromString(role)); setAuthenticated(true); } @@ -23,7 +24,7 @@ public Object getCredentials() { } @Override - public UserModel getPrincipal() { + public JwtUserModel getPrincipal() { return user; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementController.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementController.java deleted file mode 100644 index 7b154118..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementController.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import com.RDS.skilltree.Common.Response.GenericResponse; -import jakarta.persistence.EntityNotFoundException; -import jakarta.validation.Valid; -import jakarta.validation.constraints.Min; -import java.io.IOException; -import java.util.UUID; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@RequestMapping("/v1/endorsements") -@Slf4j -@RequiredArgsConstructor -public class EndorsementController { - private final EndorsementService endorsementService; - - @GetMapping(value = "") - public ResponseEntity> getAllEndorsements( - @RequestParam(name = "offset", defaultValue = "0", required = false) @Min(0) int offset, - @RequestParam(name = "limit", defaultValue = "10", required = false) @Min(1) int limit, - @RequestParam(name = "skillID", required = false) String skillID, - @RequestParam(name = "userID", required = false) String userID, - @RequestParam(name = "dummyData", required = false) boolean dummyData) - throws IOException { - PageRequest pageRequest = PageRequest.of(offset, limit); - if (dummyData) { - Page pagedEndorsements = - endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, userID); - if (pagedEndorsements.isEmpty()) { - return ResponseEntity.noContent().build(); - } else { - return ResponseEntity.ok(pagedEndorsements); - } - } else { - return ResponseEntity.ok(endorsementService.getEndorsements(pageRequest)); - } - } - - @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity> getEndorsementById( - @PathVariable(value = "id", required = true) String id) { - try { - UUID uuid = UUID.fromString(id); - EndorsementDTO response = endorsementService.getEndorsementById(uuid); - return ResponseEntity.ok() - .body(new GenericResponse(response, "Data retrieved successfully")); - } catch (IllegalArgumentException e) { - String message = "Invalid UUID: " + id; - return ResponseEntity.status(HttpStatus.BAD_REQUEST) - .body(new GenericResponse(null, message)); - } catch (EntityNotFoundException e) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(new GenericResponse(null, e.getMessage())); - } catch (Exception e) { - String message = "Something went wrong. Please contact admin."; - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) - .body(new GenericResponse(null, message)); - } - } - - @PostMapping(value = "") - public ResponseEntity> postEndorsement( - @RequestBody @Valid EndorsementDRO endorsementDRO) { - - EndorsementModel endorsementModel = endorsementService.createEndorsement(endorsementDRO); - if (endorsementModel != null) - return new ResponseEntity<>( - new GenericResponse(EndorsementDTO.toDto(endorsementModel), ""), - HttpStatus.CREATED); - return new ResponseEntity<>( - new GenericResponse(null, "Failed to create endorsement"), - HttpStatus.BAD_REQUEST); - } - - @PatchMapping(value = "/{id}") - public ResponseEntity> updateEndorsementStatus( - @PathVariable(value = "id") UUID id, @RequestParam String status) { - return ResponseEntity.ok().body(endorsementService.updateEndorsementStatus(id, status)); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java deleted file mode 100644 index d0910431..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDRO.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import jakarta.validation.constraints.NotNull; -import java.util.UUID; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@NoArgsConstructor -@AllArgsConstructor -@Data -@Builder -public class EndorsementDRO { - @NotNull(message = "user id cannot be null") - private UUID endorseeId; - - @NotNull(message = "skill id cannot be null") - private UUID skillId; -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java deleted file mode 100644 index 3047e63f..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementDTO.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import com.RDS.skilltree.EndorsementList.EndorsementListModel; -import com.RDS.skilltree.Skill.SkillDTO; -import com.RDS.skilltree.utils.TrackedProperties; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.util.List; -import java.util.UUID; -import lombok.*; - -@Getter -@Builder -@JsonIgnoreProperties(ignoreUnknown = true) -public class EndorsementDTO extends TrackedProperties { - private UUID id; - private UUID endorseeId; - private SkillDTO skill; - private EndorsementStatus status; - private List endorsersList; - - public static EndorsementDTO toDto(EndorsementModel endorsementModel) { - EndorsementDTO endorsementDTO = - EndorsementDTO.builder() - .id(endorsementModel.getId()) - .endorseeId(endorsementModel.getEndorseeId()) - .skill(SkillDTO.toDto(endorsementModel.getSkill())) - .status(endorsementModel.getStatus()) - .endorsersList(endorsementModel.getEndorsersList()) - .build(); - endorsementDTO.setCreatedAt(endorsementModel.getCreatedAt()); - endorsementDTO.setUpdatedAt(endorsementModel.getUpdatedAt()); - endorsementDTO.setCreatedBy(endorsementModel.getCreatedBy()); - endorsementDTO.setUpdatedBy(endorsementModel.getUpdatedBy()); - return endorsementDTO; - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java deleted file mode 100644 index 68a3faec..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModel.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import com.RDS.skilltree.EndorsementList.EndorsementListModel; -import com.RDS.skilltree.Skill.SkillModel; -import com.RDS.skilltree.utils.TrackedProperties; -import com.fasterxml.jackson.annotation.JsonManagedReference; -import jakarta.persistence.*; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import lombok.*; - -@AllArgsConstructor -@NoArgsConstructor -@Entity -@Builder -@Getter -@Table(name = "endorsements") -public class EndorsementModel extends TrackedProperties { - @Id - @GeneratedValue - @Column(name = "id", columnDefinition = "BINARY(16)") - private UUID id; - - @Column(name = "endorsee_id") - private UUID endorseeId; - - @ManyToOne(targetEntity = SkillModel.class, cascade = CascadeType.ALL) - @JoinColumn(name = "skill_id", referencedColumnName = "id") - private SkillModel skill; - - @OneToMany(mappedBy = "endorsement") - @JsonManagedReference - private List endorsersList = new ArrayList<>(); - - @Column(name = "endorsement_status") - @Enumerated(value = EnumType.STRING) - private EndorsementStatus status = EndorsementStatus.PENDING; -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModelFromJSON.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModelFromJSON.java deleted file mode 100644 index c399043d..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementModelFromJSON.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; -import java.time.LocalDateTime; -import java.util.UUID; -import lombok.*; - -/* TODO:Dummy JSON code, needs to be changed as part of #103 */ -@Data -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -public class EndorsementModelFromJSON { - private UUID id; - - @JsonProperty("user_id") - private UUID userID; - - @JsonProperty("skill_id") - private UUID skillId; - - private String status; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS") - @JsonProperty("created_at") - private LocalDateTime createdAt; - - @JsonProperty("created_by") - private UUID createdBy; - - @JsonProperty("updated_at") - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SSSSSS") - private LocalDateTime updatedAt; - - @JsonProperty("updated_by") - private UUID updatedBy; -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java deleted file mode 100644 index 6da326dd..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import java.util.List; -import java.util.UUID; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface EndorsementRepository extends JpaRepository { - List findByEndorseeId(UUID userId); - - List findBySkillId(UUID skillId); -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementService.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementService.java deleted file mode 100644 index a7254a48..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import com.RDS.skilltree.Common.Response.GenericResponse; -import java.io.IOException; -import java.util.UUID; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; - -public interface EndorsementService { - EndorsementDTO getEndorsementById(UUID id); - - Page getEndorsements(PageRequest pageRequest); - - /* TODO:Dummy JSON code, needs to be changed as part of #103 */ - Page getEndorsementsFromDummyData( - PageRequest pageRequest, String skillID, String userID) throws IOException; - - EndorsementModel createEndorsement(EndorsementDRO endorsementDRO); - - GenericResponse updateEndorsementStatus(UUID id, String status); -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java deleted file mode 100644 index fce1ed63..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementServiceImpl.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import com.RDS.skilltree.Common.Response.GenericResponse; -import com.RDS.skilltree.Exceptions.EntityAlreadyExistsException; -import com.RDS.skilltree.Exceptions.InvalidParameterException; -import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.Skill.SkillModel; -import com.RDS.skilltree.Skill.SkillRepository; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRole; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import jakarta.persistence.EntityNotFoundException; -import java.io.IOException; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; -import lombok.RequiredArgsConstructor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.ClassPathResource; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Service; - -@Service -@RequiredArgsConstructor -public class EndorsementServiceImpl implements EndorsementService { - private final EndorsementRepository endorsementRepository; - private final SkillRepository skillRepository; - - private final ObjectMapper objectMapper; - - @Value("${endorsements.dummmy-data.path}") - private String dummyEndorsementDataPath; - - private static final Logger logger = LoggerFactory.getLogger(EndorsementServiceImpl.class); - - @Override - public EndorsementDTO getEndorsementById(UUID id) throws IllegalStateException { - Optional endorsementModel = endorsementRepository.findById(id); - return EndorsementDTO.toDto( - endorsementModel.orElseThrow( - () -> new EntityNotFoundException("No endorsement with the id " + id + " found"))); - } - - @Override - public Page getEndorsements(PageRequest pageRequest) { - return endorsementRepository.findAll(pageRequest); - } - - /* TODO:Dummy JSON code, needs to be changed as part of #103 */ - @Override - public Page getEndorsementsFromDummyData( - PageRequest pageRequest, String skillID, String userID) throws IOException { - - try { - List endorsementModelFromJSONList = readEndorsementsFromJSON(); - - if (endorsementModelFromJSONList.isEmpty()) { - return Page.empty(pageRequest); - } - - List filteredEndorsements = - filterEndorsements(endorsementModelFromJSONList, skillID, userID); - return createPagedEndorsements(filteredEndorsements, pageRequest); - } catch (IOException e) { - logger.error("Error reading endorsements JSON data: {}", e.getMessage()); - throw new IOException("Error reading endorsements JSON data", e); - } - } - - private List readEndorsementsFromJSON() throws IOException { - ClassPathResource resource = new ClassPathResource(dummyEndorsementDataPath); - return objectMapper.readValue( - resource.getInputStream(), new TypeReference>() {}); - } - - private List filterEndorsements( - List endorsements, String skillID, String userID) { - return endorsements.stream() - .filter(endorsement -> isMatchingSkillId(endorsement, skillID)) - .filter(endorsement -> isMatchingUserId(endorsement, userID)) - .collect(Collectors.toList()); - } - - private boolean isMatchingSkillId(EndorsementModelFromJSON endorsement, String skillID) { - return skillID == null - || skillID.isEmpty() - || endorsement.getSkillId().equals(UUID.fromString(skillID)); - } - - private boolean isMatchingUserId(EndorsementModelFromJSON endorsement, String userID) { - return userID == null - || userID.isEmpty() - || endorsement.getUserID().equals(UUID.fromString(userID)); - } - - private Page createPagedEndorsements( - List endorsements, PageRequest pageRequest) { - int startIdx = (int) pageRequest.getOffset(); - int totalEndorsements = endorsements.size(); - - if (startIdx >= totalEndorsements) { - return Page.empty(pageRequest); - } - - int endIdx = Math.min(startIdx + pageRequest.getPageSize(), endorsements.size()); - List currentPageEndorsements = endorsements.subList(startIdx, endIdx); - return new PageImpl<>(currentPageEndorsements, pageRequest, endorsements.size()); - } - - @Override - public EndorsementModel createEndorsement(EndorsementDRO endorsementDRO) { - UUID userId = endorsementDRO.getEndorseeId(); - UUID skillId = endorsementDRO.getSkillId(); - - Optional skillOptional = skillRepository.findById(skillId); - if (skillOptional.isPresent()) { - EndorsementModel endorsementModel = - EndorsementModel.builder().endorseeId(userId).skill(skillOptional.get()).build(); - - return endorsementRepository.save(endorsementModel); - } else { - - throw new NoEntityException("Skill with id:" + skillId + " not found"); - } - } - - @Override - public GenericResponse updateEndorsementStatus(UUID id, String status) { - UserModel user = - (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); - if (!user.getRole().equals(UserRole.SUPERUSER)) { - throw new AccessDeniedException("Unauthorized, Access is only available to super users"); - } - - EndorsementStatus endorsementStatus = EndorsementStatus.fromString(status); - if (endorsementStatus.equals(EndorsementStatus.PENDING)) { - throw new InvalidParameterException("endorsement status", status); - } - Optional optionalEndorsementModel = endorsementRepository.findById(id); - if (optionalEndorsementModel.isPresent()) { - if (optionalEndorsementModel.get().getStatus() != EndorsementStatus.PENDING) { - throw new EntityAlreadyExistsException( - "Endorsement is already updated. Cannot modify status"); - } - EndorsementModel updatedEndorsementModel = - EndorsementModel.builder() - .id(optionalEndorsementModel.get().getId()) - .endorseeId(optionalEndorsementModel.get().getEndorseeId()) - .skill(optionalEndorsementModel.get().getSkill()) - .endorsersList(optionalEndorsementModel.get().getEndorsersList()) - .status(EndorsementStatus.valueOf(status)) - .build(); - endorsementRepository.save(updatedEndorsementModel); - return new GenericResponse<>(null, "Successfully updated endorsement status"); - } - throw new NoEntityException("No endorsement with id " + id + " was found"); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementStatus.java b/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementStatus.java deleted file mode 100644 index 9300b618..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Endorsement/EndorsementStatus.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.RDS.skilltree.Endorsement; - -import com.RDS.skilltree.Exceptions.InvalidParameterException; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public enum EndorsementStatus { - APPROVED, - PENDING, - REJECTED; - - private static final Map endorsementStatusMap = - Stream.of(values()) - .collect(Collectors.toMap(EndorsementStatus::toString, Function.identity())); - - public static EndorsementStatus fromString(final String name) { - EndorsementStatus endorsementStatus = endorsementStatusMap.get(name); - if (endorsementStatus == null) { - throw new InvalidParameterException("endorsement status", name); - } - return endorsementStatus; - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDRO.java b/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDRO.java deleted file mode 100644 index 99ad11b2..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDRO.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.RDS.skilltree.EndorsementList; - -import java.util.UUID; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@AllArgsConstructor -@NoArgsConstructor -@Data -@Builder -public class EndorsementListDRO { - private String description; - private UUID endorsementId; - private UUID endorserId; - private EndorsementType type; -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDTO.java b/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDTO.java deleted file mode 100644 index d840d6c9..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListDTO.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.RDS.skilltree.EndorsementList; - -import com.RDS.skilltree.User.UserModel; -import java.util.UUID; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -@Builder -@Data -@AllArgsConstructor -public class EndorsementListDTO { - private UUID id; - private String description; - private UserModel endorser; - private EndorsementType type; -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListModel.java b/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListModel.java deleted file mode 100644 index c734925d..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListModel.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.RDS.skilltree.EndorsementList; - -import com.RDS.skilltree.Endorsement.EndorsementModel; -import com.RDS.skilltree.utils.TrackedProperties; -import com.fasterxml.jackson.annotation.JsonBackReference; -import jakarta.persistence.*; -import java.util.UUID; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; - -@EqualsAndHashCode(callSuper = true) -@Entity -@NoArgsConstructor -@Data -@Table(name = "endorsement_list") -public class EndorsementListModel extends TrackedProperties { - @Id - @GeneratedValue - @Column(name = "id", columnDefinition = "BINARY(16)") - private UUID id; - - @JoinColumn(name = "endorsement_id", referencedColumnName = "id") - @ManyToOne(targetEntity = EndorsementModel.class, cascade = CascadeType.ALL) - @JsonBackReference - private EndorsementModel endorsement; - - @Column(name = "endorser_id") - private UUID endorserId; - - @Column(name = "description") - private String description; - - @Column(name = "is_deleted", nullable = false) - private boolean deleted; - - @Column(name = "type", nullable = false) - @Enumerated(value = EnumType.STRING) - private EndorsementType type; - - public EndorsementListModel( - EndorsementModel endorsement, UUID endorserId, String description, EndorsementType type) { - this.endorsement = endorsement; - this.endorserId = endorserId; - this.description = description; - this.type = type; - this.deleted = false; - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListRepository.java deleted file mode 100644 index ce372c5f..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.RDS.skilltree.EndorsementList; - -import java.util.UUID; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface EndorsementListRepository extends JpaRepository {} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListService.java b/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListService.java deleted file mode 100644 index c26308b2..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementListService.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.RDS.skilltree.EndorsementList; - -import com.RDS.skilltree.Endorsement.EndorsementModel; -import com.RDS.skilltree.Endorsement.EndorsementRepository; -import com.RDS.skilltree.Exceptions.NoEntityException; -import java.util.Optional; -import java.util.UUID; -import org.springframework.stereotype.Service; - -@Service -public class EndorsementListService { - - private final EndorsementListRepository endorsementListRepository; - private final EndorsementRepository endorsementRepository; - - public EndorsementListService( - EndorsementListRepository endorsementListRepository, - EndorsementRepository endorsementRepository) { - this.endorsementListRepository = endorsementListRepository; - this.endorsementRepository = endorsementRepository; - } - - public EndorsementListModel createEndorsementListEntry(EndorsementListDRO endorsementListDRO) { - EndorsementListModel endorsementListEntry = new EndorsementListModel(); - - UUID endorserId = endorsementListDRO.getEndorserId(); - UUID endorsementId = endorsementListDRO.getEndorsementId(); - - Optional endorsementOptional = endorsementRepository.findById(endorsementId); - if (endorsementOptional.isPresent()) { - - endorsementListEntry.setEndorserId(endorserId); - endorsementListEntry.setEndorsement(endorsementOptional.get()); - endorsementListEntry.setDescription(endorsementListDRO.getDescription()); - endorsementListEntry.setType(endorsementListDRO.getType()); - endorsementListRepository.save(endorsementListEntry); - return endorsementListEntry; - - } else { - throw new NoEntityException("Endorsement with id:" + endorsementId + " not found"); - } - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementType.java b/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementType.java deleted file mode 100644 index 1d028fc8..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/EndorsementList/EndorsementType.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.RDS.skilltree.EndorsementList; - -public enum EndorsementType { - POSITIVE, - NEGATIVE -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Health/HealthCheckController.java b/skill-tree/src/main/java/com/RDS/skilltree/Health/HealthCheckController.java deleted file mode 100644 index 854ddece..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Health/HealthCheckController.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.RDS.skilltree.Health; - -import com.RDS.skilltree.metrics.MetricService; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/v1/health") -@Slf4j -public class HealthCheckController { - - private final MetricService metricService; - - @Autowired - public HealthCheckController(MetricService metricService) { - this.metricService = metricService; - } - - @GetMapping("") - public Map checkHealth() { - double uptime = metricService.getUptime(); - return Map.of("uptimeInSeconds", uptime); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java deleted file mode 100644 index 543c4ace..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDRO.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.RDS.skilltree.Skill; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import jakarta.validation.constraints.NotNull; -import java.util.UUID; -import lombok.Builder; -import lombok.Getter; - -@Getter -@Builder -@JsonIgnoreProperties(ignoreUnknown = true) -public class SkillDRO { - @NotNull(message = "Name cannot be null") - private String name; - - @NotNull(message = "SkillType cannot be null") - private SkillType type; - - @NotNull(message = "Created by user Id cannot be null") - private UUID createdBy; - - public static SkillModel toModel(SkillDRO skillDRO) { - return SkillModel.builder() - .name(skillDRO.getName()) - .type(skillDRO.getType()) - .deleted(false) - .build(); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java deleted file mode 100644 index a6304e2b..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillDTO.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.RDS.skilltree.Skill; - -import com.RDS.skilltree.User.UserDTO; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; -import lombok.Builder; -import lombok.Getter; - -@Getter -@Builder -@JsonIgnoreProperties(ignoreUnknown = true) -public class SkillDTO { - private UUID id; - private SkillType type; - private String name; - private Set users; - - public static SkillDTO toDto(SkillModel skillModel) { - return SkillDTO.builder() - .id(skillModel.getId()) - .name(skillModel.getName()) - .type(skillModel.getType()) - .build(); - } - - public static SkillDTO getSkillsWithUsers(SkillModel skillModel) { - Set users = new HashSet<>(); - if (skillModel.getUsers() != null) { - users = skillModel.getUsers().stream().map(UserDTO::toDTO).collect(Collectors.toSet()); - } - return SkillDTO.builder() - .id(skillModel.getId()) - .name(skillModel.getName()) - .type(skillModel.getType()) - .users(users) - .build(); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillModel.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillModel.java deleted file mode 100644 index 0074c602..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillModel.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.RDS.skilltree.Skill; - -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.utils.TrackedProperties; -import com.fasterxml.jackson.annotation.JsonBackReference; -import com.fasterxml.jackson.annotation.JsonIgnore; -import jakarta.persistence.*; -import java.util.Set; -import java.util.UUID; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; - -@AllArgsConstructor -@NoArgsConstructor -@Entity -@Builder -@Getter -@Table(name = "Skill") -public class SkillModel extends TrackedProperties { - @Id - @GeneratedValue - @Column(name = "id", columnDefinition = "BINARY(16)") - private UUID id; - - @Column(name = "name", unique = true, nullable = false) - private String name; - - @Column(name = "skill_type", nullable = false) - @Enumerated(value = EnumType.STRING) - private SkillType type = SkillType.ATOMIC; - - @Column(name = "is_deleted", nullable = false) - private boolean deleted; - - @JsonBackReference - @JsonIgnore - @ManyToMany(mappedBy = "skills", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - private Set users; -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java deleted file mode 100644 index a523a3b0..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.RDS.skilltree.Skill; - -import java.util.Optional; -import java.util.UUID; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface SkillRepository extends JpaRepository { - Optional findByName(String name); - - Page findAll(Pageable pageable); -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillType.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillType.java deleted file mode 100644 index 32500383..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillType.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.RDS.skilltree.Skill; - -public enum SkillType { - ATOMIC, - DERIVED -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java deleted file mode 100644 index 00e9f669..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsController.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.RDS.skilltree.Skill; - -import com.RDS.skilltree.utils.MessageResponse; -import jakarta.validation.Valid; -import jakarta.validation.constraints.Min; -import java.util.UUID; -import lombok.extern.slf4j.Slf4j; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.util.ObjectUtils; -import org.springframework.web.bind.annotation.*; - -@RestController -@Slf4j -@RequestMapping("/v1/skills") -public class SkillsController { - private final SkillsService skillsService; - - public SkillsController(SkillsService skillsService) { - this.skillsService = skillsService; - } - - @PostMapping("/") - public ResponseEntity createSkill(@RequestBody(required = true) @Valid SkillDRO skillDRO) { - try { - return ResponseEntity.status(HttpStatus.CREATED).body(skillsService.createSkill(skillDRO)); - } catch (DataIntegrityViolationException ex) { - return ResponseEntity.status(HttpStatus.CONFLICT) - .body(new MessageResponse("Cannot create entry for Skill as Skill name is duplicate")); - } catch (Exception ex) { - log.error( - "There is some error in storing the skills, error message: {}", ex.getMessage(), ex); - throw ex; - } - } - - @GetMapping("/") - public Page getAllSkills( - @RequestParam(value = "offset", defaultValue = "0", required = false) @Min(0) int offset, - @RequestParam(value = "limit", defaultValue = "10", required = false) @Min(1) int limit) { - Pageable pageable = PageRequest.of(offset, limit); - return skillsService.getAllSkills(pageable); - } - - @GetMapping("/name/{name}") - public ResponseEntity getSkillByName( - @PathVariable(value = "name", required = true) String name) { - SkillDTO skillDTO = skillsService.getSkillByName(name); - if (ObjectUtils.isEmpty(skillDTO)) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(new MessageResponse("Skill not found with the given name")); - } - return ResponseEntity.ok(skillDTO); - } - - @GetMapping("/{id}") - public ResponseEntity getSkillById(@PathVariable(value = "id", required = true) UUID id) { - SkillDTO skillDTO = skillsService.getSkillById(id); - if (ObjectUtils.isEmpty(skillDTO)) { - return ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(new MessageResponse("Skill not found with given Id")); - } - return ResponseEntity.ok(skillDTO); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsService.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsService.java deleted file mode 100644 index b8a4e015..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.RDS.skilltree.Skill; - -import java.util.UUID; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -public interface SkillsService { - SkillDTO getSkillById(UUID id); - - SkillDTO getSkillByName(String skillName); - - Page getAllSkills(Pageable pageable); - - SkillDTO createSkill(SkillDRO skillDRO); -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsServiceImpl.java b/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsServiceImpl.java deleted file mode 100644 index 61943723..00000000 --- a/skill-tree/src/main/java/com/RDS/skilltree/Skill/SkillsServiceImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.RDS.skilltree.Skill; - -import com.RDS.skilltree.User.UserRepository; -import java.time.Instant; -import java.util.Optional; -import java.util.UUID; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; - -@Service -@Slf4j -@RequiredArgsConstructor -public class SkillsServiceImpl implements SkillsService { - private final SkillRepository skillRepository; - private final UserRepository userRepository; - - @Override - public SkillDTO getSkillById(UUID id) { - Optional skillModel = skillRepository.findById(id); - return skillModel.map(SkillDTO::getSkillsWithUsers).orElse(null); - } - - @Override - public SkillDTO getSkillByName(String skillName) { - Optional skillModel = skillRepository.findByName(skillName); - return skillModel.map(SkillDTO::getSkillsWithUsers).orElse(null); - } - - @Override - public Page getAllSkills(Pageable pageable) { - Page skillModels = skillRepository.findAll(pageable); - return skillModels.map(SkillDTO::getSkillsWithUsers); - } - - @Override - public SkillDTO createSkill(SkillDRO skillDRO) { - SkillModel newSkill = SkillDRO.toModel(skillDRO); - newSkill.setCreatedAt(Instant.now()); - newSkill.setUpdatedAt(Instant.now()); - - try { - skillRepository.save(newSkill); - } catch (DataIntegrityViolationException ex) { - log.error( - "Error saving the skills object with name : {}, with exception :{}", - skillDRO.getName(), - ex.getMessage(), - ex); - throw ex; - } - return SkillDTO.toDto(newSkill); - } -} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/JwtUserModel.java b/skill-tree/src/main/java/com/RDS/skilltree/User/JwtUserModel.java new file mode 100644 index 00000000..29b92988 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/JwtUserModel.java @@ -0,0 +1,14 @@ +package com.RDS.skilltree.User; + +import lombok.Getter; + +@Getter +public class JwtUserModel { + private final String rdsUserId; + private final UserRoleEnum role; + + public JwtUserModel(String rdsUserId, UserRoleEnum role) { + this.role = role; + this.rdsUserId = rdsUserId; + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java index c0141963..79bd6b2c 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDRO.java @@ -20,25 +20,19 @@ public class UserDRO { private URL imageUrl; - private UserRole role; + private UserRoleEnum role; public static UserModel toModel(UserDRO user) { return UserModel.builder() .rdsUserId(user.getRdsUserId()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .role(user.getRole()) - .imageUrl(user.getImageUrl()) + // .role(user.getRole()) .build(); } public static UserDRO fromModel(UserModel user) { return UserDRO.builder() .rdsUserId(user.getRdsUserId()) - .role(user.getRole()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .imageUrl(user.getImageUrl()) + // .role(user.getRole()) .build(); } @@ -46,18 +40,9 @@ public static UserModel compareAndUpdateModel(UserModel user, UserDRO userDRO) { if (userDRO.getRdsUserId() != null) { user.setRdsUserId(user.getRdsUserId()); } - if (userDRO.getFirstName() != null) { - user.setFirstName(user.getFirstName()); - } - if (userDRO.getLastName() != null) { - user.setLastName(user.getLastName()); - } - if (userDRO.getImageUrl() != null) { - user.setImageUrl(user.getImageUrl()); - } - if (userDRO.getRole() != null) { - user.setRole(user.getRole()); - } + // if (userDRO.getRole() != null) { + // user.setRole(user.getRole()); + // } user.setUpdatedAt(Instant.now()); return user; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java index fedccf7b..87ceb395 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserDTO.java @@ -1,10 +1,8 @@ package com.RDS.skilltree.User; -import com.RDS.skilltree.Skill.SkillDTO; +import com.RDS.skilltree.models.Skill; import java.net.URL; import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; import lombok.Builder; import lombok.Getter; @@ -12,7 +10,7 @@ @Builder public class UserDTO { - private UUID id; + private String id; private String rdsUserId; @@ -22,34 +20,24 @@ public class UserDTO { private URL imageUrl; - private UserRole role; + private UserRoleEnum role; - private Set skills; + private Set skills; public static UserDTO toDTO(UserModel user) { - return UserDTO.builder() - .id(user.getId()) - .rdsUserId(user.getRdsUserId()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .imageUrl(user.getImageUrl()) - .role(user.getRole()) - .build(); + return UserDTO.builder().id(user.getId()).rdsUserId(user.getRdsUserId()).build(); } public static UserDTO getUsersWithSkills(UserModel user) { - Set skills = - user.getSkills().stream().map(SkillDTO::toDto).collect(Collectors.toSet()); + // Set skills = [] + // user.getSkills().stream().map(SkillDTO::toDto).collect(Collectors.toSet()); return UserDTO.builder() .id(user.getId()) .rdsUserId(user.getRdsUserId()) - .firstName(user.getFirstName()) - .lastName(user.getLastName()) - .imageUrl(user.getImageUrl()) - .skills(skills) - .role(user.getRole()) + // .skills(skills) + // .role(user.getRole()) .build(); } } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java index 42776846..65f4f8af 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserModel.java @@ -1,13 +1,8 @@ package com.RDS.skilltree.User; -import com.RDS.skilltree.Skill.SkillModel; import com.RDS.skilltree.utils.TrackedProperties; -import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import jakarta.persistence.*; -import java.net.URL; -import java.util.Set; -import java.util.UUID; import lombok.*; @Entity @@ -17,34 +12,12 @@ @JsonSerialize @NoArgsConstructor @AllArgsConstructor -@Table(name = "Users") +@Table(name = "users") public class UserModel extends TrackedProperties { @Id - @GeneratedValue - @Column(name = "id", columnDefinition = "BINARY(16)") - private UUID id; + @Column(name = "id") + private String id; @Column(name = "rds_user_id", unique = true) private String rdsUserId; - - @Column(name = "first_name", nullable = false) - private String firstName; - - @Column(name = "last_name") - private String lastName; - - @Column(name = "image_url", nullable = false) - private URL imageUrl; - - @Column(name = "user_role", nullable = false) - @Enumerated(value = EnumType.STRING) - private UserRole role = UserRole.USER; - - @JsonManagedReference - @ManyToMany(targetEntity = SkillModel.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable( - name = "user_skill", - joinColumns = @JoinColumn(name = "user_id"), - inverseJoinColumns = @JoinColumn(name = "skill_id")) - private Set skills; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserRepository.java index a557c19e..6700fd30 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserRepository.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserRepository.java @@ -1,8 +1,7 @@ package com.RDS.skilltree.User; -import java.util.UUID; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository -public interface UserRepository extends JpaRepository {} +public interface UserRepository extends JpaRepository {} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserRole.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserRoleEnum.java similarity index 55% rename from skill-tree/src/main/java/com/RDS/skilltree/User/UserRole.java rename to skill-tree/src/main/java/com/RDS/skilltree/User/UserRoleEnum.java index 04e1adaa..78caeac6 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserRole.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserRoleEnum.java @@ -2,7 +2,7 @@ import java.util.Arrays; -public enum UserRole { +public enum UserRoleEnum { USER("user"), MEMBER("member"), SUPERUSER("super_user"), @@ -10,20 +10,20 @@ public enum UserRole { public final String label; - UserRole(String label) { + UserRoleEnum(String label) { this.label = label; } - public static UserRole fromString(String text) { - for (UserRole role : UserRole.values()) { + public static UserRoleEnum fromString(String text) { + for (UserRoleEnum role : UserRoleEnum.values()) { if (role.label.equalsIgnoreCase(text)) { return role; } } - return UserRole.GUEST; + return UserRoleEnum.GUEST; } public static String[] getAllRoles() { - return Arrays.stream(UserRole.values()).map(UserRole::name).toArray(String[]::new); + return Arrays.stream(UserRoleEnum.values()).map(UserRoleEnum::name).toArray(String[]::new); } } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java index f853bf04..2115b995 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserService.java @@ -1,16 +1,15 @@ package com.RDS.skilltree.User; import java.util.List; -import java.util.UUID; public interface UserService { UserDTO createUser(UserDRO user); - void updateUser(UUID id, UserDRO user); + void updateUser(String id, UserDRO user); - UserDTO getUserById(UUID id); + UserDTO getUserById(String id); List getAllUsers(); - void addSkill(UUID skill, UUID userId); + void addSkill(Integer skill, String userId); } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java index c85f9d94..1171911a 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserServiceImpl.java @@ -1,12 +1,11 @@ package com.RDS.skilltree.User; -import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.Skill.SkillModel; -import com.RDS.skilltree.Skill.SkillRepository; +import com.RDS.skilltree.exceptions.NoEntityException; +import com.RDS.skilltree.models.Skill; +import com.RDS.skilltree.repositories.SkillRepository; import jakarta.transaction.Transactional; import java.util.List; import java.util.Optional; -import java.util.UUID; import org.springframework.stereotype.Service; @Service @@ -27,10 +26,10 @@ public UserDTO createUser(UserDRO user) { } @Override - public void updateUser(UUID id, UserDRO user) {} + public void updateUser(String id, UserDRO user) {} @Override - public UserDTO getUserById(UUID id) { + public UserDTO getUserById(String id) { Optional userModel = userRepository.findById(id); return userModel.map(UserDTO::getUsersWithSkills).orElse(null); } @@ -42,24 +41,25 @@ public List getAllUsers() { /** * updates the user and skill both + * * @param skillId * @param userId */ @Override @Transactional - public void addSkill(UUID skillId, UUID userId) { + public void addSkill(Integer skillId, String userId) { Optional userOptional = userRepository.findById(userId); - Optional skillOptional = skillRepository.findById(skillId); + Optional skillOptional = skillRepository.findById(skillId); if (userOptional.isPresent() && skillOptional.isPresent()) { UserModel userModel = userOptional.get(); - SkillModel skillModel = skillOptional.get(); + Skill skill = skillOptional.get(); - userModel.getSkills().add(skillModel); - skillModel.getUsers().add(userModel); + // userModel.getSkills().add(skillModel); + // skillModel.getUsers().add(userModel); userRepository.save(userModel); - skillRepository.save(skillModel); + skillRepository.save(skill); } else { if (skillOptional.isEmpty()) { throw new NoEntityException("Skill Id is not passed in the input"); diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillStatusEnum.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillStatusEnum.java new file mode 100644 index 00000000..79637df6 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillStatusEnum.java @@ -0,0 +1,7 @@ +package com.RDS.skilltree.User; + +public enum UserSkillStatusEnum { + APPROVED, + REJECTED, + PENDING +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillsModel.java b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillsModel.java new file mode 100644 index 00000000..4754cb64 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/User/UserSkillsModel.java @@ -0,0 +1,35 @@ +package com.RDS.skilltree.User; + +import com.RDS.skilltree.models.Skill; +import com.fasterxml.jackson.annotation.JsonBackReference; +import jakarta.persistence.*; +import java.util.UUID; +import lombok.*; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "user_skills") +public class UserSkillsModel { + @Id + @GeneratedValue + @Column(name = "id", columnDefinition = "BINARY(16)") + private UUID id; + + @JsonBackReference + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private UserModel user; + + @JsonBackReference + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "skill_id", nullable = false) + private Skill skill; + + @Enumerated(EnumType.STRING) + @Column(name = "status", nullable = false) + private UserSkillStatusEnum status = UserSkillStatusEnum.PENDING; +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/apis/EndorsementsApi.java b/skill-tree/src/main/java/com/RDS/skilltree/apis/EndorsementsApi.java new file mode 100644 index 00000000..d775d5c7 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/apis/EndorsementsApi.java @@ -0,0 +1,32 @@ +package com.RDS.skilltree.apis; + +import com.RDS.skilltree.services.EndorsementService; +import com.RDS.skilltree.viewmodels.CreateEndorsementViewModel; +import com.RDS.skilltree.viewmodels.EndorsementViewModel; +import com.RDS.skilltree.viewmodels.UpdateEndorsementViewModel; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("v1/endorsements") +public class EndorsementsApi { + private final EndorsementService endorsementService; + + @PostMapping + public ResponseEntity create( + @Valid @RequestBody CreateEndorsementViewModel endorsement) { + return new ResponseEntity<>(endorsementService.create(endorsement), HttpStatus.CREATED); + } + + @PatchMapping("/{id}") + public ResponseEntity update( + @PathVariable Integer id, @Valid @RequestBody UpdateEndorsementViewModel body) { + return new ResponseEntity<>(endorsementService.update(id, body), HttpStatus.OK); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/apis/HealthApi.java b/skill-tree/src/main/java/com/RDS/skilltree/apis/HealthApi.java new file mode 100644 index 00000000..88dd1d20 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/apis/HealthApi.java @@ -0,0 +1,25 @@ +package com.RDS.skilltree.apis; + +import com.RDS.skilltree.services.MetricService; +import java.util.Map; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("v1/health") +public class HealthApi { + private final MetricService metricService; + + @GetMapping + public ResponseEntity> getUptime() { + return new ResponseEntity<>( + Map.of("uptime in seconds", metricService.getUptime()), HttpStatus.OK); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/apis/SkillsApi.java b/skill-tree/src/main/java/com/RDS/skilltree/apis/SkillsApi.java new file mode 100644 index 00000000..ebf07ed6 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/apis/SkillsApi.java @@ -0,0 +1,44 @@ +package com.RDS.skilltree.apis; + +import com.RDS.skilltree.services.EndorsementService; +import com.RDS.skilltree.services.SkillService; +import com.RDS.skilltree.viewmodels.CreateSkillViewModel; +import com.RDS.skilltree.viewmodels.EndorsementViewModel; +import com.RDS.skilltree.viewmodels.SkillViewModel; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Min; +import java.util.List; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@Slf4j +@RestController +@RequiredArgsConstructor +@RequestMapping("v1/skills") +public class SkillsApi { + private final SkillService skillService; + private final EndorsementService endorsementService; + + @GetMapping + public ResponseEntity> getAll() { + return ResponseEntity.ok(skillService.getAll()); + } + + @PostMapping + public ResponseEntity create(@Valid @RequestBody CreateSkillViewModel skill) { + return ResponseEntity.ok(skillService.create(skill)); + } + + @GetMapping("/{id}/endorsements") + public ResponseEntity> getEndorsementsBySkillId( + @RequestParam(name = "offset", defaultValue = "0", required = false) @Min(0) int offset, + @RequestParam(name = "limit", defaultValue = "10", required = false) @Min(1) int limit, + @PathVariable(value = "id") Integer skillID) { + PageRequest pageRequest = PageRequest.of(offset, limit); + return ResponseEntity.ok(endorsementService.getAllEndorsementsBySkillId(skillID, pageRequest)); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Config/SecurityConfig.java b/skill-tree/src/main/java/com/RDS/skilltree/config/SecurityConfig.java similarity index 91% rename from skill-tree/src/main/java/com/RDS/skilltree/Config/SecurityConfig.java rename to skill-tree/src/main/java/com/RDS/skilltree/config/SecurityConfig.java index ac4fa3dc..b01c3b49 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Config/SecurityConfig.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/config/SecurityConfig.java @@ -1,9 +1,9 @@ -package com.RDS.skilltree.Config; +package com.RDS.skilltree.config; import com.RDS.skilltree.Authentication.AuthEntryPoint; import com.RDS.skilltree.Authentication.CustomAccessDeniedHandler; -import com.RDS.skilltree.Filters.JWTAuthenticationFilter; -import com.RDS.skilltree.User.UserRole; +import com.RDS.skilltree.User.UserRoleEnum; +import com.RDS.skilltree.utils.JWTAuthenticationFilter; import java.util.Arrays; import java.util.List; import org.springframework.context.annotation.Bean; @@ -50,10 +50,12 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { && request.getQueryString().contains("dummyData=true")) .permitAll() .requestMatchers(HttpMethod.GET, "/v1/**") - .hasAnyAuthority(UserRole.getAllRoles()) // give read-only access to all + .hasAnyAuthority(UserRoleEnum.getAllRoles()) // give read-only access to all .requestMatchers("/v1/**") .hasAnyAuthority( - UserRole.USER.name(), UserRole.MEMBER.name(), UserRole.SUPERUSER.name()) + UserRoleEnum.USER.name(), + UserRoleEnum.MEMBER.name(), + UserRoleEnum.SUPERUSER.name()) .anyRequest() .authenticated()) .exceptionHandling( diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Config/WebMvcConfig.java b/skill-tree/src/main/java/com/RDS/skilltree/config/WebMvcConfig.java similarity index 96% rename from skill-tree/src/main/java/com/RDS/skilltree/Config/WebMvcConfig.java rename to skill-tree/src/main/java/com/RDS/skilltree/config/WebMvcConfig.java index f02f79ea..6b5a96e0 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Config/WebMvcConfig.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/config/WebMvcConfig.java @@ -1,4 +1,4 @@ -package com.RDS.skilltree.Config; +package com.RDS.skilltree.config; import com.RDS.skilltree.utils.UUIDValidationInterceptor; import org.springframework.beans.factory.annotation.Autowired; diff --git a/skill-tree/src/main/java/com/RDS/skilltree/enums/SkillTypeEnum.java b/skill-tree/src/main/java/com/RDS/skilltree/enums/SkillTypeEnum.java new file mode 100644 index 00000000..255de25c --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/enums/SkillTypeEnum.java @@ -0,0 +1,5 @@ +package com.RDS.skilltree.enums; + +public enum SkillTypeEnum { + ATOMIC, +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/exceptions/EndorsementNotFoundException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/EndorsementNotFoundException.java new file mode 100644 index 00000000..15790383 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/EndorsementNotFoundException.java @@ -0,0 +1,7 @@ +package com.RDS.skilltree.exceptions; + +public class EndorsementNotFoundException extends RuntimeException { + public EndorsementNotFoundException(String message) { + super(message); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Exceptions/EntityAlreadyExistsException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/EntityAlreadyExistsException.java similarity index 80% rename from skill-tree/src/main/java/com/RDS/skilltree/Exceptions/EntityAlreadyExistsException.java rename to skill-tree/src/main/java/com/RDS/skilltree/exceptions/EntityAlreadyExistsException.java index a013a043..3fc9a5d7 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Exceptions/EntityAlreadyExistsException.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/EntityAlreadyExistsException.java @@ -1,4 +1,4 @@ -package com.RDS.skilltree.Exceptions; +package com.RDS.skilltree.exceptions; public class EntityAlreadyExistsException extends RuntimeException { public EntityAlreadyExistsException(String message) { diff --git a/skill-tree/src/main/java/com/RDS/skilltree/utils/GlobalExceptionHandler.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/GlobalExceptionHandler.java similarity index 70% rename from skill-tree/src/main/java/com/RDS/skilltree/utils/GlobalExceptionHandler.java rename to skill-tree/src/main/java/com/RDS/skilltree/exceptions/GlobalExceptionHandler.java index 35cfff7e..50df4784 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/utils/GlobalExceptionHandler.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/GlobalExceptionHandler.java @@ -1,9 +1,6 @@ -package com.RDS.skilltree.utils; +package com.RDS.skilltree.exceptions; -import com.RDS.skilltree.Common.Response.GenericResponse; -import com.RDS.skilltree.Exceptions.EntityAlreadyExistsException; -import com.RDS.skilltree.Exceptions.InvalidParameterException; -import com.RDS.skilltree.Exceptions.NoEntityException; +import com.RDS.skilltree.utils.GenericResponse; import jakarta.validation.ConstraintViolationException; import java.util.List; import lombok.extern.slf4j.Slf4j; @@ -16,9 +13,10 @@ import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; -@ControllerAdvice @Slf4j +@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler({NoEntityException.class}) public ResponseEntity> handleNoEntityException(NoEntityException ex) { @@ -95,4 +93,40 @@ public ResponseEntity> handleException(ConstraintViolati return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new GenericResponse<>(null, ex.getMessage())); } + + @ExceptionHandler(UserNotFoundException.class) + public ResponseEntity handleUserNotFoundException( + UserNotFoundException ex, WebRequest request) { + log.error("Exception - Error : {}", ex.getMessage(), ex); + return new ResponseEntity<>(new GenericResponse<>(null, ex.getMessage()), HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(SkillAlreadyExistsException.class) + public ResponseEntity handleSkillAlreadyExistsException( + SkillAlreadyExistsException ex, WebRequest request) { + log.error("Exception - Error : {}", ex.getMessage(), ex); + return new ResponseEntity<>(new GenericResponse<>(null, ex.getMessage()), HttpStatus.CONFLICT); + } + + @ExceptionHandler(SelfEndorsementNotAllowedException.class) + public ResponseEntity handleSelfEndorsementNotAllowedException( + SelfEndorsementNotAllowedException ex, WebRequest request) { + log.error("Exception - Error : {}", ex.getMessage(), ex); + return new ResponseEntity<>( + new GenericResponse<>(null, ex.getMessage()), HttpStatus.METHOD_NOT_ALLOWED); + } + + @ExceptionHandler(SkillNotFoundException.class) + public ResponseEntity handleSkillNotFoundException( + SkillNotFoundException ex, WebRequest request) { + log.error("Exception - Error : {}", ex.getMessage(), ex); + return new ResponseEntity<>(new GenericResponse<>(null, ex.getMessage()), HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(EndorsementNotFoundException.class) + public ResponseEntity handleEndorsementNotException( + EndorsementNotFoundException ex, WebRequest request) { + log.error("Exception - Error : {}", ex.getMessage(), ex); + return new ResponseEntity<>(new GenericResponse<>(null, ex.getMessage()), HttpStatus.NOT_FOUND); + } } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Exceptions/InvalidParameterException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/InvalidParameterException.java similarity index 85% rename from skill-tree/src/main/java/com/RDS/skilltree/Exceptions/InvalidParameterException.java rename to skill-tree/src/main/java/com/RDS/skilltree/exceptions/InvalidParameterException.java index fda72a6d..0e5bd832 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Exceptions/InvalidParameterException.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/InvalidParameterException.java @@ -1,4 +1,4 @@ -package com.RDS.skilltree.Exceptions; +package com.RDS.skilltree.exceptions; public class InvalidParameterException extends IllegalArgumentException { public InvalidParameterException(String parameterName, String message) { diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Exceptions/NoEntityException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/NoEntityException.java similarity index 89% rename from skill-tree/src/main/java/com/RDS/skilltree/Exceptions/NoEntityException.java rename to skill-tree/src/main/java/com/RDS/skilltree/exceptions/NoEntityException.java index 0b8685bc..16143d89 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Exceptions/NoEntityException.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/NoEntityException.java @@ -1,4 +1,4 @@ -package com.RDS.skilltree.Exceptions; +package com.RDS.skilltree.exceptions; public class NoEntityException extends RuntimeException { diff --git a/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SelfEndorsementNotAllowedException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SelfEndorsementNotAllowedException.java new file mode 100644 index 00000000..67d81250 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SelfEndorsementNotAllowedException.java @@ -0,0 +1,7 @@ +package com.RDS.skilltree.exceptions; + +public class SelfEndorsementNotAllowedException extends RuntimeException { + public SelfEndorsementNotAllowedException(String message) { + super(message); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillAlreadyExistsException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillAlreadyExistsException.java new file mode 100644 index 00000000..16322344 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillAlreadyExistsException.java @@ -0,0 +1,7 @@ +package com.RDS.skilltree.exceptions; + +public class SkillAlreadyExistsException extends RuntimeException { + public SkillAlreadyExistsException(String message) { + super(message); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillNotFoundException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillNotFoundException.java new file mode 100644 index 00000000..0a124fd0 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/SkillNotFoundException.java @@ -0,0 +1,7 @@ +package com.RDS.skilltree.exceptions; + +public class SkillNotFoundException extends RuntimeException { + public SkillNotFoundException(String message) { + super(message); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/exceptions/UserNotFoundException.java b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/UserNotFoundException.java new file mode 100644 index 00000000..6c7fc7fc --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/exceptions/UserNotFoundException.java @@ -0,0 +1,7 @@ +package com.RDS.skilltree.exceptions; + +public class UserNotFoundException extends RuntimeException { + public UserNotFoundException(String message) { + super(message); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/models/Endorsement.java b/skill-tree/src/main/java/com/RDS/skilltree/models/Endorsement.java new file mode 100644 index 00000000..9c619b36 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/models/Endorsement.java @@ -0,0 +1,35 @@ +package com.RDS.skilltree.models; + +import com.RDS.skilltree.User.UserModel; +import com.RDS.skilltree.utils.TrackedProperties; +import jakarta.persistence.*; +import lombok.*; + +@AllArgsConstructor +@NoArgsConstructor +@Entity +@Builder +@Getter +@Setter +@Table(name = "endorsements") +public class Endorsement extends TrackedProperties { + @Id + @GeneratedValue + @Column(name = "id") + private Integer id; + + @ManyToOne + @JoinColumn(name = "skill_id", referencedColumnName = "id") + private Skill skill; + + @ManyToOne + @JoinColumn(name = "endorse_id", referencedColumnName = "id") + private UserModel endorse; + + @ManyToOne(targetEntity = UserModel.class, cascade = CascadeType.ALL, optional = false) + @JoinColumn(name = "endorser_id", referencedColumnName = "id") + private UserModel endorser; + + @Column(name = "message", nullable = false) + private String message; +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/models/Skill.java b/skill-tree/src/main/java/com/RDS/skilltree/models/Skill.java new file mode 100644 index 00000000..48b93981 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/models/Skill.java @@ -0,0 +1,36 @@ +package com.RDS.skilltree.models; + +import com.RDS.skilltree.User.UserModel; +import com.RDS.skilltree.enums.SkillTypeEnum; +import com.RDS.skilltree.utils.TrackedProperties; +import jakarta.persistence.*; +import lombok.*; + +@AllArgsConstructor +@NoArgsConstructor +@Entity +@Builder +@Getter +@Setter +@Table(name = "skills") +public class Skill extends TrackedProperties { + @Id + @GeneratedValue + @Column(name = "id") + private Integer id; + + @Column(name = "name", unique = true, nullable = false) + private String name; + + @Column(name = "skill_type", nullable = false) + @Enumerated(value = EnumType.STRING) + private SkillTypeEnum type = SkillTypeEnum.ATOMIC; + + @ManyToOne + @JoinColumn(name = "created_by", nullable = false) + private UserModel createdBy; + + @ManyToOne + @JoinColumn(name = "updated_by") + private UserModel updatedBy; +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/repositories/EndorsementRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/repositories/EndorsementRepository.java new file mode 100644 index 00000000..c5e8d670 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/repositories/EndorsementRepository.java @@ -0,0 +1,10 @@ +package com.RDS.skilltree.repositories; + +import com.RDS.skilltree.models.Endorsement; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface EndorsementRepository extends JpaRepository { + Page findBySkillId(Integer skillId, Pageable pageable); +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/repositories/SkillRepository.java b/skill-tree/src/main/java/com/RDS/skilltree/repositories/SkillRepository.java new file mode 100644 index 00000000..8f005d92 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/repositories/SkillRepository.java @@ -0,0 +1,10 @@ +package com.RDS.skilltree.repositories; + +import com.RDS.skilltree.models.Skill; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SkillRepository extends JpaRepository { + boolean existsByName(String name); +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementService.java b/skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementService.java new file mode 100644 index 00000000..b11d73f6 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementService.java @@ -0,0 +1,15 @@ +package com.RDS.skilltree.services; + +import com.RDS.skilltree.viewmodels.CreateEndorsementViewModel; +import com.RDS.skilltree.viewmodels.EndorsementViewModel; +import com.RDS.skilltree.viewmodels.UpdateEndorsementViewModel; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +public interface EndorsementService { + Page getAllEndorsementsBySkillId(Integer skillId, Pageable pageable); + + EndorsementViewModel create(CreateEndorsementViewModel endorsement); + + EndorsementViewModel update(Integer endorsementId, UpdateEndorsementViewModel endorsement); +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementServiceImplementation.java b/skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementServiceImplementation.java new file mode 100644 index 00000000..e16fe967 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/services/EndorsementServiceImplementation.java @@ -0,0 +1,95 @@ +package com.RDS.skilltree.services; + +import com.RDS.skilltree.User.UserModel; +import com.RDS.skilltree.User.UserRepository; +import com.RDS.skilltree.exceptions.EndorsementNotFoundException; +import com.RDS.skilltree.exceptions.SelfEndorsementNotAllowedException; +import com.RDS.skilltree.exceptions.SkillNotFoundException; +import com.RDS.skilltree.exceptions.UserNotFoundException; +import com.RDS.skilltree.models.Endorsement; +import com.RDS.skilltree.models.Skill; +import com.RDS.skilltree.repositories.EndorsementRepository; +import com.RDS.skilltree.repositories.SkillRepository; +import com.RDS.skilltree.viewmodels.CreateEndorsementViewModel; +import com.RDS.skilltree.viewmodels.EndorsementViewModel; +import com.RDS.skilltree.viewmodels.UpdateEndorsementViewModel; +import java.util.Objects; +import java.util.Optional; +import lombok.RequiredArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class EndorsementServiceImplementation implements EndorsementService { + private final UserRepository userRepository; + private final SkillRepository skillRepository; + private final EndorsementRepository endorsementRepository; + + @Override + public Page getAllEndorsementsBySkillId( + Integer skillId, Pageable pageable) { + Page endorsementPage = endorsementRepository.findBySkillId(skillId, pageable); + return endorsementPage.map(EndorsementViewModel::toViewModel); + } + + @Override + // TODO : add a check for when a endorsement is already created by a user for a particular skill. + public EndorsementViewModel create(CreateEndorsementViewModel endorsementViewModel) { + String message = endorsementViewModel.getMessage(); + Integer skillId = endorsementViewModel.getSkillId(); + String endorseId = endorsementViewModel.getEndorseId(); + + // TODO: Get this from security context once the login api is implemented. + String endorserId = "ae7a6673c5574140838f209de4c644fc"; + + if (Objects.equals(endorseId, endorserId)) { + throw new SelfEndorsementNotAllowedException("Self endorsement not allowed"); + } + + Optional skillDetails = skillRepository.findById(skillId); + Optional endorseDetails = userRepository.findById(endorseId); + Optional endorserDetails = userRepository.findById(endorserId); + + if (endorserDetails.isEmpty()) { + throw new UserNotFoundException("Cannot create endorsement for the current user"); + } + + if (endorseDetails.isEmpty()) { + throw new UserNotFoundException("Endorse not found"); + } + + if (skillDetails.isEmpty()) { + throw new SkillNotFoundException(String.format("Skill id: %s not found", skillId)); + } + + Endorsement endorsement = new Endorsement(); + + endorsement.setMessage(message); + endorsement.setSkill(skillDetails.get()); + endorsement.setEndorse(endorseDetails.get()); + endorsement.setEndorser(endorserDetails.get()); + + return EndorsementViewModel.toViewModel(endorsementRepository.save(endorsement)); + } + + @Override + public EndorsementViewModel update(Integer endorsementId, UpdateEndorsementViewModel body) { + Optional exitingEndorsement = endorsementRepository.findById(endorsementId); + + if (exitingEndorsement.isEmpty()) { + throw new EndorsementNotFoundException( + String.format("Endorsement with id: %s not found", endorsementId)); + } + + Endorsement endorsement = exitingEndorsement.get(); + String updatedMessage = body.getMessage(); + + if (updatedMessage != null) { + endorsement.setMessage(updatedMessage); + } + + return EndorsementViewModel.toViewModel(endorsementRepository.save(endorsement)); + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/services/MetricService.java b/skill-tree/src/main/java/com/RDS/skilltree/services/MetricService.java new file mode 100644 index 00000000..2670a51a --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/services/MetricService.java @@ -0,0 +1,5 @@ +package com.RDS.skilltree.services; + +public interface MetricService { + Double getUptime(); +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/metrics/MetricService.java b/skill-tree/src/main/java/com/RDS/skilltree/services/MetricServiceImplementation.java similarity index 57% rename from skill-tree/src/main/java/com/RDS/skilltree/metrics/MetricService.java rename to skill-tree/src/main/java/com/RDS/skilltree/services/MetricServiceImplementation.java index 60c86997..67df4a78 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/metrics/MetricService.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/services/MetricServiceImplementation.java @@ -1,20 +1,16 @@ -package com.RDS.skilltree.metrics; +package com.RDS.skilltree.services; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.boot.actuate.metrics.MetricsEndpoint; import org.springframework.stereotype.Service; @Service -public class MetricService { - +@RequiredArgsConstructor +public class MetricServiceImplementation implements MetricService { private final MetricsEndpoint metricsEndpoint; - @Autowired - public MetricService(MetricsEndpoint metricsEndpoint) { - this.metricsEndpoint = metricsEndpoint; - } - - public double getUptime() { + @Override + public Double getUptime() { return metricsEndpoint.metric("process.uptime", null).getMeasurements().stream() .findFirst() .map(MetricsEndpoint.Sample::getValue) diff --git a/skill-tree/src/main/java/com/RDS/skilltree/services/SkillService.java b/skill-tree/src/main/java/com/RDS/skilltree/services/SkillService.java new file mode 100644 index 00000000..10368a0a --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/services/SkillService.java @@ -0,0 +1,11 @@ +package com.RDS.skilltree.services; + +import com.RDS.skilltree.viewmodels.CreateSkillViewModel; +import com.RDS.skilltree.viewmodels.SkillViewModel; +import java.util.List; + +public interface SkillService { + List getAll(); + + SkillViewModel create(CreateSkillViewModel skill); +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/services/SkillServiceImplementation.java b/skill-tree/src/main/java/com/RDS/skilltree/services/SkillServiceImplementation.java new file mode 100644 index 00000000..8797205c --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/services/SkillServiceImplementation.java @@ -0,0 +1,62 @@ +package com.RDS.skilltree.services; + +import com.RDS.skilltree.User.JwtUserModel; +import com.RDS.skilltree.User.UserModel; +import com.RDS.skilltree.User.UserRepository; +import com.RDS.skilltree.exceptions.SkillAlreadyExistsException; +import com.RDS.skilltree.exceptions.UserNotFoundException; +import com.RDS.skilltree.models.Skill; +import com.RDS.skilltree.repositories.SkillRepository; +import com.RDS.skilltree.viewmodels.CreateSkillViewModel; +import com.RDS.skilltree.viewmodels.SkillViewModel; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.BeanUtils; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class SkillServiceImplementation implements SkillService { + private final SkillRepository skillRepository; + private final UserRepository userRepository; + + @Override + public List getAll() { + return skillRepository.findAll().stream() + .map(SkillViewModel::toViewModel) + .collect(Collectors.toList()); + } + + @Override + public SkillViewModel create(CreateSkillViewModel skill) { + if (skillRepository.existsByName(skill.getName())) { + throw new SkillAlreadyExistsException( + String.format("Skill with name %s already exists", skill.getName())); + } + + JwtUserModel jwtDetails = + (JwtUserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + + // TODO : user the userId from jwtDetails after the login api is implemented + String userId = "ae7a6673c5574140838f209de4c644fc"; + Optional user = userRepository.findById(userId); + + if (user.isEmpty()) { + throw new UserNotFoundException("unable to create skill for the current user"); + } + + Skill newSkill = toEntity(skill); + newSkill.setCreatedBy(user.get()); + + return SkillViewModel.toViewModel(skillRepository.saveAndFlush(newSkill)); + } + + private Skill toEntity(CreateSkillViewModel viewModel) { + Skill entity = new Skill(); + BeanUtils.copyProperties(viewModel, entity); + return entity; + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Common/Response/GenericResponse.java b/skill-tree/src/main/java/com/RDS/skilltree/utils/GenericResponse.java similarity index 89% rename from skill-tree/src/main/java/com/RDS/skilltree/Common/Response/GenericResponse.java rename to skill-tree/src/main/java/com/RDS/skilltree/utils/GenericResponse.java index ee31959f..70d73df3 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Common/Response/GenericResponse.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/utils/GenericResponse.java @@ -1,4 +1,4 @@ -package com.RDS.skilltree.Common.Response; +package com.RDS.skilltree.utils; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; diff --git a/skill-tree/src/main/java/com/RDS/skilltree/Filters/JWTAuthenticationFilter.java b/skill-tree/src/main/java/com/RDS/skilltree/utils/JWTAuthenticationFilter.java similarity index 96% rename from skill-tree/src/main/java/com/RDS/skilltree/Filters/JWTAuthenticationFilter.java rename to skill-tree/src/main/java/com/RDS/skilltree/utils/JWTAuthenticationFilter.java index 5392978e..4d40a8a9 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/Filters/JWTAuthenticationFilter.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/utils/JWTAuthenticationFilter.java @@ -1,7 +1,6 @@ -package com.RDS.skilltree.Filters; +package com.RDS.skilltree.utils; import com.RDS.skilltree.Authentication.UserAuthenticationToken; -import com.RDS.skilltree.utils.JWTUtils; import io.jsonwebtoken.Claims; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; diff --git a/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java b/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java index 23601457..d11dd1e1 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/utils/TrackedProperties.java @@ -3,22 +3,25 @@ import jakarta.persistence.Column; import jakarta.persistence.MappedSuperclass; import java.time.Instant; -import java.util.UUID; import lombok.Data; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.SourceType; +import org.hibernate.annotations.UpdateTimestamp; @Data @MappedSuperclass public abstract class TrackedProperties { - - @Column(name = "created_by") - private UUID createdBy; - - @Column(name = "updated_by") - private UUID updatedBy; - - @Column(name = "created_at") + @CreationTimestamp(source = SourceType.DB) + @Column(name = "created_at", nullable = false, updatable = false) private Instant createdAt; + @UpdateTimestamp(source = SourceType.DB) @Column(name = "updated_at") private Instant updatedAt; + + @Column(name = "is_deleted", nullable = false, columnDefinition = "boolean default false") + private boolean isDeleted; + + @Column(name = "deleted_at") + private Instant deletedAt; } diff --git a/skill-tree/src/main/java/com/RDS/skilltree/utils/UUIDValidationInterceptor.java b/skill-tree/src/main/java/com/RDS/skilltree/utils/UUIDValidationInterceptor.java index cccc1d5b..06393977 100644 --- a/skill-tree/src/main/java/com/RDS/skilltree/utils/UUIDValidationInterceptor.java +++ b/skill-tree/src/main/java/com/RDS/skilltree/utils/UUIDValidationInterceptor.java @@ -1,6 +1,6 @@ package com.RDS.skilltree.utils; -import com.RDS.skilltree.Exceptions.InvalidParameterException; +import com.RDS.skilltree.exceptions.InvalidParameterException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; diff --git a/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateEndorsementViewModel.java b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateEndorsementViewModel.java new file mode 100644 index 00000000..32b3670b --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateEndorsementViewModel.java @@ -0,0 +1,18 @@ +package com.RDS.skilltree.viewmodels; + +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class CreateEndorsementViewModel { + @NotNull(message = "Message cannot be empty") + private String message; + + @NotNull(message = "user id cannot be null") + private String endorseId; + + @NotNull(message = "skill id cannot be null") + private Integer skillId; +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateSkillViewModel.java b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateSkillViewModel.java new file mode 100644 index 00000000..8cbba309 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/CreateSkillViewModel.java @@ -0,0 +1,19 @@ +package com.RDS.skilltree.viewmodels; + +import com.RDS.skilltree.User.UserModel; +import com.RDS.skilltree.enums.SkillTypeEnum; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class CreateSkillViewModel { + @NotNull(message = "Name cannot be empty") + private String name; + + @NotNull(message = "SkillType cannot be empty") + private SkillTypeEnum type; + + private UserModel createdBy; +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/EndorsementViewModel.java b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/EndorsementViewModel.java new file mode 100644 index 00000000..a4faad31 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/EndorsementViewModel.java @@ -0,0 +1,27 @@ +package com.RDS.skilltree.viewmodels; + +import com.RDS.skilltree.models.Endorsement; +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.BeanUtils; + +@Getter +@Setter +public class EndorsementViewModel { + private Integer id; + private SkillViewModel skill; + private UserViewModel endorse; + private UserViewModel endorser; + private String message; + + public static EndorsementViewModel toViewModel(Endorsement endorsement) { + EndorsementViewModel viewModel = new EndorsementViewModel(); + BeanUtils.copyProperties(endorsement, viewModel); + + viewModel.setSkill(SkillViewModel.toViewModel(endorsement.getSkill())); + viewModel.setEndorser(UserViewModel.toViewModel(endorsement.getEndorser())); + viewModel.setEndorse(UserViewModel.toViewModel(endorsement.getEndorse())); + + return viewModel; + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/SkillViewModel.java b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/SkillViewModel.java new file mode 100644 index 00000000..6b9321e6 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/SkillViewModel.java @@ -0,0 +1,25 @@ +package com.RDS.skilltree.viewmodels; + +import com.RDS.skilltree.enums.SkillTypeEnum; +import com.RDS.skilltree.models.Skill; +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.BeanUtils; + +@Getter +@Setter +public class SkillViewModel { + private Integer id; + private String name; + private SkillTypeEnum type = SkillTypeEnum.ATOMIC; + + public static SkillViewModel toViewModel(Skill skill) { + if (skill == null) { + return null; + } + + SkillViewModel viewModel = new SkillViewModel(); + BeanUtils.copyProperties(skill, viewModel); + return viewModel; + } +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UpdateEndorsementViewModel.java b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UpdateEndorsementViewModel.java new file mode 100644 index 00000000..0b1685a7 --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UpdateEndorsementViewModel.java @@ -0,0 +1,12 @@ +package com.RDS.skilltree.viewmodels; + +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class UpdateEndorsementViewModel { + @NotNull(message = "Message cannot be empty") + private String message; +} diff --git a/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UserViewModel.java b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UserViewModel.java new file mode 100644 index 00000000..e9a98d3a --- /dev/null +++ b/skill-tree/src/main/java/com/RDS/skilltree/viewmodels/UserViewModel.java @@ -0,0 +1,22 @@ +package com.RDS.skilltree.viewmodels; + +import com.RDS.skilltree.User.UserModel; +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.BeanUtils; + +@Getter +@Setter +public class UserViewModel { + private String name; + + public static UserViewModel toViewModel(UserModel user) { + if (user == null) { + return null; + } + + UserViewModel viewModel = new UserViewModel(); + BeanUtils.copyProperties(user, viewModel); + return viewModel; + } +} diff --git a/skill-tree/src/main/resources/application-dev.properties b/skill-tree/src/main/resources/application-dev.properties index 8fa24448..21199428 100644 --- a/skill-tree/src/main/resources/application-dev.properties +++ b/skill-tree/src/main/resources/application-dev.properties @@ -1 +1,2 @@ -cookieName=rds-session-v2-development \ No newline at end of file +cookieName=rds-session-v2-development +logging.level.root=DEBUG \ No newline at end of file diff --git a/skill-tree/src/main/resources/application.properties b/skill-tree/src/main/resources/application.properties index 098a53b3..6929702e 100644 --- a/skill-tree/src/main/resources/application.properties +++ b/skill-tree/src/main/resources/application.properties @@ -11,5 +11,3 @@ management.endpoints.web.exposure.include=health,info,metrics logging.level.root=ERROR # If no value received from env default is dev spring.profiles.active=${SPRING_PROFILES_ACTIVE:dev} -# TODO:Dummy JSON code, needs to be changed as part of #103 -endorsements.dummmy-data.path=dummy-data/endorsements.json diff --git a/skill-tree/src/main/resources/dummy-data/endorsements.json b/skill-tree/src/main/resources/dummy-data/endorsements.json deleted file mode 100644 index cdad6516..00000000 --- a/skill-tree/src/main/resources/dummy-data/endorsements.json +++ /dev/null @@ -1,142 +0,0 @@ -[ - { - "id": "7f6cb5e8-2e22-4a33-a120-6a0f684fb1fc", - "user_id": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "skill_id": "7a6b8876-44e3-4b18-8579-79e9d4a5f0c9", - "status": "PENDING", - "created_at": "2024-02-18 17:34:47.504189", - "created_by": "7a6b8876-44e3-4b18-8579-79e9d4a5f0c9", - "updated_at": "2024-02-18 17:34:47.504189", - "updated_by": "7a6b8876-44e3-4b18-8579-79e9d4a5f0c9" - }, - { - "id": "c13a5db1-8df0-4b63-99fd-4e75f97d383c", - "user_id": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "skill_id": "4dcf2994-e5b4-45f3-8974-d2db0272a6cc", - "status": "APPROVED", - "created_at": "2024-02-18 17:34:47.504189", - "created_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "updated_at": "2024-02-18 17:34:47.504189", - "updated_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb" - }, - { - "id": "d2a40739-53a3-4a47-8c14-5b64ee5eaa3d", - "user_id": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "skill_id": "1e7af93e-3de5-4a24-a4b7-9fc4ff48e37e", - "status": "PENDING", - "created_at": "2024-02-19 12:45:32.092461", - "created_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "updated_at": "2024-02-19 12:45:32.092461", - "updated_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261" - }, - { - "id": "bd177123-0c50-458d-8d56-0d6f1a78f69c", - "user_id": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "skill_id": "f9d0cf6d-44b5-4c3e-867d-ee4a5ffad017", - "status": "APPROVED", - "created_at": "2024-02-20 09:21:18.735582", - "created_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "updated_at": "2024-02-20 09:21:18.735582", - "updated_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb" - }, - { - "id": "56d27502-39c3-4744-822f-c1e0504d149d", - "user_id": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "skill_id": "b29d4941-ef22-4c39-86f9-b048554c1419", - "status": "PENDING", - "created_at": "2024-02-25 19:17:08.201468", - "created_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "updated_at": "2024-02-25 19:17:08.201468", - "updated_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261" - }, - { - "id": "3a5c6a30-8c68-4d38-8b70-720a0e7a4a6b", - "user_id": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "skill_id": "7d6db19e-442e-4247-b5cf-87cf6db26bb2", - "status": "APPROVED", - "created_at": "2024-02-26 22:09:57.994362", - "created_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "updated_at": "2024-02-26 22:09:57.994362", - "updated_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb" - }, - { - "id": "1a0c1baf-86c6-4f13-8fd5-c736a94c2c54", - "user_id": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "skill_id": "d30e4b2d-9c53-48d7-8920-8a225526d688", - "status": "PENDING", - "created_at": "2024-02-27 19:42:31.628175", - "created_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "updated_at": "2024-02-27 19:42:31.628175", - "updated_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261" - }, - { - "id": "f4f4827d-5f22-4e01-9b97-d10889124578", - "user_id": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "skill_id": "0b37ef80-21d5-4960-995b-089221efc84f", - "status": "PENDING", - "created_at": "2024-02-28 14:51:22.941799", - "created_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "updated_at": "2024-02-28 14:51:22.941799", - "updated_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb" - }, - { - "id": "b0bda1de-3cf4-4f90-961f-d928334abf5b", - "user_id": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "skill_id": "e11cd9d8-0649-4d33-b4e3-60f9f68b6c39", - "status": "APPROVED", - "created_at": "2024-02-29 08:11:45.202497", - "created_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "updated_at": "2024-02-29 08:11:45.202497", - "updated_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261" - }, - { - "id": "c7e026b9-f184-4fb1-881f-625ccf937fd0", - "user_id": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "skill_id": "a94a7322-4f52-456d-850a-b2c03485be61", - "status": "PENDING", - "created_at": "2024-03-01 16:22:33.795328", - "created_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "updated_at": "2024-03-01 16:22:33.795328", - "updated_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb" - }, - { - "id": "99f2035f-4a6a-4f8c-938f-5e51b04d6a8d", - "user_id": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "skill_id": "e3084315-0355-4644-ae89-5a84f16d91e6", - "status": "APPROVED", - "created_at": "2024-03-02 11:59:59.999999", - "created_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "updated_at": "2024-03-02 11:59:59.999999", - "updated_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261" - }, - { - "id": "2513c590-78ff-4a56-90e4-5b3e06370b64", - "user_id": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "skill_id": "87490d7c-37a6-442d-8255-fd086555a35a", - "status": "PENDING", - "created_at": "2024-03-03 17:48:04.564729", - "created_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "updated_at": "2024-03-03 17:48:04.564729", - "updated_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb" - }, - { - "id": "cf4d6fc5-79c0-49ed-8f5b-4cc9c0e0c7b0", - "user_id": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "skill_id": "2bb70a9b-31d2-4a9b-9751-efb3feae4cd9", - "status": "APPROVED", - "created_at": "2024-03-04 14:33:27.901382", - "created_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261", - "updated_at": "2024-03-04 14:33:27.901382", - "updated_by": "73e0b7c4-d128-4e53-9501-0e7f4ff5a261" - }, - { - "id": "d1c947cb-ae6f-422e-ae67-bfd057f4177d", - "user_id": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "skill_id": "07a5b5c5-fd7f-4992-9fa7-5c4e41468b68", - "status": "PENDING", - "created_at": "2024-03-05 09:15:38.283750", - "created_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb", - "updated_at": "2024-03-05 09:15:38.283750", - "updated_by": "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb" - } -] \ No newline at end of file diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/EndorsementsIntegrationTests.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/EndorsementsIntegrationTests.java deleted file mode 100644 index a4b5cb1b..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/EndorsementsIntegrationTests.java +++ /dev/null @@ -1,589 +0,0 @@ -package com.RDS.skilltree.integration; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -import com.RDS.skilltree.Endorsement.*; -import com.RDS.skilltree.Skill.*; -import com.RDS.skilltree.User.*; -import io.restassured.response.Response; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.UUID; -import org.junit.jupiter.api.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import utils.RestAPIHelper; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class EndorsementsIntegrationTests extends TestContainerManager { - - private UserRepository userRepository; - private SkillRepository skillRepository; - private final UserService userService; - private final SkillsService skillsService; - private UserDTO user; - private SkillDTO skill; - private EndorsementRepository endorsementRepository; - - @Autowired - public EndorsementsIntegrationTests( - UserService userService, - UserRepository userRepository, - SkillsService skillsService, - SkillRepository skillRepository, - EndorsementRepository endorsementRepository) { - this.userService = userService; - this.userRepository = userRepository; - this.skillsService = skillsService; - this.skillRepository = skillRepository; - this.endorsementRepository = endorsementRepository; - } - - @BeforeEach - private void addData() throws MalformedURLException { - user = - userService.createUser( - UserDRO.builder() - .role(UserRole.MEMBER) - .rdsUserId("p6Bo61VEClhtVdwW0ihg") - .lastName("Doe") - .firstName("John") - .imageUrl( - new URL( - "https://res.cloudinary.com/realdevsquad/image/upload/v1666193594/profile/p6Bo61VEClhtVdwW0iGH/lezguwdq5bgzawa3.jpg")) - .build()); - - skill = - skillsService.createSkill( - SkillDRO.builder().name("Java").type(SkillType.ATOMIC).createdBy(user.getId()).build()); - } - - @AfterEach - private void cleanUp() { - endorsementRepository.deleteAll(); - skillRepository.deleteAll(); - userRepository.deleteAll(); - } - - private UUID createEndorsementModel(Boolean isStatusPending) { - EndorsementStatus endorsementStatus; - if (isStatusPending) { - endorsementStatus = EndorsementStatus.PENDING; - } else { - endorsementStatus = EndorsementStatus.APPROVED; - } - EndorsementModel endorsementModel = - EndorsementModel.builder().status(endorsementStatus).build(); - return endorsementRepository.save(endorsementModel).getId(); - } - - @Test - @Disabled - @DisplayName("Fetch all the endorsements") - public void testAPIReturnsAllEndorsements() { - Response response = given().cookies(RestAPIHelper.getUserCookie()).get("/endorsements"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("data", hasSize(1)) - .body("data[0].endorseeId", equalTo("user-1")) - .body("data[0].skillName", equalTo("Java")) - .body("data[0].status", anyOf(equalTo("APPROVED"), equalTo("REJECTED"), equalTo("PENDING"))) - .body("data[0].endorsementType", anyOf(equalTo("POSITIVE"), equalTo("NEGATIVE"))) - .body("data[0].endorsersList", hasSize(1)) - .body("data[0].endorserList[0].endorseeId", equalTo("user-2")) - .body("data[0].endorserList[0].description", isA(String.class)) - .body( - "data[0].endorserList[0].userType", - anyOf(equalTo("NORMAL_USER"), equalTo("SUPER_USER"), equalTo("MAVEN"))); - } - - @Test - @Disabled - @DisplayName("Fetch all the endorsements given endorsement status") - public void testAPIReturnsEndorsementsGivenStatus() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .queryParam("status", "PENDING") - .get("/endorsements"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("data", hasSize(1)) - .body("data[0].endorseeId", equalTo("user-1")) - .body("data[0].skillName", equalTo("Java")) - .body("data[0].status", equalTo("PENDING")) - .body("data[0].endorsementType", anyOf(equalTo("POSITIVE"), equalTo("NEGATIVE"))) - .body("data[0].endorsersList", hasSize(1)) - .body("data[0].endorserList[0].endorseeId", equalTo("user-2")) - .body("data[0].endorserList[0].description", isA(String.class)) - .body( - "data[0].endorserList[0].userType", - anyOf(equalTo("NORMAL_USER"), equalTo("SUPER_USER"), equalTo("MAVEN"))); - } - - @Test - @Disabled - @DisplayName("Return 400 on invalid endorsement status passed") - public void testAPIReturns400_OnInvalidStatusPassed() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .queryParam("status", "APPROVAL") - .get("/endorsements"); - - response - .then() - .statusCode(400) - .body("code", equalTo(400)) - .body("message", equalTo("Invalid status passed")); - } - - @Test - @Disabled - @DisplayName("Return 400 on invalid endorsementId passed") - public void testAPIReturns400_OnInvalidParameterPassed() { - String endorsementId = "randomId"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .patch("/endorsements"); - - response - .then() - .statusCode(400) - .body("code", equalTo(400)) - .body("message", equalTo("Invalid endorsementId passed")); - } - - @Test - @DisplayName("Return 201 on endorsements creation") - public void testAPIReturns201_OnEndorsementCreation() { - UUID endorseeId = user.getId(); - UUID skillId = skill.getId(); - - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorseeId); - endorsementDRO.setSkillId(skillId); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(endorsementDRO) - .post("/v1/endorsements"); - - response - .then() - .statusCode(201) - .contentType("application/json") - .body("data.endorseeId", equalTo(endorseeId.toString())) - .body("data.skill.name", equalTo("Java")); - } - - @Test - @DisplayName("Return 400 on endorsements userid null") - public void testAPIReturns400_OnEndorsementCreationUserIdNull() { - - UUID skillId = skill.getId(); - - EndorsementDRO endorsementDRO = new EndorsementDRO(); - - endorsementDRO.setSkillId(skillId); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(endorsementDRO) - .post("/v1/endorsements"); - - response - .then() - .statusCode(400) - .contentType("application/json") - .body("data", equalTo(null)) - .body("message", equalTo("user id cannot be null")); - } - - @Test - @DisplayName("Return 400 on endorsements skillid null") - public void testAPIReturns400_OnEndorsementCreationSkillIdNull() { - UUID endorseeId = user.getId(); - - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorseeId); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(endorsementDRO) - .post("/v1/endorsements"); - - response - .then() - .statusCode(400) - .contentType("application/json") - .body("data", equalTo(null)) - .body("message", equalTo("skill id cannot be null")); - } - - @Test - @Disabled - @DisplayName("Return 200 on endorsements updation") - public void testAPIReturns200_OnEndorsementGivenId() { - String endorsementId = "e-1"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .patch("/endorsements"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("code", equalTo(200)) - .body("data.endorseeId", equalTo("user-1")) - .body("data.skillName", equalTo("Java")) - .body("data.status", anyOf(equalTo("APPROVED"), equalTo("PENDING"), equalTo("REJECTED"))) - .body("data.endorsementType", anyOf(equalTo("POSITIVE"), equalTo("NEGATIVE"))) - .body("data.endorsersList", hasSize(1)) - .body("data.endorsersList[0].endorseeId", equalTo("user-2")) - .body("data.endorsersList[0].description", isA(String.class)) - .body( - "data.endorsersList[0].userType", - anyOf(equalTo("SUPER_USER"), equalTo("MAVEN"), equalTo("USER"))); - } - - @Test - @Disabled - @DisplayName("Return 400 on invalid endorsementId passed") - public void testAPIReturn400_OnInvalidIdPassed() { - String endorsementId = "randomId"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .get("/endorsements"); - - response - .then() - .statusCode(400) - .body("code", equalTo(400)) - .body("message", equalTo("Invalid endorsementId passed")); - } - - @Test - @Disabled - @DisplayName("Return 404 when endorsement not found given endorsementId") - public void testAPIReturn404_OnEndorsementNotFound() { - String endorsementId = "randomId"; - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("endorsementId", endorsementId) - .get("/endorsements"); - - response - .then() - .statusCode(404) - .body("code", equalTo(404)) - .body("message", equalTo("Endorsement not found")); - } - - @Test - @DisplayName("Return 200, with the endorsements of a particular user given userID") - public void itShouldReturn200OnEndorsementSearchByUserIDPresentInList() { - String userID = "f13ac7a0-76ab-4215-8bfc-2dd5d9f8ebeb"; - - Response response = given().get("/v1/endorsements?dummyData=true&userID=" + userID); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("content", everyItem(hasKey("user_id"))) - .body("content.user_id", everyItem(equalTo(userID))) - .body("content.size()", equalTo(7)) - .body("totalPages", equalTo(1)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(7)); - } - - @Test - @DisplayName("Return 200, with the endorsements of a particular skill given skillID") - public void itShouldReturn200OnEndorsementSearchBySkillIDPresentInList() { - String skillID = "7a6b8876-44e3-4b18-8579-79e9d4a5f0c9"; - - Response response = given().get("/v1/endorsements?dummyData=true&skillID=" + skillID); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("content", everyItem(hasKey("skill_id"))) - .body("content.skill_id", everyItem(equalTo(skillID))) - .body("content.size()", equalTo(1)) - .body("totalPages", equalTo(1)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(1)); - } - - @Test - @DisplayName("Return 200, with 1st page all the endorsements with default pagesize") - public void itShouldReturn200OnEndorsementSearchAllEndorsements() { - Response response = given().get("/v1/endorsements?dummyData=true"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(2)) - .body("content.size()", equalTo(10)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with 1st page all the endorsements with custom limit value") - public void itShouldReturn200OnEndorsementSearchAllEndorsementsWithLimit() { - Response response = given().get("/v1/endorsements?dummyData=true&limit=15"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(1)) - .body("content.size()", equalTo(14)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(15)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with 1st page of all endorsements result where page size is 5") - public void itShouldReturn200OnEndorsementSearchAllEndorsementsWithMultiplePages() { - Response response = given().get("/v1/endorsements?dummyData=true&limit=5"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(3)) - .body("content.size()", equalTo(5)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(5)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with 2nd page of all the endorsements result") - public void itShouldReturn200With2ndPageOnEndorsementSearchAllEndorsementsWithMultiplePages() { - Response response = given().get("/v1/endorsements?dummyData=true&limit=5&offset=1"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("totalPages", equalTo(3)) - .body("content.size()", equalTo(5)) - .body("pageable.pageNumber", equalTo(1)) - .body("pageable.pageSize", equalTo(5)) - .body("totalElements", equalTo(14)); - } - - @Test - @DisplayName("Return 200, with the endorsements matching the given userID and skillID") - public void itShouldReturn200OnEndorsementSearchGivenBothUserIDAndSkillID() { - String userID = "73e0b7c4-d128-4e53-9501-0e7f4ff5a261"; - String skillID = "7a6b8876-44e3-4b18-8579-79e9d4a5f0c9"; - - Response response = - given().get("/v1/endorsements?dummyData=true&skillID=" + skillID + "&userID=" + userID); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("content", everyItem(hasKey("skill_id"))) - .body("content.skill_id", everyItem(equalTo(skillID))) - .body("content", everyItem(hasKey("user_id"))) - .body("content.user_id", everyItem(equalTo(userID))) - .body("content.size()", equalTo(1)) - .body("totalPages", equalTo(1)) - .body("pageable.pageNumber", equalTo(0)) - .body("pageable.pageSize", equalTo(10)) - .body("totalElements", equalTo(1)); - } - - @Test - @DisplayName( - "Return 204, when there are no endorsements present for the given userID in UUID form") - public void itShouldReturn204OnEndorsementSearchWithValidUserIDButNotPresentInList() { - String userID = UUID.randomUUID().toString(); - - Response response = given().get("/v1/endorsements?dummyData=true&userID=" + userID); - - response.then().statusCode(204); - } - - @Test - @DisplayName( - "Return 204, when there are no endorsements present for the given skillID in UUID form") - public void itShouldReturn204OnEndorsementSearchWithValidSkillIDButNotPresentInList() { - String skillID = UUID.randomUUID().toString(); - - Response response = given().get("/v1/endorsements?dummyData=true&skillID=" + skillID); - - response.then().statusCode(204); - } - - @Test - @DisplayName("Return 400, given a userID which is not a UUID") - public void itShouldReturn400OnEndorsementSearchWithInvalidUserID() { - String userID = "invalid-user-id"; - - Response response = given().get("/v1/endorsements?dummyData=true&userID=" + userID); - - response.then().statusCode(400); - } - - @Test - @DisplayName("Return 400, given a skillID which is not a UUID") - public void itShouldReturn400OnEndorsementSearchWithInvalidSkillID() { - String skillID = "invalid-skill-id"; - - Response response = given().get("/v1/endorsements?dummyData=true&skillID=" + skillID); - - response.then().statusCode(400); - } - - @Test - @DisplayName("Return 204, given an offset value greater than maximum endorsements") - public void itShouldReturn204OnEndorsementSearchWithOffsetGreaterThanMaximumEndorsements() { - Response response = given().get("/v1/endorsements?dummyData=true&offset=10"); - - response.then().statusCode(204); - } - - @Test - @Disabled - @DisplayName("Return 401, when request is made without a valid cookie") - public void itShouldReturn401OnEndorsementSearchWithoutCookie() { - Response response = given().get("/v1/endorsements"); - - response - .then() - .statusCode(401) - .body( - "message", - equalTo( - "The access token provided is expired, revoked, malformed, or invalid for other reasons.")); - } - - @Test - @DisplayName( - "Return 200, when request is made using super user cookie and status is APPROVED/REJECTED") - public void - itShouldReturn200OnUpdateEndorsementStatusWithSuperUserCookieAndAcceptOrRejectEndorsementStatus() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", EndorsementStatus.APPROVED.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(200) - .body("data", equalTo(null)) - .body("message", equalTo("Successfully updated endorsement status")); - } - - @Test - @DisplayName( - "Return 403, when request is made without using super user cookie and status is APPROVED/REJECTED") - public void - itShouldReturn403OnUpdateEndorsementStatusWithOutSuperUserCookieAndAcceptOrRejectEndorsementStatus() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .queryParam("status", EndorsementStatus.APPROVED.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(403) - .body("data", equalTo(null)) - .body("message", equalTo("Unauthorized, Access is only available to super users")); - } - - @Test - @DisplayName( - "Return 400, when request is made with using super user cookie and status is invalid") - public void - itShouldReturn400OnUpdateEndorsementStatusWithSuperUserCookieAndEndorsementStatusIsInvalid() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", "invalid-status") - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Invalid parameter endorsement status: invalid-status")); - } - - @Test - @DisplayName( - "Return 400, when request is made with using super user cookie and status is PENDING") - public void - itShouldReturn400OnUpdateEndorsementStatusWithSuperUserCookieAndEndorsementStatusIsPending() { - UUID endorsementId = createEndorsementModel(true); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", EndorsementStatus.PENDING.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Invalid parameter endorsement status: PENDING")); - } - - @Test - @DisplayName( - "Return 409, when request is made with using super user cookie and endorsement is already updated") - public void - itShouldReturn409OnUpdateEndorsementStatusWithSuperUserCookieAndEndorsementAlreadyUpdated() { - UUID endorsementId = createEndorsementModel(false); - Response response = - given() - .cookies(RestAPIHelper.getSuperUserCookie()) - .queryParam("status", EndorsementStatus.APPROVED.name()) - .patch("/v1/endorsements/{id}", endorsementId); - - response - .then() - .statusCode(409) - .body("data", equalTo(null)) - .body("message", equalTo("Endorsement is already updated. Cannot modify status")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/SecurityContextIntegrationTest.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/SecurityContextIntegrationTest.java deleted file mode 100644 index 19754e71..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/SecurityContextIntegrationTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.RDS.skilltree.integration; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.equalTo; - -import io.restassured.response.Response; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.springframework.boot.test.context.SpringBootTest; -import utils.RestAPIHelper; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SecurityContextIntegrationTest extends TestContainerManager { - - @Test - public void testTokenIsNotPresent() { - - Response response = given().get("/v1/endorsement"); - response - .then() - .statusCode(401) - .body( - "message", - equalTo( - "The access token provided is expired, revoked, malformed, or invalid for other reasons.")); - } - - @Test - public void testInvalidToken() { - Response response = given().cookie("rds-session-v2", "invalidtoken").get("/v1/endorsement"); - response - .then() - .statusCode(401) - .body( - "message", - equalTo( - "The access token provided is expired, revoked, malformed, or invalid for other reasons.")); - } - - @Test - public void test_GetSkill_WithGuestToken() { - Response response = - given() - .cookies(RestAPIHelper.getGuestUserCookie()) - .contentType("application/json") - .get("/v1/skills/"); - response.then().statusCode(200); - } - - @Test - public void test_CreateSkill_WithGuestToken() { - Response response = - given() - .cookies(RestAPIHelper.getGuestUserCookie()) - .contentType("application/json") - .post("/v1/skills/"); - response.then().statusCode(403).body("message", equalTo("Access Denied")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/SkillsIntegrationTests.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/SkillsIntegrationTests.java deleted file mode 100644 index 9fd65268..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/SkillsIntegrationTests.java +++ /dev/null @@ -1,268 +0,0 @@ -package com.RDS.skilltree.integration; - -import static io.restassured.RestAssured.given; -import static org.hamcrest.Matchers.*; - -import com.RDS.skilltree.Skill.*; -import com.RDS.skilltree.User.*; -import io.restassured.response.Response; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.UUID; -import org.junit.jupiter.api.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import utils.RestAPIHelper; - -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -public class SkillsIntegrationTests extends TestContainerManager { - private UserRepository userRepository; - private SkillRepository skillRepository; - private final UserService userService; - private final SkillsService skillsService; - private UserDTO user; - private SkillDTO skill; - - @Autowired - public SkillsIntegrationTests( - UserService userService, - UserRepository userRepository, - SkillsService skillsService, - SkillRepository skillRepository) { - this.userService = userService; - this.userRepository = userRepository; - this.skillsService = skillsService; - this.skillRepository = skillRepository; - } - - @BeforeEach - private void addData() throws MalformedURLException { - user = - userService.createUser( - UserDRO.builder() - .role(UserRole.MEMBER) - .rdsUserId("p6Bo61VEClhtVdwW0ihg") - .lastName("Doe") - .firstName("John") - .imageUrl( - new URL( - "https://res.cloudinary.com/realdevsquad/image/upload/v1666193594/profile/p6Bo61VEClhtVdwW0iGH/lezguwdq5bgzawa3.jpg")) - .build()); - - skill = - skillsService.createSkill( - SkillDRO.builder().name("Java").type(SkillType.ATOMIC).createdBy(user.getId()).build()); - } - - @AfterEach - private void cleanUp() { - skillRepository.deleteAll(); - userRepository.deleteAll(); - } - - @Test - @DisplayName("Return 200, on all skills") - public void testAPIReturns200_OnAllSkillsFound() { - Response response = - given() - .queryParam("offset", 0) - .queryParam("limit", 1) - .cookies(RestAPIHelper.getUserCookie()) - .get("/v1/skills/"); - - response - .then() - .statusCode(200) - .body("content", hasSize(1)) - .body("content[0].type", equalTo("ATOMIC")) - .body("content[0].name", equalTo("Java")) - .body("content[0].users", empty()) - .body("totalPages", equalTo(1)) - .body("totalElements", equalTo(1)) - .body("last", equalTo(true)) - .body("size", equalTo(1)) - .body("number", equalTo(0)) - .body("numberOfElements", equalTo(1)) - .body("empty", equalTo(false)); - } - - @Test - @DisplayName("Return 200, on no skills found") - public void testAPIReturns200_OnNoSkillsFound() { - skillRepository.deleteAll(); - Response response = given().cookies(RestAPIHelper.getUserCookie()).get("/v1/skills/"); - - response - .then() - .statusCode(200) - .body("content", hasSize(0)) - .body("totalPages", equalTo(0)) - .body("totalElements", equalTo(0)) - .body("last", equalTo(true)) - .body("size", equalTo(10)) - .body("number", equalTo(0)) - .body("numberOfElements", equalTo(0)) - .body("empty", equalTo(true)); - } - - @Test - @DisplayName("Return 200, on skill found given skillId") - public void testAPIReturns200_OnSkillFoundById() { - UUID skillId = skill.getId(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("id", skillId) - .get("/v1/skills/{id}"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("id", equalTo(String.valueOf(skillId))) - .body("name", equalTo("Java")) - .body("type", equalTo("ATOMIC")); - } - - @Test - @DisplayName("Return 404, on skill not found given SkillId") - public void testAPIReturns404_OnSkillNotFound() { - UUID skillId = UUID.randomUUID(); - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("id", skillId) - .get("/v1/skills/{id}"); - - response.then().statusCode(404).body("message", equalTo("Skill not found with given Id")); - } - - @Test - @DisplayName("Return 200, on skill with given name") - public void testAPIReturns200_OnSkillFoundGivenName() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("name", "Java") - .get("/v1/skills/name/{name}"); - - response - .then() - .statusCode(200) - .contentType("application/json") - .body("name", equalTo("Java")) - .body("id", equalTo(skill.getId().toString())) - .body("type", equalTo("ATOMIC")); - } - - @Test - @DisplayName("Return 404, if skill given skill name is not found") - public void testAPIReturns404_OnSkillGivenSkillNameNotFound() { - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .pathParam("name", "Go") - .get("/v1/skills/name/{name}"); - - response.then().statusCode(404).body("message", equalTo("Skill not found with the given name")); - } - - @Test - @DisplayName("Return 400, if createdBy is not passed for Skill creation") - public void testAPIReturns400_OnCreatedByNotPassedForSKillCreation() { - SkillDRO skillDRO = SkillDRO.builder().name("Go").type(SkillType.ATOMIC).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Created by user Id cannot be null")); - } - - @Test - @DisplayName("Return 400, if type is not passed for Skill creation") - public void testAPIReturns400_OnTypeNotPassedForSkillCreation() { - SkillDRO skillDRO = SkillDRO.builder().name("Go").createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("SkillType cannot be null")); - } - - @Test - @DisplayName("Return 400, if name is not passed for Skill creation") - public void testAPIReturns400_OnNameNotPassedForSkillCreation() { - SkillDRO skillDRO = SkillDRO.builder().type(SkillType.ATOMIC).createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(400) - .body("data", equalTo(null)) - .body("message", equalTo("Name cannot be null")); - } - - @Test - @DisplayName("Return 409, if name is already used for Skill creation") - public void testAPIReturns409_OnNameAlreadyUsedForSkillCreation() { - SkillDRO skillDRO = - SkillDRO.builder().type(SkillType.ATOMIC).name("Java").createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(409) - .body("message", equalTo("Cannot create entry for Skill as Skill name is duplicate")); - } - - @Test - @DisplayName("Return 201, on successful Skill creation") - public void testAPIReturns201_OnSuccessfulSkillCreation() { - SkillDRO skillDRO = - SkillDRO.builder().type(SkillType.ATOMIC).name("Go").createdBy(user.getId()).build(); - - Response response = - given() - .cookies(RestAPIHelper.getUserCookie()) - .contentType("application/json") - .body(skillDRO) - .post("/v1/skills/"); - - response - .then() - .statusCode(201) - .contentType("application/json") - .body("name", equalTo("Go")) - .body("type", equalTo("ATOMIC")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/integration/TestContainerManager.java b/skill-tree/src/test/java/com/RDS/skilltree/integration/TestContainerManager.java deleted file mode 100644 index ecd0ff75..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/integration/TestContainerManager.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.RDS.skilltree.integration; - -import org.springframework.boot.testcontainers.service.connection.ServiceConnection; -import org.springframework.test.context.DynamicPropertyRegistry; -import org.springframework.test.context.DynamicPropertySource; -import org.testcontainers.containers.MySQLContainer; - -abstract class TestContainerManager { - @ServiceConnection static final MySQLContainer mysqlContainer; - - static { - mysqlContainer = - new MySQLContainer("mysql:8.1") - .withDatabaseName("skilltree-test") - .withUsername("root") - .withPassword("password"); - mysqlContainer.start(); - } - - @DynamicPropertySource - static void configureTestProperties(DynamicPropertyRegistry registry) { - registry.add("spring.jpa.hibernate.ddl-auto", () -> "update"); - registry.add("cookieName", () -> "rds-session-v2"); - registry.add( - "jwt.rds.public.key", - () -> - "-----BEGIN PUBLIC KEY-----MIICITANBgkqhkiG9w0BAQEFAAOCAg4AMIICCQKCAgBpAet8sOf64PtzdnwtkZB4JEJTCtQT9ZQMuuWUDXZGTG0iO7x3WZw6GanBboKGblU4VZEgd8H7bKOOIaQF4AsiXsw/vUsOV5Ue73a9Jj5d57jyon7M8fFmjna3afZfb5SBru5Iv0ECePqIKUIhSmToML+y3bFKF2cbUTEe2qPK5xzBeH4AWq4Zb2N0gHNstinwrXL9LWawQPkJr23TohZZEFSzyZbeklWWwz67A6YnE01w42R/TLE3LmU8YKkrHkgFsAHtUMQO++JsH4q3F9J0e0VkLzj5sB5RgAYscs6YFKoFD5jKgtSRPIXz7O9GsC76dHtwGXOk47/NWxu7bUQ0VcD2hJYprR28PjdNk5KiRKO5Z83JkiM6ed9UAkiD/fIRI8LITaLayHdFfQvXM+d9v4ugPHEq+aVllFMH1lUu/2B1aJpk4D4w5JcIzIZ9og4cMz00EGU/1o+BX2S55/Ok 4MaxX6Zl3QYm1K0cPLOdisYoygPtnNEav32JLgM2yOXdyuhpYzmn66yyFFck2nnCkezG5Gvlf3MejMavRO+sfIz0gDIhXEwWu0EJDrG5nmNRwejrSXx42YxmYZGkK/c8 2fiwbOVqIuFgsI6lWGdyDayFRg9bjrk6KiQZFnP4KcmUXk4PhiSItDJAUEkNz0+4StHNoqFhNH5pnEj4VbmJqwIDAQAB -----END PUBLIC KEY-----"); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementListServiceTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementListServiceTest.java deleted file mode 100644 index 4a7e0ad4..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementListServiceTest.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -import com.RDS.skilltree.Endorsement.EndorsementModel; -import com.RDS.skilltree.Endorsement.EndorsementRepository; -import com.RDS.skilltree.EndorsementList.*; -import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRepository; -import java.util.Optional; -import java.util.UUID; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -class EndorsementListServiceTest { - - @Mock private EndorsementListRepository endorsementListRepository; - - @Mock private EndorsementRepository endorsementRepository; - - @Mock private UserRepository userRepository; - - @InjectMocks private EndorsementListService endorsementListService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - } - - @Test - void testCreateEndorsementListEntry() { - // Mock data - UUID endorserId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementListDRO endorsementListDRO = new EndorsementListDRO(); - endorsementListDRO.setEndorserId(endorserId); - endorsementListDRO.setEndorsementId(endorsementId); - endorsementListDRO.setDescription("Test Description"); - endorsementListDRO.setType(EndorsementType.POSITIVE); - - UserModel mockUser = new UserModel(); - mockUser.setId(endorserId); - - EndorsementModel mockEndorsement = EndorsementModel.builder().id(endorsementId).build(); - - // Mock the repository behavior - when(userRepository.findById(endorserId)).thenReturn(Optional.of(mockUser)); - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(mockEndorsement)); - - // Call the service method - EndorsementListModel result = - endorsementListService.createEndorsementListEntry(endorsementListDRO); - - // Verify the interactions - verify(endorsementListRepository, times(1)).save(any(EndorsementListModel.class)); - - // Assertions - assertNotNull(result); - assertEquals(endorserId, result.getEndorserId()); - assertEquals(endorsementId, result.getEndorsement().getId()); - assertEquals("Test Description", result.getDescription()); - assertEquals(EndorsementType.POSITIVE, result.getType()); - } - - @Test - void testCreateEndorsementListEntryWithInvalidEndorsement() { - UUID endorserId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementListDRO endorsementListDRO = new EndorsementListDRO(); - endorsementListDRO.setEndorserId(endorserId); - endorsementListDRO.setEndorsementId(endorsementId); - - UserModel mockUser = new UserModel(); - mockUser.setId(endorserId); - - // Mock the repository behavior for an invalid endorsement - when(userRepository.findById(endorserId)).thenReturn(Optional.of(mockUser)); - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.empty()); - - // Assert that a NoEntityException is thrown - NoEntityException exception = - assertThrows( - NoEntityException.class, - () -> endorsementListService.createEndorsementListEntry(endorsementListDRO)); - assertEquals("Endorsement with id:" + endorsementId + " not found", exception.getMessage()); - - // Verify that save method is not called - verify(endorsementListRepository, never()).save(any(EndorsementListModel.class)); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementServiceTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementServiceTest.java deleted file mode 100644 index 2ee4dcef..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/EndorsementServiceTest.java +++ /dev/null @@ -1,746 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -import com.RDS.skilltree.Common.Response.GenericResponse; -import com.RDS.skilltree.Endorsement.*; -import com.RDS.skilltree.Exceptions.EntityAlreadyExistsException; -import com.RDS.skilltree.Exceptions.InvalidParameterException; -import com.RDS.skilltree.Exceptions.NoEntityException; -import com.RDS.skilltree.Skill.SkillModel; -import com.RDS.skilltree.Skill.SkillRepository; -import com.RDS.skilltree.User.UserModel; -import com.RDS.skilltree.User.UserRepository; -import com.RDS.skilltree.User.UserRole; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import jakarta.persistence.EntityNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.time.Instant; -import java.time.LocalDateTime; -import java.util.*; -import org.junit.jupiter.api.*; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.test.util.ReflectionTestUtils; - -@ExtendWith(MockitoExtension.class) -public class EndorsementServiceTest { - @Mock private EndorsementRepository endorsementRepository; - - @Mock private UserRepository userRepository; - - @Mock private SkillRepository skillRepository; - - @Mock private ObjectMapper objectMapper; - - @InjectMocks @Autowired private EndorsementServiceImpl endorsementService; - - @Mock private Authentication auth; - - @BeforeEach - public void setUp() { - ReflectionTestUtils.setField( - endorsementService, "dummyEndorsementDataPath", "dummy-data/endorsements.json"); - } - - @AfterEach - public void clearSecurityContext() { - SecurityContextHolder.clearContext(); - } - - private void setupUpdateEndorsementTests(Boolean useSuperUserRole) { - UserModel userModel = new UserModel(); - if (useSuperUserRole) { - userModel.setRole(UserRole.SUPERUSER); - } else { - userModel.setRole(UserRole.USER); - } - when(auth.getPrincipal()).thenReturn(userModel); - SecurityContextHolder.getContext().setAuthentication(auth); - } - - @Test - public void itShouldGetEndorsementsById() { - UUID endorsementId = UUID.randomUUID(); - UUID endorserId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - - SkillModel skillModel = SkillModel.builder().id(skillId).build(); - EndorsementModel endorsementModel = - EndorsementModel.builder() - .id(endorsementId) - .endorseeId(endorserId) - .skill(skillModel) - .build(); - endorsementModel.setCreatedAt(Instant.now()); - endorsementModel.setUpdatedAt(Instant.now()); - endorsementModel.setCreatedBy(endorsementId); - endorsementModel.setUpdatedBy(endorsementId); - - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(endorsementModel)); - - EndorsementDTO result = endorsementService.getEndorsementById(endorsementId); - - assertNotNull(result); - assertEquals( - endorsementId, - result.getId(), - "The Endorsement Id doesn't matches the expected endorsement Id"); - } - - @Test - @DisplayName("Get endorsements given a valid skillID") - public void itShouldReturnEndorsementsGivenSkillID() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, null); - - assertEquals(new PageImpl<>(dummyEndorsements, pageRequest, dummyEndorsements.size()), result); - assertEquals(1, result.getTotalElements()); - } - - @Test - @DisplayName("Get endorsements given a valid userID") - void itShouldGetEndorsementsGivenUserID() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, null, userID); - - assertEquals(new PageImpl<>(dummyEndorsements, pageRequest, dummyEndorsements.size()), result); - assertEquals(1, result.getTotalElements()); - } - - @Test - @DisplayName("Get endorsements given an invalid userID") - public void itShouldThrowErrorIfInvalidUserIDIsGiven() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - - assertThrows( - IllegalArgumentException.class, - () -> - endorsementService.getEndorsementsFromDummyData(pageRequest, null, "invalid-user-id")); - } - - @Test - @DisplayName("Get endorsements given an invalid skillID") - public void itShouldThrowIllegalArgumentExceptionIfInvalidSkillIDIsGiven() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - - assertThrows( - IllegalArgumentException.class, - () -> - endorsementService.getEndorsementsFromDummyData(pageRequest, "invalid-skill-id", null)); - } - - @Test - @DisplayName("Get endorsements given a valid userID and invalid skillID") - public void itShouldThrowIllegalArgumentExceptionIfInvalidUserIDIsGiven() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "PENDING", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - - assertThrows( - IllegalArgumentException.class, - () -> - endorsementService.getEndorsementsFromDummyData( - pageRequest, "invalid-skill-id", UUID.randomUUID().toString())); - } - - @Test - @DisplayName( - "Return paginated result having 2 pages when number of endorsements with a given userID is 15") - public void itShouldReturnPaginatedResultOnSearch() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - for (int i = 0; i < 15; i++) { - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.randomUUID(), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - } - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, null, userID); - - assertEquals(2, result.getTotalPages()); - assertEquals(15, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty page when accessing out of bound page in paginated result") - public void itShouldReturnEmptyPaginatedResultOnSearch() throws IOException { - PageRequest pageRequest = PageRequest.of(10, 10); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - for (int i = 0; i < 15; i++) { - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.randomUUID(), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - } - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, null, userID); - - assertEquals(Page.empty(pageRequest), result); - } - - @Test - @DisplayName( - "Return empty endorsement list given a valid userID but skillID which is not present") - public void itShouldReturnEmptyDataGivenUserIDAndSkillIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.randomUUID(), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, userID); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty page when no endorsements are present in dummy data") - public void itShouldReturnEmptyDataWhenNoEndorsementsArePresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, userID); - - assertEquals(Page.empty(pageRequest), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given a userID which is not present") - public void itShouldReturnEmptyDataGivenUserIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData( - pageRequest, null, UUID.randomUUID().toString()); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given empty userID and skillID") - public void itShouldReturnEmptyDataGivenEmptyUserIDAndSkillID() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData(pageRequest, "", ""); - - assertEquals(new PageImpl<>(dummyEndorsements, pageRequest, dummyEndorsements.size()), result); - assertEquals(1, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given a skillID which is not present") - public void itShouldReturnEmptyDataGivenSkillIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData( - pageRequest, UUID.randomUUID().toString(), null); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return empty endorsement list given a skillID and userID which is not present") - public void itShouldReturnEmptyDataGivenSkillIDAndUserIDNotPresent() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = UUID.randomUUID().toString(); - String userID = UUID.randomUUID().toString(); - - List dummyEndorsements = new ArrayList<>(); - dummyEndorsements.add( - new EndorsementModelFromJSON( - UUID.randomUUID(), - UUID.fromString(userID), - UUID.fromString(skillID), - "APPROVED", - LocalDateTime.now(), - UUID.randomUUID(), - LocalDateTime.now(), - UUID.randomUUID())); - List endorsementsResult = new ArrayList<>(); - - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenReturn(dummyEndorsements); - Page result = - endorsementService.getEndorsementsFromDummyData( - pageRequest, UUID.randomUUID().toString(), UUID.randomUUID().toString()); - - assertEquals( - new PageImpl<>(endorsementsResult, pageRequest, endorsementsResult.size()), result); - assertEquals(0, result.getTotalElements()); - } - - @Test - @DisplayName("Return IO exception on error reading data") - void itShouldReturnIOExceptionIfErrorReadingData() throws IOException { - PageRequest pageRequest = PageRequest.of(0, 10); - String skillID = null; - String userID = null; - when(objectMapper.readValue( - ArgumentMatchers.any(), - ArgumentMatchers.>>any())) - .thenThrow(new IOException("Error reading data")); - - assertThrows( - IOException.class, - () -> endorsementService.getEndorsementsFromDummyData(pageRequest, skillID, userID)); - } - - @Test - public void itShouldHandleEndorsementNotFound() { - UUID nonExistentEndorsementId = UUID.randomUUID(); - when(endorsementRepository.findById(nonExistentEndorsementId)).thenReturn(Optional.empty()); - - EntityNotFoundException exception = - assertThrows( - EntityNotFoundException.class, - () -> endorsementService.getEndorsementById(nonExistentEndorsementId)); - - // Verify the exception message - assertEquals( - "No endorsement with the id " + nonExistentEndorsementId + " found", - exception.getMessage()); - } - - @Test - void testCreateEndorsement() { - // Mock data - UUID endorserId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorserId); - endorsementDRO.setSkillId(skillId); - - SkillModel mockSkill = SkillModel.builder().id(skillId).build(); - EndorsementModel mockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .endorseeId(endorserId) - .skill(mockSkill) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorserId); - mockEndorsement.setUpdatedBy(endorserId); - - // Mock the repository behavior - when(skillRepository.findById(skillId)).thenReturn(Optional.of(mockSkill)); - when(endorsementRepository.save(any(EndorsementModel.class))).thenReturn(mockEndorsement); - - // Call the service method - EndorsementModel result = endorsementService.createEndorsement(endorsementDRO); - - // Verify the interactions - verify(endorsementRepository, times(1)).save(any(EndorsementModel.class)); - - // Assertions - assertNotNull(result); - assertEquals(endorserId, result.getEndorseeId()); - assertEquals(skillId, result.getSkill().getId()); - } - - @Test - void testCreateEndorsementWithInvalidSkill() { - UUID endorserId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - EndorsementDRO endorsementDRO = new EndorsementDRO(); - endorsementDRO.setEndorseeId(endorserId); - endorsementDRO.setSkillId(skillId); - - // Mock the repository behavior for an invalid skill - when(skillRepository.findById(skillId)).thenReturn(Optional.empty()); - - // Assert that a NoEntityException is thrown - NoEntityException exception = - assertThrows( - NoEntityException.class, () -> endorsementService.createEndorsement(endorsementDRO)); - assertEquals("Skill with id:" + skillId + " not found", exception.getMessage()); - - // Verify that save method is not called - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName( - "Return unauthorized access, given user is not a super user to update endorsement status") - public void itShouldReturnUnauthorizedGivenUserIsNotSuperUser() { - setupUpdateEndorsementTests(false); - - UUID endorsementId = UUID.randomUUID(); - String status = EndorsementStatus.APPROVED.name(); - - AccessDeniedException exception = - assertThrows( - AccessDeniedException.class, - () -> endorsementService.updateEndorsementStatus(endorsementId, status)); - assertEquals("Unauthorized, Access is only available to super users", exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return invalid status given status is pending") - public void itShouldReturnInvalidStatusGivenEndorsementStatusIsPending() { - setupUpdateEndorsementTests(true); - - UUID endorsementId = UUID.randomUUID(); - String status = EndorsementStatus.PENDING.name(); - - InvalidParameterException exception = - assertThrows( - InvalidParameterException.class, - () -> endorsementService.updateEndorsementStatus(endorsementId, status)); - assertEquals("Invalid parameter endorsement status: " + status, exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return invalid status given status is invalid") - public void itShouldReturnInvalidStatusGivenInvalidEndorsementStatus() { - setupUpdateEndorsementTests(true); - - UUID endorsementId = UUID.randomUUID(); - String status = "invalid-status"; - - InvalidParameterException exception = - assertThrows( - InvalidParameterException.class, - () -> endorsementService.updateEndorsementStatus(endorsementId, status)); - assertEquals("Invalid parameter endorsement status: " + status, exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return cannot modify status given status is already updated") - public void itShouldThrowEntityAlreadyExistsExceptionGivenEndorsementIsUpdated() { - setupUpdateEndorsementTests(true); - - UUID endorseeId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - - SkillModel mockSkill = SkillModel.builder().id(skillId).build(); - EndorsementModel mockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .status(EndorsementStatus.APPROVED) - .endorseeId(endorseeId) - .skill(mockSkill) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorseeId); - mockEndorsement.setUpdatedBy(endorseeId); - - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(mockEndorsement)); - - EntityAlreadyExistsException exception = - assertThrows( - EntityAlreadyExistsException.class, - () -> - endorsementService.updateEndorsementStatus( - endorsementId, EndorsementStatus.APPROVED.name())); - assertEquals("Endorsement is already updated. Cannot modify status", exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName("Return endorsement not found given an unknown endorsement id") - public void itShouldReturnEndorsementNotFoundGivenUnknownEndorsementId() { - setupUpdateEndorsementTests(true); - - UUID nonExistentEndorsementId = UUID.randomUUID(); - String status = EndorsementStatus.APPROVED.name(); - - when(endorsementRepository.findById(nonExistentEndorsementId)).thenReturn(Optional.empty()); - - NoEntityException exception = - assertThrows( - NoEntityException.class, - () -> endorsementService.updateEndorsementStatus(nonExistentEndorsementId, status)); - assertEquals( - "No endorsement with id " + nonExistentEndorsementId + " was found", - exception.getMessage()); - verify(endorsementRepository, never()).save(any(EndorsementModel.class)); - } - - @Test - @DisplayName( - "Update endorsement status given a valid endorsement id and status is approved or rejected") - public void itShouldUpdateEndorsementStatusGivenEndorsementIdAndStatusApprovedOrRejected() { - setupUpdateEndorsementTests(true); - - UUID endorseeId = UUID.randomUUID(); - UUID skillId = UUID.randomUUID(); - UUID endorsementId = UUID.randomUUID(); - EndorsementStatus status = EndorsementStatus.APPROVED; - - SkillModel mockSkill = SkillModel.builder().id(skillId).build(); - EndorsementModel mockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .status(EndorsementStatus.PENDING) - .endorseeId(endorseeId) - .skill(mockSkill) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorseeId); - mockEndorsement.setUpdatedBy(endorseeId); - - when(endorsementRepository.findById(endorsementId)).thenReturn(Optional.of(mockEndorsement)); - - GenericResponse result = - endorsementService.updateEndorsementStatus(endorsementId, status.name()); - assertEquals("Successfully updated endorsement status", result.getMessage()); - - verify(endorsementRepository, times(1)).save(any(EndorsementModel.class)); - - EndorsementModel updatedMockEndorsement = - EndorsementModel.builder() - .id(endorsementId) - .endorseeId(endorseeId) - .skill(mockSkill) - .status(EndorsementStatus.APPROVED) - .build(); - mockEndorsement.setCreatedAt(Instant.now()); - mockEndorsement.setUpdatedAt(Instant.now()); - mockEndorsement.setCreatedBy(endorseeId); - mockEndorsement.setUpdatedBy(endorseeId); - - when(endorsementRepository.findById(endorsementId)) - .thenReturn(Optional.of(updatedMockEndorsement)); - Optional updatedEndorsement = endorsementRepository.findById(endorsementId); - assertTrue(updatedEndorsement.isPresent()); - assertEquals(EndorsementStatus.APPROVED, updatedEndorsement.get().getStatus()); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/HealthCheckTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/HealthCheckTest.java deleted file mode 100644 index a10ae257..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/HealthCheckTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -import com.RDS.skilltree.Health.HealthCheckController; -import com.RDS.skilltree.metrics.MetricService; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - -class HealthCheckTest { - - @Mock private MetricService metricService; - - private HealthCheckController healthCheckController; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - healthCheckController = new HealthCheckController(metricService); - } - - @Test - void checkHealth() { - // Setup - when(metricService.getUptime()).thenReturn(123.0); - - // Execute - var result = healthCheckController.checkHealth(); - - // Assert - assertNotNull(result); - assertTrue(result.containsKey("uptimeInSeconds")); - assertEquals(123.0, result.get("uptimeInSeconds")); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/unit/SkillsServiceTest.java b/skill-tree/src/test/java/com/RDS/skilltree/unit/SkillsServiceTest.java deleted file mode 100644 index bf5e0bf8..00000000 --- a/skill-tree/src/test/java/com/RDS/skilltree/unit/SkillsServiceTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.RDS.skilltree.unit; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import com.RDS.skilltree.Skill.SkillDTO; -import com.RDS.skilltree.Skill.SkillModel; -import com.RDS.skilltree.Skill.SkillRepository; -import com.RDS.skilltree.Skill.SkillsServiceImpl; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.UUID; -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 org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; - -@ExtendWith(MockitoExtension.class) -public class SkillsServiceTest { - - @Mock private SkillRepository skillRepository; - - @InjectMocks @Autowired private SkillsServiceImpl skillService; - - @Test - public void testGetSkillById() { - UUID skillId = UUID.randomUUID(); - SkillModel skillModel = SkillModel.builder().id(skillId).build(); - - when(skillRepository.findById(skillId)).thenReturn(Optional.of(skillModel)); - - SkillDTO result = skillService.getSkillById(skillId); - assertNotNull(result); - assertEquals(skillId, result.getId(), "The skill Id doesn't matches the expected skillId"); - } - - @Test - public void testGetSkillsByName() { - String skillName = "Java"; - SkillModel skillModel = SkillModel.builder().name("Java").build(); - - when(skillRepository.findByName(skillName)).thenReturn(Optional.of(skillModel)); - - SkillDTO result = skillService.getSkillByName("Java"); - assertNotNull(result); - assertEquals( - skillName, result.getName(), "The skill name doesn't match the expected skill name"); - } - - @Test - public void testGetAllSkills() { - SkillModel skillJava = SkillModel.builder().name("Java").build(); - - SkillModel skillGo = SkillModel.builder().name("Go").build(); - - List skillModelList = Arrays.asList(skillJava, skillGo); - - when(skillRepository.findAll((Pageable) any(Pageable.class))) - .thenReturn(new PageImpl<>(skillModelList)); - - Pageable pageable = PageRequest.of(2, 1); - Page resultPage = skillService.getAllSkills(pageable); - assertNotNull(resultPage); - assertEquals( - skillModelList.size(), - resultPage.getTotalElements(), - "The number of elements returned is not equal to the expected size"); - assertEquals( - skillModelList.size(), - resultPage.getContent().size(), - "The content returned is not equal to the expected content"); - assertEquals( - "Java", - resultPage.getContent().get(0).getName(), - "The returned skill on page 0 doesn't match the actual skill"); - assertEquals( - "Go", - resultPage.getContent().get(1).getName(), - "The returned skill on page 0 doesn't match the actual skill"); - } -} diff --git a/skill-tree/src/test/java/com/RDS/skilltree/utils/UUIDValidationInterceptorTest.java b/skill-tree/src/test/java/com/RDS/skilltree/utils/UUIDValidationInterceptorTest.java index a02c5d16..f17e6cc1 100644 --- a/skill-tree/src/test/java/com/RDS/skilltree/utils/UUIDValidationInterceptorTest.java +++ b/skill-tree/src/test/java/com/RDS/skilltree/utils/UUIDValidationInterceptorTest.java @@ -1,9 +1,10 @@ package com.RDS.skilltree.utils; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; -import com.RDS.skilltree.Exceptions.InvalidParameterException; +import com.RDS.skilltree.exceptions.InvalidParameterException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.util.UUID;