From 4b8839ae8f34ee8d7ad9b80eb80b0a89bd3cd1da Mon Sep 17 00:00:00 2001
From: evilimkova <xvilimk@fi.muni.cz>
Date: Fri, 14 Apr 2023 10:50:12 +0200
Subject: [PATCH] Add OpenApi documentation for CertificateController, add
 ResponseEntity

---
 .../service/CertificateController.java        | 76 ++++++++++++++-----
 .../CertificateControllerTests.java           | 36 ++++-----
 2 files changed, 78 insertions(+), 34 deletions(-)

diff --git a/application/module-certificate/src/main/java/org/fuseri/modulecertificate/service/CertificateController.java b/application/module-certificate/src/main/java/org/fuseri/modulecertificate/service/CertificateController.java
index 38853d76..e63254df 100644
--- a/application/module-certificate/src/main/java/org/fuseri/modulecertificate/service/CertificateController.java
+++ b/application/module-certificate/src/main/java/org/fuseri/modulecertificate/service/CertificateController.java
@@ -1,14 +1,19 @@
 package org.fuseri.modulecertificate.service;
 
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.responses.ApiResponses;
+import jakarta.persistence.EntityNotFoundException;
 import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
 import org.fuseri.model.dto.certificate.CertificateCreateDto;
-import org.fuseri.model.dto.certificate.CertificateDto;
 import org.fuseri.model.dto.certificate.CertificateSimpleDto;
-import org.fuseri.model.dto.common.Result;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Pageable;
+import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.http.HttpStatus;
 
 import java.util.List;
 
