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

chore: small code changes #396

Merged
merged 7 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,12 @@
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wiremock</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>3.9.1</version>
<scope>test</scope>
</dependency>

<!-- Documentation -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package ca.bc.gov.restapi.results.common.config;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/** This class holds properties used for the application configuration. */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ConstantsConfig {

public static final Integer MAX_PAGE_SIZE = 500;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package ca.bc.gov.restapi.results.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;

/**
* Configuration class for external API clients. This class is responsible for creating beans for
* the RestClient instances used to interact with external APIs.
*/
@Configuration
public class ExternalApiConfiguration {

/**
* Creates a RestClient bean for the Forest Client API.
*
* @param providersConfig the configuration properties for providers
* @return the configured RestClient instance for the Forest Client API
*/
@Bean
public RestClient forestClientApi(ProvidersConfig providersConfig) {
return RestClient
.builder()
.baseUrl(providersConfig.getForestClientBaseUri())
.defaultHeader("X-API-KEY", providersConfig.getForestClientApiKey())
.defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.build();
}

/**
* Creates a RestClient bean for the Open Maps API.
*
* @return the configured RestClient instance for the Open Maps API
*/
@Bean
public RestClient openMapsApi() {
return RestClient
.builder()
.baseUrl("https://openmaps.gov.bc.ca/geo/ows")
.defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,46 @@
import ca.bc.gov.restapi.results.common.enums.ForestClientStatusEnum;
import ca.bc.gov.restapi.results.common.enums.ForestClientTypeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.With;

/** This record represents a Forest Client object. */
/**
* This record represents a Forest Client object.
*/
@Schema(description = "One of the many agencies that work with the ministry.")
@Builder
@With
public record ForestClientDto(
@Schema(description = "An eight-digit number that identifies the client.", example = "00149081")
String clientNumber,
String clientNumber,
@Schema(
description =
"The client last name if it's an individual or the company name if it's a company.",
example = "WESTERN FOREST PRODUCTS INC.")
String clientName,
description =
"The client last name if it's an individual or the company name if it's a company.",
example = "WESTERN FOREST PRODUCTS INC.")
String clientName,
@Schema(
description = "The first name of the individual, or null if it's a company.",
example = "Maria")
String legalFirstName,
description = "The first name of the individual, or null if it's a company.",
example = "Maria")
String legalFirstName,
@Schema(
description = "The middle name of the individual, or null if it's a company",
example = "Bricks")
String legalMiddleName,
description = "The middle name of the individual, or null if it's a company",
example = "Bricks")
String legalMiddleName,
@Schema(
description =
"A code indicating the status of ministry client. Examples include but are not"
+ " limited to: Active, Deactivated, Deceased...",
example = "ACT")
ForestClientStatusEnum clientStatusCode,
description =
"A code indicating the status of ministry client. Examples include but are not"
+ " limited to: Active, Deactivated, Deceased...",
example = "ACT")
ForestClientStatusEnum clientStatusCode,
@Schema(
description =
"A code indicating a type of ministry client. Examples include but are not limited"
+ " to: Corporation, Individual, Association, First Nation..",
example = "C")
ForestClientTypeEnum clientTypeCode,
description =
"A code indicating a type of ministry client. Examples include but are not limited"
+ " to: Corporation, Individual, Association, First Nation..",
example = "C")
ForestClientTypeEnum clientTypeCode,
@Schema(
description = "An acronym for this client; works as an alternative identifier.",
example = "WFP")
String acronym) {}
description = "An acronym for this client; works as an alternative identifier.",
example = "WFP")
String acronym) {

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,21 @@
import ca.bc.gov.restapi.results.oracle.dto.DashboardResultsAuditDto;
import ca.bc.gov.restapi.results.oracle.dto.DashboardStockingEventDto;
import java.util.List;
import lombok.Builder;
import lombok.With;

/** This record holds all data extracted from Oracle to be inserted on Postgres. */
/**
* This record holds all data extracted from Oracle to be inserted on Postgres.
*/
@Builder
@With
public record OracleExtractionDto(
List<DashboardOpeningDto> mainOpenings,
List<DashboardOpeningSubmissionDto> openingSubmissions,
List<DashboardResultsAuditDto> resultsAudits,
List<DashboardStockingEventDto> stockingEvents,
List<DashboardOrgUnitDto> orgUnits,
List<DashboardActionCodeDto> actionCodes,
List<OracleLogDto> logMessages) {}
List<OracleLogDto> logMessages) {

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
package ca.bc.gov.restapi.results.common.dto;

/** This record represents the filters for the oracle extraction process. */
public record OracleExtractionParamsDto(Integer months, Boolean debug, Boolean manuallyTriggered) {}
import lombok.Builder;
import lombok.With;

/**
* This record represents the filters for the oracle extraction process.
*/
@Builder
@With
public record OracleExtractionParamsDto(Integer months, Boolean debug, Boolean manuallyTriggered) {

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
package ca.bc.gov.restapi.results.common.dto;

import java.time.LocalDateTime;
import lombok.Builder;
import lombok.With;

/** This record holds messages and its local date time when it happened. */
public record OracleLogDto(String message, LocalDateTime eventTime) {}
/**
* This record holds messages and its local date time when it happened.
*/
@Builder
@With
public record OracleLogDto(String message, LocalDateTime eventTime) {

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
package ca.bc.gov.restapi.results.common.dto;

/** This record represents a user in the whitelist. */
public record WmsLayersWhitelistUserDto(String userName) {}
import lombok.Builder;
import lombok.With;

/**
* This record represents a user in the whitelist.
*/
@Builder
@With
public record WmsLayersWhitelistUserDto(String userName) {

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** This class represents a pagination documentation. */
/**
* This class represents a pagination documentation.
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Parameter(
Expand All @@ -21,4 +23,6 @@
description = "The maximum number of results in a page.",
name = "perPage",
schema = @Schema(type = "integer", defaultValue = "5", minimum = "1"))
public @interface PaginatedViaQuery {}
public @interface PaginatedViaQuery {

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
/**
* Pagination parameters to be used in the processing of HTTP GET requests.
*
* @param page The page to be returned. Zero-based, and must be non-negative; defaults to 0
* @param page The page to be returned. Zero-based, and must be non-negative; defaults to 0
* @param perPage The maximum number of results in each page. Defaults to 20
*/
@Hidden
public record PaginationParameters(@PositiveOrZero Integer page, @Positive Integer perPage) {

/**
* Build an instance of {@link PaginationParameters}, using the default values for {@code page}
* and {@code perPage} if they're null.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,38 +1,26 @@
package ca.bc.gov.restapi.results.common.provider;

import ca.bc.gov.restapi.results.common.config.ProvidersConfig;
import ca.bc.gov.restapi.results.common.dto.ForestClientDto;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.RestClient;

/** This class contains methods to integrate SILVA REST API with ForestClient API. */
/**
* This class contains methods to integrate SILVA REST API with ForestClient API.
*/
@Slf4j
@Component
public class ForestClientApiProvider {

private final ProvidersConfig providersConfig;

private final RestTemplate restTemplate;

private final String rootUri;
private final RestClient restClient;

private static final String PROVIDER = "ForestClient API";

ForestClientApiProvider(ProvidersConfig providersConfig, RestTemplateBuilder templateBuilder) {
this.providersConfig = providersConfig;
this.restTemplate = templateBuilder.build();
this.rootUri = providersConfig.getForestClientBaseUri();
ForestClientApiProvider(@Qualifier("forestClientApi") RestClient forestClientApi) {
this.restClient = forestClientApi;
}

/**
Expand All @@ -42,46 +30,24 @@ public class ForestClientApiProvider {
* @return the ForestClient with client number, if one exists
*/
public Optional<ForestClientDto> fetchClientByNumber(String number) {
String apiUrl = String.format("%s/clients/findByClientNumber/{number}", rootUri);
log.info("Starting {} request to {}", PROVIDER, apiUrl);

log.info("Starting {} request to /clients/findByClientNumber/{number}", PROVIDER);

try {
ResponseEntity<ForestClientDto> response =
restTemplate.exchange(
apiUrl,
HttpMethod.GET,
new HttpEntity<>(addHttpHeaders()),
ForestClientDto.class,
createParamsMap("number", number));

log.info("Finished {} request for function {} - 200 OK!", PROVIDER, "fetchClientByNumber");
return Optional.of(response.getBody());
return
Optional
.ofNullable(
restClient
.get()
.uri("/clients/findByClientNumber/{number}", number)
.retrieve()
.body(ForestClientDto.class)
);
} catch (HttpClientErrorException httpExc) {
log.error("Finished {} request - Response code error: {}", PROVIDER, httpExc.getStatusCode());
}

return Optional.empty();
}

private String[] addAuthorizationHeader() {
String apiKey = this.providersConfig.getForestClientApiKey();
return new String[] {"X-API-KEY", apiKey};
}

private HttpHeaders addHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
String[] authorization = addAuthorizationHeader();
headers.set(authorization[0], authorization[1]);

return headers;
}

private Map<String, String> createParamsMap(String... values) {
Map<String, String> uriVars = new HashMap<>();
for (int i = 0; i < values.length; i += 2) {
uriVars.put(values[i], values[i + 1]);
}
return uriVars;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public Optional<ForestClientDto> getClientByNumber(String clientNumber) {
log.info("Received client number to fetch {}", clientNumber);

String fixedNumber = checkClientNumber(clientNumber);
if (!fixedNumber.equals("clientNumber")) {
if (!fixedNumber.equals(clientNumber)) {
log.info("Fixed client number to fetch {}", fixedNumber);
}

Expand Down
Loading
Loading