Skip to content

Commit

Permalink
Merge pull request #148 from bcgov/feature/GRAD2-3037
Browse files Browse the repository at this point in the history
Feature/grad2 3037
  • Loading branch information
mightycox authored Dec 30, 2024
2 parents fc9ba9e + acf075c commit 18ba304
Show file tree
Hide file tree
Showing 22 changed files with 742 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,12 @@
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.context.annotation.Profile;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import reactor.netty.http.client.HttpClient;

@Profile("!test")
@Configuration
public class EducGradBusinessApiConfig implements WebMvcConfigurer {

Expand All @@ -30,21 +28,7 @@ public void addInterceptors(InterceptorRegistry registry) {

@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
return modelMapper;
}

@Bean
public WebClient webClient() {
HttpClient client = HttpClient.create();
client.warmup().block();
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(HttpClient.newConnection().compress(true)))
.exchangeStrategies(ExchangeStrategies.builder()
.codecs(configurer -> configurer
.defaultCodecs()
.maxInMemorySize(300 * 1024 * 1024))
.build()).build();
return new ModelMapper();
}

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package ca.bc.gov.educ.api.gradbusiness.config;

import ca.bc.gov.educ.api.gradbusiness.util.EducGradBusinessApiConstants;
import ca.bc.gov.educ.api.gradbusiness.util.LogHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
@Profile("!test")
public class RestWebClient {

EducGradBusinessApiConstants constants;

LogHelper logHelper;

@Autowired
public RestWebClient(EducGradBusinessApiConstants constants, LogHelper logHelper) {
this.constants = constants;
this.logHelper = logHelper;
}

@Bean("gradBusinessClient")
public WebClient getGraduationClientWebClient(OAuth2AuthorizedClientManager authorizedClientManager) {
ServletOAuth2AuthorizedClientExchangeFilterFunction filter = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
filter.setDefaultClientRegistrationId("grad-business-client");
return WebClient.builder()
.exchangeStrategies(ExchangeStrategies
.builder()
.codecs(codecs -> codecs
.defaultCodecs()
.maxInMemorySize(50 * 1024 * 1024))
.build())
.apply(filter.oauth2Configuration())
.filter(this.log())
.build();
}
@Bean
public OAuth2AuthorizedClientManager authorizedClientManager(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials()
.build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
return authorizedClientManager;
}

/**
* Old web client. You can use a @Qualifier('default') to summon it.
*/
@Bean
public WebClient webClient() {
return WebClient.builder().exchangeStrategies(ExchangeStrategies.builder()
.codecs(configurer -> configurer
.defaultCodecs()
.maxInMemorySize(300 * 1024 * 1024)) // 300MB
.build())
.filter(this.log())
.build();
}

private ExchangeFilterFunction log() {
return (clientRequest, next) -> next
.exchange(clientRequest)
.doOnNext((clientResponse -> LogHelper.logClientHttpReqResponseDetails(
clientRequest.method(),
clientRequest.url().toString(),
clientResponse.statusCode().value(),
clientRequest.headers().get(EducGradBusinessApiConstants.CORRELATION_ID),
constants.isSplunkLogHelperEnabled())
));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ public ResponseEntity<byte[]> certificateReportDataFromGraduation(@RequestBody S
@PreAuthorize("hasAuthority('SCOPE_GET_GRADUATION_DATA')")
@Operation(summary = "Get School Report pdf from graduation by mincode and report type", description = "Get School Report pdf from graduation by mincode and report type", tags = { "Graduation Data" })
@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "OK")})
public ResponseEntity<byte[]> schoolReportByMincode(@PathVariable String mincode,@RequestParam(name = "type") String type, @RequestHeader(name="Authorization") String accessToken) {
return gradBusinessService.getSchoolReportPDFByMincode(mincode, type, accessToken.replace(BEARER, ""));
public ResponseEntity<byte[]> schoolReportByMincode(@PathVariable String mincode,@RequestParam(name = "type") String type) {
return gradBusinessService.getSchoolReportPDFByMincode(mincode, type);
}

@GetMapping(EducGraduationApiConstants.STUDENT_CREDENTIAL_PDF)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ public ServiceException(String message, int value) {
this.statusCode = value;
}

public ServiceException(String s, int value, Exception e) {
super(s, e);
this.statusCode = value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package ca.bc.gov.educ.api.gradbusiness.model.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import org.springframework.stereotype.Component;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Component("instituteSchool")
@JsonIgnoreProperties(ignoreUnknown = true)
public class School {

private String schoolId;
private String districtId;
private String mincode;
private String independentAuthorityId;
private String schoolNumber;
private String faxNumber;
private String phoneNumber;
private String email;
private String website;
private String displayName;
private String displayNameNoSpecialChars;
private String schoolReportingRequirementCode;
private String schoolOrganizationCode;
private String schoolCategoryCode;
private String facilityTypeCode;
private String openedDate;
private String closedDate;
private boolean canIssueTranscripts;
private boolean canIssueCertificates;

}
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package ca.bc.gov.educ.api.gradbusiness.service;

import ca.bc.gov.educ.api.gradbusiness.exception.ServiceException;
import ca.bc.gov.educ.api.gradbusiness.model.dto.School;
import ca.bc.gov.educ.api.gradbusiness.model.dto.Student;
import ca.bc.gov.educ.api.gradbusiness.util.EducGradBusinessApiConstants;
import ca.bc.gov.educ.api.gradbusiness.util.EducGradBusinessUtil;
import ca.bc.gov.educ.api.gradbusiness.util.EducGraduationApiConstants;
import ca.bc.gov.educ.api.gradbusiness.util.TokenUtils;
import ca.bc.gov.educ.api.gradbusiness.util.*;
import io.github.resilience4j.retry.annotation.Retry;
import jakarta.transaction.Transactional;
import org.apache.commons.collections4.ListUtils;
Expand Down Expand Up @@ -63,17 +61,24 @@ public class GradBusinessService {
*/
final EducGraduationApiConstants educGraduationApiConstants;

final SchoolService schoolService;
final RESTService restService;
final JsonTransformer jsonTransformer;

/**
* Instantiates a new Grad business service.
*
* @param webClient the web client
*/
@Autowired
public GradBusinessService(WebClient webClient, TokenUtils tokenUtils, EducGradBusinessApiConstants educGradStudentApiConstants, EducGraduationApiConstants educGraduationApiConstants) {
public GradBusinessService(WebClient webClient, TokenUtils tokenUtils, EducGradBusinessApiConstants educGradStudentApiConstants, EducGraduationApiConstants educGraduationApiConstants, SchoolService schoolService, RESTService restService, JsonTransformer jsonTransformer) {
this.webClient = webClient;
this.tokenUtils = tokenUtils;
this.educGradStudentApiConstants = educGradStudentApiConstants;
this.educGraduationApiConstants = educGraduationApiConstants;
this.schoolService = schoolService;
this.restService = restService;
this.jsonTransformer = jsonTransformer;
}

/**
Expand Down Expand Up @@ -179,22 +184,26 @@ public ResponseEntity<byte[]> getStudentDemographicsByPen(String pen, String acc
}
}

public ResponseEntity<byte[]> getSchoolReportPDFByMincode(String mincode, String type, String accessToken) {
public ResponseEntity<byte[]> getSchoolReportPDFByMincode(String mincode, String type) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("PST"), Locale.CANADA);
int year = cal.get(Calendar.YEAR);
String month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
try {
HttpHeaders headers = new HttpHeaders();
headers.put(HttpHeaders.AUTHORIZATION, Collections.singletonList(BEARER + accessToken));
headers.put(HttpHeaders.ACCEPT, Collections.singletonList(APPLICATION_PDF));
headers.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(APPLICATION_PDF));
InputStreamResource result = webClient.get().uri(String.format(educGraduationApiConstants.getSchoolReportByMincode(), mincode,type)).headers(h -> h.setBearerAuth(accessToken)).retrieve().bodyToMono(InputStreamResource.class).block();
byte[] res = new byte[0];
if(result != null) {
res = result.getInputStream().readAllBytes();
List<School> schoolDetails = schoolService.getSchoolDetails(mincode);
if (schoolDetails.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
String schoolOfRecordId = schoolDetails.get(0).getSchoolId();

var result = restService.get(String.format(educGraduationApiConstants.getSchoolReportBySchoolIdAndReportType(), schoolOfRecordId,type), InputStreamResource.class);
byte[] response = new byte[0];
if (result != null) {
response = result.getInputStream().readAllBytes();
}
return handleBinaryResponse(res, EducGradBusinessUtil.getFileNameSchoolReports(mincode,year,month,type,MediaType.APPLICATION_PDF), MediaType.APPLICATION_PDF);

return handleBinaryResponse(response, EducGradBusinessUtil.getFileNameSchoolReports(mincode,year,month,type,MediaType.APPLICATION_PDF), MediaType.APPLICATION_PDF);
} catch (Exception e) {
logger.error("Error getting school report PDF by mincode: {}", e.getMessage());
return getInternalServerErrorResponse(e);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package ca.bc.gov.educ.api.gradbusiness.service;

import ca.bc.gov.educ.api.gradbusiness.exception.ServiceException;
import ca.bc.gov.educ.api.gradbusiness.util.EducGradBusinessApiConstants;
import ca.bc.gov.educ.api.gradbusiness.util.ThreadLocalStateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;

import java.time.Duration;

@Service
public class RESTService {
private final WebClient graduationServiceWebClient;

private static final String SERVER_ERROR = "5xx error.";
private static final String SERVICE_FAILED_ERROR = "Service failed to process after max retries.";

@Autowired
public RESTService(@Qualifier("gradBusinessClient") WebClient graduationServiceWebClient) {
this.graduationServiceWebClient = graduationServiceWebClient;
}

public <T> T get(String url, Class<T> clazz) {
T obj;
try {
obj = graduationServiceWebClient
.get()
.uri(url)
.headers(h -> h.set(EducGradBusinessApiConstants.CORRELATION_ID, ThreadLocalStateUtil.getCorrelationID()))
.retrieve()
// if 5xx errors, throw Service error
.onStatus(HttpStatusCode::is5xxServerError,
clientResponse -> Mono.error(new ServiceException(getErrorMessage(url, SERVER_ERROR), clientResponse.statusCode().value())))
.bodyToMono(clazz)
// only does retry if initial error was 5xx as service may be temporarily down
// 4xx errors will always happen if 404, 401, 403 etc, so does not retry
.retryWhen(Retry.backoff(3, Duration.ofSeconds(2))
.filter(ServiceException.class::isInstance)
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> {
throw new ServiceException(getErrorMessage(url, SERVICE_FAILED_ERROR), HttpStatus.SERVICE_UNAVAILABLE.value());
}))
.block();
} catch (Exception e) {
// catches IOExceptions and the like
throw new ServiceException(
getErrorMessage(url, e.getLocalizedMessage()),
(e instanceof WebClientResponseException exception) ? exception.getStatusCode().value() : HttpStatus.SERVICE_UNAVAILABLE.value(),
e);
}
return obj;
}

public <T> T post(String url, Object body, Class<T> clazz) {
T obj;
try {
obj = graduationServiceWebClient.post()
.uri(url)
.headers(h -> h.set(EducGradBusinessApiConstants.CORRELATION_ID, ThreadLocalStateUtil.getCorrelationID()))
.body(BodyInserters.fromValue(body))
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError,
clientResponse -> Mono.error(new ServiceException(getErrorMessage(url, SERVER_ERROR), clientResponse.statusCode().value())))
.bodyToMono(clazz)
.retryWhen(Retry.backoff(3, Duration.ofSeconds(2))
.filter(ServiceException.class::isInstance)
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> {
throw new ServiceException(getErrorMessage(url, SERVICE_FAILED_ERROR), HttpStatus.SERVICE_UNAVAILABLE.value());
}))
.block();
} catch (Exception e) {
throw new ServiceException(getErrorMessage(url, e.getLocalizedMessage()), HttpStatus.SERVICE_UNAVAILABLE.value(), e);
}
return obj;
}

private String getErrorMessage(String url, String errorMessage) {
return "Service failed to process at url: " + url + " due to: " + errorMessage;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ca.bc.gov.educ.api.gradbusiness.service;

import ca.bc.gov.educ.api.gradbusiness.model.dto.School;
import ca.bc.gov.educ.api.gradbusiness.util.EducGradBusinessApiConstants;
import ca.bc.gov.educ.api.gradbusiness.util.JsonTransformer;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SchoolService {
EducGradBusinessApiConstants educGraduationApiConstants;
RESTService restService;

JsonTransformer jsonTransformer;
@Autowired
public SchoolService(EducGradBusinessApiConstants educGraduationApiConstants, RESTService restService, JsonTransformer jsonTransformer) {
this.educGraduationApiConstants = educGraduationApiConstants;
this.restService = restService;
this.jsonTransformer = jsonTransformer;
}

public List<School> getSchoolDetails(String mincode) {
var response = this.restService.get(String.format(educGraduationApiConstants.getSchoolDetails(),mincode), List.class);
return jsonTransformer.convertValue(response, new TypeReference<>() {});
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ public class EducGradBusinessApiConstants {
@Value("${endpoint.grad-student-api.amalgamated-students.url}")
private String studentsForAmalgamatedReport;

@Value("${endpoint.grad-trax-api.search-schools-by-min-code.url}")
private String schoolDetails;

// Splunk LogHelper Enabled
@Value("${splunk.log-helper.enabled}")
private boolean splunkLogHelperEnabled;
Expand Down
Loading

0 comments on commit 18ba304

Please sign in to comment.