@@ -35,9 +40,16 @@ public class CertificateController {
      * @param certificateCreateDto Dto with data used for generating certificate
      * @return CertificateDto with data of generated certificate
      */
-    @PostMapping("/generate")
-    public CertificateSimpleDto generate(@Valid @RequestBody CertificateCreateDto certificateCreateDto) {
-        return certificateFacade.generate(certificateCreateDto);
+    @Operation(summary = "Generate certificate",
+            description = "Generates certificate, saves it into database and returns certificate information and certificate file.")
+    @ApiResponses(value = {
+            @ApiResponse(responseCode = "201", description = "Certificate generated successfully."),
+            @ApiResponse(responseCode = "400", description = "Invalid input.")
+    })
+    @PostMapping
+    public ResponseEntity<CertificateSimpleDto> generate(@Valid @RequestBody CertificateCreateDto certificateCreateDto) {
+        var certificateSimpleDto = certificateFacade.generate(certificateCreateDto);
+        return ResponseEntity.status(HttpStatus.CREATED).body(certificateSimpleDto);
     }
 
     /**
@@ -46,9 +58,18 @@ public class CertificateController {
      * @param id ID of certificate to be retrieved
      * @return CertificateDto with data of previously generated certificate with specified ID
      */
-    @GetMapping("/find")
-    public CertificateSimpleDto find(@RequestParam Long id) {
-        return certificateFacade.findById(id);
+    @Operation(summary = "Get a certificate by ID", description = "Returns a certificate with the specified ID.")
+    @ApiResponses(value = {
+            @ApiResponse(responseCode = "200", description = "Certificate with the specified ID retrieved successfully."),
+            @ApiResponse(responseCode = "404", description = "Certificate with the specified ID was not found.")
+    })
+    @GetMapping("/{id}")
+    public ResponseEntity<CertificateSimpleDto> find(@NotNull @PathVariable  Long id) {
+        try {
+            return ResponseEntity.ok(certificateFacade.findById(id));
+        } catch (EntityNotFoundException e) {
+            return ResponseEntity.notFound().build();
+        }
     }
 
     /**
@@ -58,9 +79,14 @@ public class CertificateController {
      * @return List of CertificateDto objects with previously generated certificates
      * for specified User.
      */
+    @Operation(summary = "Get certificates for user", description = "Returns certificates for given user in list.")
+    @ApiResponses(value = {
+            @ApiResponse(responseCode = "200", description = "Successfully retrieved certificates"),
+            @ApiResponse(responseCode = "400", description = "Invalid input."),
+    })
     @GetMapping("/findForUser")
-    public List<CertificateSimpleDto> findForUser(@RequestParam Long userId) {
-        return certificateFacade.findByUserId(userId);
+    public ResponseEntity<List<CertificateSimpleDto>> findForUser(@RequestParam Long userId) {
+        return ResponseEntity.ok(certificateFacade.findByUserId(userId));
     }
 
     /**
@@ -71,9 +97,15 @@ public class CertificateController {
      * @return List of CertificateDto objects with previously generated certificates
      * for specified User and Course.
      */
+    @Operation(summary = "Get certificates for user and course",
+            description = "Returns certificates for given user and course in list.")
+    @ApiResponses(value = {
+            @ApiResponse(responseCode = "200", description = "Successfully retrieved certificates"),
+            @ApiResponse(responseCode = "400", description = "Invalid input."),
+    })
     @GetMapping("/findForUserAndCourse")
-    public List<CertificateSimpleDto> findForUserAndCourse(@RequestParam Long userId, @RequestParam Long courseId) {
-        return certificateFacade.findByUserIdAndCourseId(userId, courseId);
+    public ResponseEntity<List<CertificateSimpleDto>> findForUserAndCourse(@RequestParam Long userId, @RequestParam Long courseId) {
+        return  ResponseEntity.ok(certificateFacade.findByUserIdAndCourseId(userId, courseId));
     }
 
     /**
@@ -81,9 +113,14 @@ public class CertificateController {
      *
      * @param id Id of certificate to be deleted.
      */
-    @DeleteMapping("/delete")
-    public void delete(@RequestParam Long id) {
+    @Operation(summary = "Delete a certificate with specified ID", description = "Deletes a certificate with the specified ID.")
+    @ApiResponses(value = {
+            @ApiResponse(responseCode = "204", description = "Certificate with the specified ID deleted successfully."),
+    })
+    @DeleteMapping("/{id}")
+    public ResponseEntity<Void> delete(@NotNull @PathVariable Long id) {
         certificateFacade.deleteCertificate(id);
+        return ResponseEntity.noContent().build();
     }
 
     /**
@@ -91,8 +128,13 @@ public class CertificateController {
      *
      * @return a Result object containing a list of CertificateDto objects and pagination information
      */
-    @GetMapping("/findAll")
-    public Page<CertificateSimpleDto> findAllCertificates(Pageable pageable) {
-        return certificateFacade.findAll(pageable);
+    @Operation(summary = "Get certificates in paginated format", description = "Returns certificates in paginated format.")
+    @ApiResponses(value = {
+            @ApiResponse(responseCode = "200", description = "Successfully retrieved paginated certificates"),
+            @ApiResponse(responseCode = "400", description = "Invalid page number supplied"),
+    })
+    @GetMapping
+    public ResponseEntity<Page<CertificateSimpleDto>> findAllCertificates(Pageable pageable) {
+        return ResponseEntity.ok(certificateFacade.findAll(pageable));
     }
 }
diff --git a/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java b/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java
index 2e2e243a..105d07a0 100644
--- a/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java
+++ b/application/module-certificate/src/test/java/org/fuseri/modulecertificate/CertificateControllerTests.java
@@ -19,8 +19,10 @@ import org.springframework.boot.test.mock.mockito.MockBean;
 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.MediaType;
 import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.http.ResponseEntity;
 
 import java.time.Instant;
 import java.util.List;
@@ -56,12 +58,12 @@ class CertificateControllerTests {
     @Test
     void generateCertificate() throws Exception {
         Mockito.when(certificateController.generate(ArgumentMatchers.any(CertificateCreateDto.class)))
-                .thenReturn(certificateDto);
+                .thenReturn(ResponseEntity.status(HttpStatus.CREATED).body(certificateDto));
 
-        mockMvc.perform(post("/certificates/generate")
+        mockMvc.perform(post("/certificates")
                         .content(asJsonString(certificateCreateDto))
                         .contentType(MediaType.APPLICATION_JSON))
-                .andExpect(status().isOk())
+                .andExpect(status().is2xxSuccessful())
                 .andExpect(jsonPath("$.id").value(certificateDto.getId()))
                 .andExpect(jsonPath("$.userId").value(certificateDto.getUserId()))
                 .andExpect(jsonPath("$.generatedAt").value(certificateDto.getGeneratedAt().toString()))
@@ -96,22 +98,22 @@ class CertificateControllerTests {
 
     @Test
     void findCertificate() throws Exception {
-        Mockito.when(certificateController.find(ArgumentMatchers.anyLong())).thenReturn(certificateDto);
+        Mockito.when(certificateController.find(ArgumentMatchers.anyLong())).thenReturn(ResponseEntity.ok(certificateDto));
 
-        mockMvc.perform(get("/certificates/find").param("id", certificateDto.getId().toString()))
+        mockMvc.perform(get("/certificates/" + certificateDto.getId()))
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.id").value(certificateDto.getId()));
     }
 
     @Test
     void findCertificateWithoutId() throws Exception {
-        mockMvc.perform(get("/certificates/find"))
+        mockMvc.perform(get("/certificates/"))
                 .andExpect(status().is4xxClientError());
     }
 
     @Test
     void findCertificatesForUser() throws Exception {
-        Mockito.when(certificateController.findForUser(ArgumentMatchers.anyLong())).thenReturn(List.of(certificateDto));
+        Mockito.when(certificateController.findForUser(ArgumentMatchers.anyLong())).thenReturn(ResponseEntity.ok(List.of(certificateDto)));
 
         mockMvc.perform(get("/certificates/findForUser").param("userId", "0"))
                 .andExpect(status().isOk())
@@ -129,7 +131,7 @@ class CertificateControllerTests {
     void findCertificateIdForUserAndCourse() throws Exception {
         Mockito.when(certificateController.findForUserAndCourse(ArgumentMatchers.anyLong(),
                         ArgumentMatchers.anyLong()))
-                .thenReturn(List.of(certificateDto));
+                .thenReturn(ResponseEntity.ok(List.of(certificateDto)));
 
         mockMvc.perform(get("/certificates/findForUserAndCourse")
                         .param("userId", "0")
@@ -161,25 +163,25 @@ class CertificateControllerTests {
 
     @Test
     void deleteCertificate() throws Exception {
-        Mockito.doNothing().when(certificateController).delete(ArgumentMatchers.anyLong());
+        Mockito.when(certificateController.delete(ArgumentMatchers.anyLong())).
+                thenReturn(ResponseEntity.noContent().build());
 
-        mockMvc.perform(delete("/certificates/delete")
-                        .param("id", String.valueOf(0L)))
-                .andExpect(status().isOk());
+        mockMvc.perform(delete("/certificates/" + 0L))
+                .andExpect(status().is2xxSuccessful());
     }
 
     @Test
     void deleteCertificateWithoutParam() throws Exception {
-        mockMvc.perform(delete("/certificates/delete"))
+        mockMvc.perform(delete("/certificates/"))
                 .andExpect(status().is4xxClientError());
     }
 
     @Test
     void findAllCertificates() throws Exception {
         Mockito.when(certificateController.findAllCertificates(ArgumentMatchers.any(Pageable.class)))
-                .thenReturn(Page.empty(PageRequest.of(0, 1)));
+                .thenReturn(ResponseEntity.ok(Page.empty(PageRequest.of(0, 1))));
 
-        mockMvc.perform(get("/certificates/findAll")
+        mockMvc.perform(get("/certificates")
                         .param("page", "0")
                         .param("size", "10"))
                 .andExpect(status().isOk())
@@ -190,9 +192,9 @@ class CertificateControllerTests {
     @Test
     void findAllCertificatesWithoutParam() throws Exception {
         Mockito.when(certificateController.findAllCertificates(ArgumentMatchers.any(Pageable.class)))
-                .thenReturn(Page.empty(PageRequest.of(0, 1)));
+                .thenReturn(ResponseEntity.ok(Page.empty(PageRequest.of(0, 1))));
 
-        mockMvc.perform(get("/certificates/findAll"))
+        mockMvc.perform(get("/certificates"))
                 .andExpect(status().isOk())
                 .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                 .andExpect(jsonPath("$.content").isEmpty());
-- 
GitLab