Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve apis logs #785

Merged
merged 12 commits into from
Jan 22, 2024
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package ca.bc.gov.backendstartapi.endpoint;

import ca.bc.gov.backendstartapi.config.SparLog;
import ca.bc.gov.backendstartapi.dto.DescribedEnumDto;
import ca.bc.gov.backendstartapi.enums.DescribedEnum;
import io.swagger.v3.oas.annotations.Operation;
Expand All @@ -9,6 +10,7 @@
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down Expand Up @@ -44,8 +46,11 @@ interface DescribedEnumEndpoint<E extends Enum<E> & DescribedEnum> {
description = "A list of all the codes and their descriptions.")
})
default ResponseEntity<List<DescribedEnumDto<E>>> fetchAll() {
String simpleName = enumClass().getSimpleName();
SparLog.info("Fetching all codes and descriptions for {} class", simpleName);
var valueDtos =
Arrays.stream(enumClass().getEnumConstants()).map(DescribedEnumDto::new).toList();
SparLog.info("{} records found for class {}", valueDtos.size(), simpleName);
return ResponseEntity.ok(valueDtos);
}

Expand All @@ -66,11 +71,22 @@ default ResponseEntity<List<DescribedEnumDto<E>>> fetchAll() {
})
default ResponseEntity<DescribedEnumDto<E>> fetch(
@Parameter(description = "The code to be fetched.") @PathVariable("code") String code) {
var valueDto =
SparLog.info(
"Fetching code and description from class {} with code {}",
enumClass().getSimpleName(),
code);
Optional<DescribedEnumDto<E>> valueDto =
Arrays.stream(enumClass().getEnumConstants())
.dropWhile(v -> !v.name().equals(code))
.findFirst()
.map(DescribedEnumDto::new);
String simpleName = enumClass().getSimpleName();
valueDto.ifPresent(
values ->
SparLog.info("Record for code {} found in class {}", code, simpleName));
if (valueDto.isEmpty()) {
SparLog.warn("Record for code {} not found in class {}", code, simpleName);
}
return ResponseEntity.of(valueDto);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
Expand All @@ -23,9 +24,7 @@
/** This class exposes resources to handle all genetic class codes. */
@RestController
@RequestMapping(path = "/api/genetic-classes", produces = "application/json")
@Tag(
name = "GeneticClasses",
description = "Resources to handle all genetic classes")
@Tag(name = "GeneticClasses", description = "Resources to handle all genetic classes")
public class GeneticClassEndpoint {

private GeneticClassService geneticClassService;
Expand Down Expand Up @@ -101,7 +100,9 @@ public CodeDescriptionDto getOrchardById(
@Parameter(
name = "code",
in = ParameterIn.PATH,
required = true,
description = "Identifier of the genetic class.")
@NonNull
String code) {
return geneticClassService.getGeneticClassByCode(code);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import jakarta.validation.Valid;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
Expand Down Expand Up @@ -107,8 +108,9 @@ public CodeDescriptionDto getGeneticWorthByCode(
@Parameter(
name = "code",
in = ParameterIn.PATH,
description = "Identifier of the genetic worth.")
String code) {
description = "Identifier of the genetic worth.",
required = true)
@NonNull String code) {
return geneticWorthService.getGeneticWorthByCode(code);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down Expand Up @@ -405,6 +406,7 @@ public ResponseEntity<Void> saveFormProgressClassA(
required = true,
schema = @Schema(type = "integer", format = "int64"))
@PathVariable
@NonNull
String seedlotNumber,
@RequestBody SaveSeedlotFormDtoClassA data) {

Expand Down Expand Up @@ -438,6 +440,7 @@ public SaveSeedlotFormDtoClassA getFormProgressClassA(
required = true,
schema = @Schema(type = "integer", format = "int64"))
@PathVariable
@NonNull
String seedlotNumber) {

return saveSeedlotFormService.getFormClassA(seedlotNumber);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,11 @@
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.With;

/** This class represents a user's favorite activity in the database. */
@Entity
@Getter
@Setter
@With
@AllArgsConstructor
@Table(name = "favourite_activity")
@Schema(description = "An object representing a user's favourite activity in the database")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
public class InvalidActivityException extends ResponseStatusException {

public InvalidActivityException() {
super(HttpStatus.NOT_FOUND, "Invalid activity or page name!");
super(HttpStatus.NOT_FOUND, "Invalid or not found activity id!");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
import org.springframework.web.server.ResponseStatusException;

/** This class represents a failed json parsing exception and will trigger a RuntimeException. */
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class JsonParsingException extends ResponseStatusException {

/** Constructor. */
public JsonParsingException() {
super(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to process requested JSON value.");
super(HttpStatus.BAD_REQUEST, "Failed to process requested JSON value.");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public List<CodeDescriptionDto> getAllConeCollectionMethods() {
resultList.add(methodToAdd);
});

SparLog.info("{} Cone Collection Methods found.", resultList.size());
return resultList;
}

Expand All @@ -43,6 +44,10 @@ public List<CodeDescriptionDto> getAllConeCollectionMethods() {
*/
public List<ConeCollectionMethodEntity> getAllValidConeCollectionMethods() {
SparLog.info("Fetching all Cone Collection Methods for ConeCollectionMethodEntity");
return coneCollectionMethodRepository.findAll().stream().filter(x -> x.isValid()).toList();

List<ConeCollectionMethodEntity> list =
coneCollectionMethodRepository.findAll().stream().filter(x -> x.isValid()).toList();
SparLog.info("{} Cone Collection Methods found.", list.size());
return list;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

/** This class contains all routines and database access to a users' favorite activity. */
Expand Down Expand Up @@ -58,7 +59,10 @@ public FavouriteActivityEntity createUserActivity(FavouriteActivityCreateDto act
FavouriteActivityEntity activityEntity = new FavouriteActivityEntity();
activityEntity.setUserId(userId);
activityEntity.setActivity(activityDto.activity());
return favouriteActivityRepository.save(activityEntity);

FavouriteActivityEntity activityEntitySaved = favouriteActivityRepository.save(activityEntity);
SparLog.info("Activity {} created for user {}", activityDto.activity(), userId);
return activityEntitySaved;
}

/**
Expand All @@ -69,7 +73,11 @@ public FavouriteActivityEntity createUserActivity(FavouriteActivityCreateDto act
public List<FavouriteActivityEntity> getAllUserFavoriteActivities() {
String userId = loggedUserService.getLoggedUserId();
SparLog.info("Retrieving all favorite activities for user {}", userId);
return favouriteActivityRepository.findAllByUserId(userId);

List<FavouriteActivityEntity> list = favouriteActivityRepository.findAllByUserId(userId);
SparLog.info("{} favourite activity(ies) for user {}", list.size(), userId);

return list;
}

/**
Expand All @@ -81,7 +89,8 @@ public List<FavouriteActivityEntity> getAllUserFavoriteActivities() {
* @throws InvalidActivityException if the activity doesn't exist
*/
@Transactional
public FavouriteActivityEntity updateUserActivity(Long id, FavouriteActivityUpdateDto updateDto) {
public FavouriteActivityEntity updateUserActivity(
@NonNull Long id, FavouriteActivityUpdateDto updateDto) {
String userId = loggedUserService.getLoggedUserId();

SparLog.info("Updating activity id {} for user {}", id, userId);
Expand All @@ -93,17 +102,20 @@ public FavouriteActivityEntity updateUserActivity(Long id, FavouriteActivityUpda
favouriteActivityRepository.removeAllHighlightedByUser(userId);
}

FavouriteActivityEntity entity = activityEntity.withHighlighted(updateDto.highlighted());
activityEntity.setHighlighted(updateDto.highlighted());

FavouriteActivityEntity activityEntitySaved = favouriteActivityRepository.save(activityEntity);
SparLog.info("Activity id {} updated for user {}", id, userId);

return favouriteActivityRepository.save(entity);
return activityEntitySaved;
}

/**
* Deletes a user activity by the activity id number.
*
* @param id A {@link Long} value as the id of the activity
*/
public void deleteUserActivity(Long id) {
public void deleteUserActivity(@NonNull Long id) {
String userId = loggedUserService.getLoggedUserId();

SparLog.info("Deleting activity id {} for user {}", id, userId);
Expand All @@ -113,5 +125,6 @@ public void deleteUserActivity(Long id) {
}

favouriteActivityRepository.deleteById(id);
SparLog.info("Activity id {} deleted for user {}", id, userId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public List<GameticMethodologyDto> getAllGameticMethodologies() {
resultList.add(methodToAdd);
});

SparLog.info("{} gametic methodologies found.", resultList.size());
return resultList;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

import ca.bc.gov.backendstartapi.config.SparLog;
import ca.bc.gov.backendstartapi.dto.CodeDescriptionDto;
import ca.bc.gov.backendstartapi.entity.GeneticClassEntity;
import ca.bc.gov.backendstartapi.exception.NoGeneticWorthException;
import ca.bc.gov.backendstartapi.repository.GeneticClassRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

/** This class contains all routines and database access to a list of genetic class. */
Expand All @@ -19,7 +22,7 @@ public GeneticClassService(GeneticClassRepository geneticClassRepository) {

/** Fetch all valid genetic class from the repository. */
public List<CodeDescriptionDto> getAllGeneticClass() {
SparLog.info("Fetching all genetic class");
SparLog.info("Fetching all genetic classes");
List<CodeDescriptionDto> resultList = new ArrayList<>();
geneticClassRepository.findAll().stream()
.filter(method -> method.isValid())
Expand All @@ -30,15 +33,18 @@ public List<CodeDescriptionDto> getAllGeneticClass() {
resultList.add(methodToAdd);
});

SparLog.info("{} genetic classes found.", resultList.size());
return resultList;
}

/** Fetch a single genetic class by code. */
public CodeDescriptionDto getGeneticClassByCode(String code) {
SparLog.info("Fetching genetic class with code {}", code);
public CodeDescriptionDto getGeneticClassByCode(@NonNull String code) {
SparLog.info("Fetching genetic class for code {}", code);

return geneticClassRepository
.findById(code)
Optional<GeneticClassEntity> gceOptional = geneticClassRepository.findById(code);
gceOptional.ifPresent(entity -> SparLog.info("Genetic class {} found.", code));

return gceOptional
.map(
entity -> new CodeDescriptionDto(entity.getGeneticClassCode(), entity.getDescription()))
.orElseThrow(NoGeneticWorthException::new);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import ca.bc.gov.backendstartapi.dto.GeneticWorthSummaryDto;
import ca.bc.gov.backendstartapi.dto.GeneticWorthTraitsDto;
import ca.bc.gov.backendstartapi.dto.GeneticWorthTraitsRequestDto;
import ca.bc.gov.backendstartapi.entity.GeneticWorthEntity;
import ca.bc.gov.backendstartapi.exception.NoGeneticWorthException;
import ca.bc.gov.backendstartapi.repository.GeneticWorthRepository;
import java.math.BigDecimal;
Expand All @@ -13,6 +14,7 @@
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

/** This class contains all routines and database access to a list of genetic worth. */
Expand All @@ -38,15 +40,18 @@ public List<CodeDescriptionDto> getAllGeneticWorth() {
resultList.add(methodToAdd);
});

SparLog.info("{} genetic worth found.", resultList.size());
return resultList;
}

/** Fetch a genetic worth from the repository by code. */
public CodeDescriptionDto getGeneticWorthByCode(String code) {
SparLog.info("Fetching genetic worth with code %s", code);
public CodeDescriptionDto getGeneticWorthByCode(@NonNull String code) {
SparLog.info("Fetching genetic worth with code {}", code);

return geneticWorthRepository
.findById(code)
Optional<GeneticWorthEntity> gweOptional = geneticWorthRepository.findById(code);
gweOptional.ifPresent(entity -> SparLog.info("Genetic worth {} found.", code));

return gweOptional
.map(
entity -> new CodeDescriptionDto(entity.getGeneticWorthCode(), entity.getDescription()))
.orElseThrow(NoGeneticWorthException::new);
Expand All @@ -62,7 +67,8 @@ public CodeDescriptionDto getGeneticWorthByCode(String code) {
*/
public GeneticWorthSummaryDto calculateGeneticWorth(
List<GeneticWorthTraitsRequestDto> traitsDto) {
BigDecimal minimumTreshold = new BigDecimal("0.7");
SparLog.info("Starting Genetic Worth calculations");
BigDecimal minimumThreshold = new BigDecimal("0.7");
BigDecimal neValue = calculateNe(traitsDto);

GeneticWorthSummaryDto summaryDto = new GeneticWorthSummaryDto(new ArrayList<>(), neValue);
Expand All @@ -74,9 +80,12 @@ public GeneticWorthSummaryDto calculateGeneticWorth(
BigDecimal calculatedValue = null;
BigDecimal percentage = checkGeneticTraitTreshold(traitsDto, trait);

if (percentage.compareTo(minimumTreshold) >= 0) {
if (percentage.compareTo(minimumThreshold) >= 0) {
SparLog.info("Calculating Genetic Worth for {} trait", trait.code());
calculatedValue = calculateTraitGeneticWorth(traitsDto, trait);
} else {
SparLog.info(
"No Genetic Worth calculations for trait {}, threshold not met.", trait.code());
}

GeneticWorthTraitsDto traitResponse =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public List<MethodOfPaymentDto> getAllMethodOfPayment() {
resultList.add(methodToAdd);
});

SparLog.info("{} valid payment method found for MethodOfPaymentDto.", resultList.size());
return resultList;
}

Expand All @@ -41,6 +42,11 @@ public List<MethodOfPaymentDto> getAllMethodOfPayment() {
*/
public List<MethodOfPaymentEntity> getAllValidMethodOfPayments() {
SparLog.info("Fetching all method of payment for MethodOfPaymentEntity");
return methodOfPaymentRepository.findAll().stream().filter(x -> x.isValid()).toList();

List<MethodOfPaymentEntity> list =
methodOfPaymentRepository.findAll().stream().filter(x -> x.isValid()).toList();
SparLog.info("{} valid payment method found for MethodOfPaymentEntity.", list.size());

return list;
}
}
Loading