Skip to content

Commit

Permalink
Clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitolo-Andrea committed Nov 8, 2024
1 parent 984f500 commit 68951fb
Show file tree
Hide file tree
Showing 7 changed files with 136 additions and 142 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public RuntimeException throwException(String exceptionKey, String message) {
if (exceptions.containsKey(exceptionKey)) {
return exceptions.get(exceptionKey).apply(message);
} else {
log.error("Exception Name Not Found: {}", exceptionKey);
log.error("[EMP-TPP][EXCEPTION-MAP] Exception Name Not Found: {}", exceptionKey);
return new RuntimeException();
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/main/java/it/gov/pagopa/tpp/controller/TppController.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
public interface TppController {

/**
* Get list of tpps
* Get list of tpp
*
* @param tppIdList whose data is to be retrieved
* @return outcome of retrieving the tpps
* @return outcome of retrieving the tpp
*/
@PostMapping("/list")
Mono<ResponseEntity<List<TppDTO>>> getEnabledList(@Valid @RequestBody TppIdList tppIdList);
Expand All @@ -41,10 +41,10 @@ public interface TppController {
Mono<ResponseEntity<TppDTO>> upsert(@Valid @RequestBody TppDTO tppDTO);

/**
* Save a tpp
* Get a tpp
*
* @param tppId to save
* @return outcome of saving the tpp
* @param tppId to get
* @return outcome of getting tpp
*/
@GetMapping("/{tppId}")
Mono<ResponseEntity<TppDTO>> get(@Valid @PathVariable String tppId);
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/it/gov/pagopa/tpp/dto/TppIdList.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package it.gov.pagopa.tpp.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class TppIdList {
List<String> ids;
}
77 changes: 40 additions & 37 deletions src/main/java/it/gov/pagopa/tpp/service/TppServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public class TppServiceImpl implements TppService {
private final TppDTOToObjectMapper mapperToObject;
private final ExceptionMap exceptionMap;

public TppServiceImpl(TppRepository tppRepository, TppObjectToDTOMapper mapperToDTO, TppDTOToObjectMapper mapperToObject, ExceptionMap exceptionMap) {
public TppServiceImpl(TppRepository tppRepository, TppObjectToDTOMapper mapperToDTO,
TppDTOToObjectMapper mapperToObject, ExceptionMap exceptionMap) {
this.tppRepository = tppRepository;
this.mapperToDTO = mapperToDTO;
this.mapperToObject = mapperToObject;
Expand All @@ -37,65 +38,67 @@ public TppServiceImpl(TppRepository tppRepository, TppObjectToDTOMapper mapperTo

@Override
public Mono<List<TppDTO>> getEnabledList(List<String> tppIdList) {
log.info("[EMD-TPP][GET-ENABLED] Received tppIdList: {}",(tppIdList));
log.info("[EMD-TPP][GET-ENABLED] Received tppIdList: {}", tppIdList);
return tppRepository.findByTppIdInAndStateTrue(tppIdList)
.collectList()
.map(tppList -> tppList.stream()
.map(mapperToDTO::map)
.toList()
)
.doOnSuccess(tppDTOList -> log.info("[EMD-TPP][GET-ENABLED] Tpps founded: {}",tppDTOList))
.doOnError(error -> log.error("[EMD-TPP][GET-ENABLED] Error: {}", error.getMessage()));
}

.toList())
.doOnSuccess(tppDTOList -> log.info("[EMD-TPP][GET-ENABLED] Found TPPs: {}", tppDTOList))
.doOnError(error -> log.error("[EMD-TPP][GET-ENABLED] Error: {}", error.getMessage()));
}

@Override
public Mono<TppDTO> upsert(TppDTO tppDTO) {
log.info("[EMD-TPP][UPSERT] Received tppDTO: {}", inputSanify(tppDTO.toString()));
Tpp tppReceived = mapperToObject.map(tppDTO);
log.info("[EMD-TPP][UPSERT] Received tppDTO: {}", inputSanify(tppDTO.toString()));
Tpp tppToSave = mapperToObject.map(tppDTO);

return tppRepository.findByTppId(tppDTO.getTppId())
.flatMap(tppDB -> {
log.info("[EMD-TPP][UPSERT] TPP with tppId:[{}] already exists",(tppDTO.getTppId()));
tppReceived.setId(tppDB.getId());
tppReceived.setLastUpdateDate(LocalDateTime.now());
return tppRepository.save(tppReceived)
.map(mapperToDTO::map)
.doOnSuccess(savedTpp -> log.info("[EMD-TPP][UPSERT] Updated existing TPP"));
.flatMap(existingTpp -> {
log.info("[EMD-TPP][UPSERT] TPP with tppId [{}] already exists", tppDTO.getTppId());
tppToSave.setId(existingTpp.getId());
tppToSave.setLastUpdateDate(LocalDateTime.now());
return saveTpp(tppToSave, "[EMD-TPP][UPSERT] Updated existing TPP ");
})
.switchIfEmpty(
Mono.defer(() -> {
tppReceived.setTppId("%s_%d".formatted(UUID.randomUUID().toString(), System.currentTimeMillis()));
tppReceived.setCreationDate(LocalDateTime.now());
tppReceived.setLastUpdateDate(LocalDateTime.now());
return tppRepository.save(tppReceived)
.map(mapperToDTO::map)
.doOnSuccess(savedTpp -> log.info("[EMD-TPP][UPSERT] Created TPP"));
})
);
.switchIfEmpty(Mono.defer(() -> {
tppToSave.setTppId(generateTppId());
tppToSave.setCreationDate(LocalDateTime.now());
tppToSave.setLastUpdateDate(LocalDateTime.now());
return saveTpp(tppToSave, "[EMD-TPP][UPSERT] Created new TPP");
}));
}

@Override
public Mono<TppDTO> updateState(String tppId, Boolean state) {
log.info("[EMD-TPP][UPDATE] Received tppId: {}",inputSanify(tppId));
log.info("[EMD-TPP][UPDATE-STATE] Received tppId: {}", inputSanify(tppId));
return tppRepository.findByTppId(tppId)
.switchIfEmpty(Mono.error(exceptionMap
.throwException(ExceptionName.TPP_NOT_ONBOARDED,"Tpp not founded during update state process")))
.switchIfEmpty(Mono.error(exceptionMap.throwException(ExceptionName.TPP_NOT_ONBOARDED,
"Tpp not found during state update process")))
.flatMap(tpp -> {
tpp.setState(state);
return tppRepository.save(tpp);
})
.map(mapperToDTO::map)
.doOnSuccess(updatedTpp -> log.info("[EMD][TPP][UPDATE-STATE] Updated"));
.doOnSuccess(updatedTpp -> log.info("[EMD-TPP][UPDATE-STATE] State updated for tppId: {}", tppId));
}


@Override
public Mono<TppDTO> get(String tppId) {
log.info("[EMD-TPP][GET] Received tppId: {}",inputSanify(tppId));
log.info("[EMD-TPP][GET] Received tppId: {}", inputSanify(tppId));
return tppRepository.findByTppId(tppId)
.switchIfEmpty(Mono.error(exceptionMap
.throwException(ExceptionName.TPP_NOT_ONBOARDED,"Tpp not founded during get process")))
.switchIfEmpty(Mono.error(exceptionMap.throwException(ExceptionName.TPP_NOT_ONBOARDED,
"Tpp not found during get process")))
.map(mapperToDTO::map)
.doOnSuccess(updatedTpp -> log.info("[EMD][TPP][GET] Founded"));
.doOnSuccess(tppDTO -> log.info("[EMD-TPP][GET] Found TPP with tppId: {}", tppId));
}

private Mono<TppDTO> saveTpp(Tpp tppToSave, String successLogMessage) {
return tppRepository.save(tppToSave)
.map(mapperToDTO::map)
.doOnSuccess(savedTpp -> log.info(successLogMessage));
}

private String generateTppId() {
return String.format("%s_%d", UUID.randomUUID(), System.currentTimeMillis());
}
}
}
57 changes: 20 additions & 37 deletions src/test/java/it/gov/pagopa/tpp/controller/TppControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@WebFluxTest(TppControllerImpl.class)
Expand All @@ -30,98 +29,82 @@ class TppControllerTest {
@Autowired
private ObjectMapper objectMapper;

private static final TppDTO MOCK_TPP_DTO = TppDTOFaker.mockInstance(true);

private static final List<TppDTO> MOCK_TPP_DTO_LIST = List.of(MOCK_TPP_DTO);
private static final TppIdList MOCK_TPP_ID_LIST = new TppIdList(List.of(MOCK_TPP_DTO.getTppId()));

@Test
void upsert_Ok() {
TppDTO mockTppDTO = TppDTOFaker.mockInstance(true);

Mockito.when(tppService.upsert(mockTppDTO)).thenReturn(Mono.just(mockTppDTO));
Mockito.when(tppService.upsert(MOCK_TPP_DTO)).thenReturn(Mono.just(MOCK_TPP_DTO));

webClient.post()
.uri("/emd/tpp")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(mockTppDTO)
.bodyValue(MOCK_TPP_DTO)
.exchange()
.expectStatus().isOk()
.expectBody(TppDTO.class)
.consumeWith(response -> {
TppDTO resultResponse = response.getResponseBody();
Assertions.assertNotNull(resultResponse);
Assertions.assertEquals(mockTppDTO, resultResponse);
Assertions.assertEquals(MOCK_TPP_DTO, resultResponse);
});
}

@Test
void stateUpdate_Ok() {
TppDTO mockTppDTO = TppDTOFaker.mockInstance(true);

Mockito.when(tppService.updateState(mockTppDTO.getTppId(), mockTppDTO.getState()))
.thenReturn(Mono.just(mockTppDTO));
Mockito.when(tppService.updateState(MOCK_TPP_DTO.getTppId(), MOCK_TPP_DTO.getState()))
.thenReturn(Mono.just(MOCK_TPP_DTO));

webClient.put()
.uri("/emd/tpp")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(mockTppDTO)
.bodyValue(MOCK_TPP_DTO)
.exchange()
.expectStatus().isOk()
.expectBody(TppDTO.class)
.consumeWith(response -> {
TppDTO resultResponse = response.getResponseBody();
Assertions.assertNotNull(resultResponse);
Assertions.assertEquals(resultResponse,mockTppDTO);
Assertions.assertEquals(MOCK_TPP_DTO,resultResponse);
});
}

@Test
void get_Ok() {
TppDTO mockTppDTO = TppDTOFaker.mockInstance(true);

Mockito.when(tppService.get(mockTppDTO.getTppId()))
.thenReturn(Mono.just(mockTppDTO));
Mockito.when(tppService.get(MOCK_TPP_DTO.getTppId()))
.thenReturn(Mono.just(MOCK_TPP_DTO));

webClient.get()
.uri("/emd/tpp/{tppId}",mockTppDTO.getTppId())
.uri("/emd/tpp/{tppId}",MOCK_TPP_DTO.getTppId())
.exchange()
.expectStatus().isOk()
.expectBody(TppDTO.class)
.consumeWith(response -> {
TppDTO resultResponse = response.getResponseBody();
Assertions.assertNotNull(resultResponse);
Assertions.assertEquals(resultResponse,mockTppDTO);
Assertions.assertEquals(MOCK_TPP_DTO,resultResponse);
});
}

@Test
void getEnabled_Ok() {
TppIdList tppIdList = new TppIdList();
ArrayList<String> tppIds = new ArrayList<>();
tppIds.add("1");
tppIds.add("2");
tppIds.add("3");
tppIdList.setIds(tppIds); // Using ArrayList


TppDTO tpp1 = new TppDTO();
TppDTO tpp2 = new TppDTO();


ArrayList<TppDTO> tppDTOList = new ArrayList<>();
tppDTOList.add(tpp1);
tppDTOList.add(tpp2);

Mockito.when(tppService.getEnabledList(tppIdList.getIds())).thenReturn(Mono.just(tppDTOList));
Mockito.when(tppService.getEnabledList(MOCK_TPP_ID_LIST.getIds())).thenReturn(Mono.just(MOCK_TPP_DTO_LIST));

webClient.post()
.uri("/emd/tpp/list")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(tppIdList) // Body of the request
.bodyValue(MOCK_TPP_ID_LIST) // Body of the request
.exchange()
.expectStatus().isOk()
.expectBodyList(TppDTO.class)
.consumeWith(response -> {
List<TppDTO> resultResponse = response.getResponseBody();
Assertions.assertNotNull(resultResponse);
Assertions.assertEquals(tppDTOList.size(), resultResponse.size());
Assertions.assertTrue(resultResponse.containsAll(tppDTOList));
Assertions.assertEquals(MOCK_TPP_DTO_LIST.size(), resultResponse.size());
Assertions.assertTrue(resultResponse.containsAll(MOCK_TPP_DTO_LIST));
});
}
}
22 changes: 22 additions & 0 deletions src/test/java/it/gov/pagopa/tpp/faker/TppFaker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package it.gov.pagopa.tpp.faker;

import it.gov.pagopa.tpp.enums.AuthenticationType;
import it.gov.pagopa.tpp.model.Contact;
import it.gov.pagopa.tpp.model.Tpp;

public class TppFaker {

private TppFaker(){}
public static Tpp mockInstance(Boolean bias){
return Tpp.builder()
.tppId("tppId")
.messageUrl("https://wwwmessageUrl.it")
.authenticationUrl("https://www.AuthenticationUrl.it")
.authenticationType(AuthenticationType.OAUTH2)
.state(bias)
.entityId("entityId01234567")
.businessName("businessName")
.contact(new Contact("name","number", "email"))
.build();
}
}
Loading

0 comments on commit 68951fb

Please sign in to comment.