From 6923f13393d81e0a763935a8805145f048adfa14 Mon Sep 17 00:00:00 2001 From: "fabio.d.mota" Date: Mon, 26 Jun 2023 14:43:59 +0100 Subject: [PATCH 1/6] feat(Country Risk): Add project name to sonar cloud properties --- .github/workflows/sonar-scan.yml | 1 + CHANGELOG.md | 3 +++ pom.xml | 3 ++- sonar-project.properties | 3 ++- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sonar-scan.yml b/.github/workflows/sonar-scan.yml index a7b73bf8..e5605321 100644 --- a/.github/workflows/sonar-scan.yml +++ b/.github/workflows/sonar-scan.yml @@ -11,6 +11,7 @@ on: secrets: SONAR_TOKEN: required: true + workflow_dispatch: env: JAVA_VERSION: 17 diff --git a/CHANGELOG.md b/CHANGELOG.md index 92eea844..3482c744 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.1.2] - tbd +- Add project name to sonar cloud properties + ## [1.1.1] - 2023-05-16 ### Fixes diff --git a/pom.xml b/pom.xml index 5f37efa2..d5e1d663 100644 --- a/pom.xml +++ b/pom.xml @@ -31,7 +31,7 @@ org.eclipse.tractusx value-added-service 1.1.1 - value-added-service + tx-vas-country-risk-backend Project to Validate Country Risks Score 17 @@ -49,6 +49,7 @@ ${project.reporting.outputDirectory}/target/jacoco-report/jacoco.xml catenax-ng catenax-ng_tx-vas-country-risk-backend + tx-vas-country-risk-backend src/main/java/org/eclipse/tractusx/valueaddedservice/dto//.,src/main/java/org/eclipse/tractusx/valueaddedservice/domain//.¨ 0.8.7 2.5.1.0 diff --git a/sonar-project.properties b/sonar-project.properties index 8e297e75..17e4429a 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -4,4 +4,5 @@ sonar.tests=src/test/ sonar.coverage.jacoco.xmlReportPaths=target/site/**/jacoco*.xml sonar.java.codeCoveragePlugin=jacoco sonar.junit.reportPaths=target/surefire-reports,target/failsafe-reports -sonar.coverage.exclusions=src/main/java/com/catenax/valueaddedservice/dto/**/*.*,src/main/java/com/catenax/valueaddedservice/domain/**/*.* \ No newline at end of file +sonar.coverage.exclusions=src/main/java/com/catenax/valueaddedservice/dto/**/*.*,src/main/java/com/catenax/valueaddedservice/domain/**/*.* +sonar.projectName=tx-vas-country-risk-backend From 5577aef503561ca18f375e956947d30b7415f9c0 Mon Sep 17 00:00:00 2001 From: "fabio.d.mota" Date: Fri, 30 Jun 2023 14:15:31 +0100 Subject: [PATCH 2/6] feat(Country Risk): Add roles to JWT token claims - Updated the JWT token generation method to include user roles in the token claims. - Roles are now available in the token payload and can be used for role-based access control on the frontend. --- CHANGELOG.md | 8 ++- DEPENDENCIES | 2 +- pom.xml | 4 +- .../config/ApplicationVariables.java | 2 +- .../constants/VasConstants.java | 3 +- .../dto/BusinessPartnerDTO.java | 6 +++ .../dto/DashBoardTableDTO.java | 6 +++ .../service/DashboardService.java | 21 ++++++-- .../service/logic/CountryLogicService.java | 19 ++++--- .../ExternalBusinessPartnersLogicService.java | 52 ++++++++++++++----- .../service/logic/ShareLogicService.java | 5 +- .../logic/WorldMapAndTableLogicService.java | 8 +-- .../resources/config/application-local.yml | 5 +- .../config/liquibase/fake-data/dashboard.json | 34 ++++++------ .../rest/BPNIntegartionTest.java | 34 ++++++++++-- .../DashBoardResourceIntegrationTest.java | 28 +++++++++- .../rest/RangeIntegartionTest.java | 2 +- .../rest/RatingApiIntegrationTest.java | 28 +++++++++- .../rest/ReportApiIntegrationTest.java | 2 +- .../UploadAndDownloadApiIntegrationTest.java | 2 +- .../logic/CountryLogicServiceTest.java | 39 ++++++++++---- 21 files changed, 234 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3482c744..977f6e3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.1.2] - tbd +## [1.2.0] - tbd + +### Added - Add project name to sonar cloud properties +- Added Suppliers and Customers fields for logic filtering + +### Changed +- Map Between API and New Data Model for getting Suppliers and Customers ## [1.1.1] - 2023-05-16 diff --git a/DEPENDENCIES b/DEPENDENCIES index 16f71695..dadc7a28 100644 --- a/DEPENDENCIES +++ b/DEPENDENCIES @@ -4,7 +4,7 @@ maven/mavencentral/com.fasterxml.jackson.core/jackson-annotations/2.14.2, Apache maven/mavencentral/com.fasterxml.jackson.core/jackson-core/2.14.2, Apache-2.0 AND MIT, approved, #4303 maven/mavencentral/com.fasterxml.jackson.core/jackson-databind/2.13.4.2, Apache-2.0, approved, #2134 maven/mavencentral/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml/2.14.2, Apache-2.0, approved, #5933 -maven/mavencentral/com.fasterxml.jackson.datatype/jackson-datatype-jdk8/2.14.2, Apache-2.0, approved, clearlydefined +maven/mavencentral/com.fasterxml.jackson.datatype/jackson-datatype-jdk8/2.14.2, Apache-2.0, approved, #8597 maven/mavencentral/com.fasterxml.jackson.datatype/jackson-datatype-jsr310/2.14.2, Apache-2.0, approved, #4699 maven/mavencentral/com.fasterxml.jackson.module/jackson-module-parameter-names/2.14.2, Apache-2.0, approved, #5938 maven/mavencentral/com.fasterxml/classmate/1.5.1, Apache-2.0, approved, clearlydefined diff --git a/pom.xml b/pom.xml index d5e1d663..313b212d 100644 --- a/pom.xml +++ b/pom.xml @@ -30,8 +30,8 @@ org.eclipse.tractusx value-added-service - 1.1.1 - tx-vas-country-risk-backend + 1.2.0 + vas-country-risk-backend Project to Validate Country Risks Score 17 diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java index 2ca000e7..7e8e29b9 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java @@ -33,7 +33,7 @@ public class ApplicationVariables { private String token; - private AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); + private AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); public String getToken() { return token; diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/constants/VasConstants.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/constants/VasConstants.java index e5049bdf..8298dec7 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/constants/VasConstants.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/constants/VasConstants.java @@ -55,7 +55,8 @@ private VasConstants() { public static final String CSV_ROLE_TYPE_COMPANY = "Company"; public static final String CSV_ROLE_COMPANY_ADMIN = "Company Admin"; - + public static final String CSV_ROLE_READ_SUPPLIER = "read_suppliers"; + public static final String CSV_ROLE_READ_CUSTOMER = "read_customers"; public static final String REQUEST_COMPANY_NAME = "companyName"; diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/BusinessPartnerDTO.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/BusinessPartnerDTO.java index d5f37265..c905a7ee 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/BusinessPartnerDTO.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/BusinessPartnerDTO.java @@ -63,6 +63,12 @@ public class BusinessPartnerDTO implements Serializable { @Schema(example = "-6.6889038") private String latitude; + @Schema(example = "false") + private Boolean supplier = false; + + @Schema(example = "true") + private Boolean customer = false; + public BusinessPartnerDTO(String json) { try { diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/DashBoardTableDTO.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/DashBoardTableDTO.java index 0495b510..02352f69 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/DashBoardTableDTO.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/DashBoardTableDTO.java @@ -67,4 +67,10 @@ public class DashBoardTableDTO implements Serializable { @Schema(example = "-6.6889038") private String latitude; + @Schema(example = "false") + private Boolean supplier; + + @Schema(example = "true") + private Boolean customer; + } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java index ab0e6a20..ba43bca6 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java @@ -20,6 +20,7 @@ package org.eclipse.tractusx.valueaddedservice.service; import lombok.extern.slf4j.Slf4j; +import org.eclipse.tractusx.valueaddedservice.config.ApplicationVariables; import org.eclipse.tractusx.valueaddedservice.domain.DataSource; import org.eclipse.tractusx.valueaddedservice.dto.*; import org.eclipse.tractusx.valueaddedservice.dto.ShareDTOs.ShareDTO; @@ -72,8 +73,12 @@ public class DashboardService { @Autowired ShareLogicService shareLogicService; + @Autowired + ApplicationVariables applicationVariables; + public List getTableInfo(Integer year, List ratingDTOList, CompanyUserDTO companyUser) { - return worldMapAndTableLogicService.getTableInfo(year, ratingDTOList, companyUser); + return worldMapAndTableLogicService.getTableInfo(year, ratingDTOList, companyUser,applicationVariables.getToken(), + applicationVariables.getAuthPropertiesDTO().getRoles(applicationVariables.getAuthPropertiesDTO().getClientResource())); } public List getWorldMapInfo(Integer year, List ratingDTOList, CompanyUserDTO companyUser) { @@ -112,16 +117,21 @@ public List getUserRangesOrDefault(CompanyUserDTO companyUser) { } public List getCountryFilterByISO2(CompanyUserDTO companyUserDTO) { - return countryLogicService.getCountryFilterByISO2(companyUserDTO); + return countryLogicService.getCountryFilterByISO2(companyUserDTO, + applicationVariables.getToken(), + applicationVariables.getAuthPropertiesDTO().getRoles(applicationVariables.getAuthPropertiesDTO().getClientResource())); } public List getExternalBusinessPartners(CompanyUserDTO companyUserDTO) { - return externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUserDTO); + return externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUserDTO,applicationVariables.getToken(), + applicationVariables.getAuthPropertiesDTO().getRoles(applicationVariables.getAuthPropertiesDTO().getClientResource())); } public List getCountryByAssociatedBPtoUser(CompanyUserDTO companyUserDTO) { - return countryLogicService.getAssociatedCountries(companyUserDTO); + return countryLogicService.getAssociatedCountries(companyUserDTO, + applicationVariables.getToken(), + applicationVariables.getAuthPropertiesDTO().getRoles(applicationVariables.getAuthPropertiesDTO().getClientResource())); } public List getReportsByCompanyUser(CompanyUserDTO companyUserDTO) { @@ -162,7 +172,8 @@ public List findRatingsByYearAndCompanyUserCompany(Integer year, } public List findRatingsScoresForEachBpn(List datasource, List businessPartner, CompanyUserDTO companyUser) { - return shareLogicService.findRatingsScoresForEachBpn(datasource, businessPartner ,companyUser); + return shareLogicService.findRatingsScoresForEachBpn(datasource, businessPartner ,companyUser,applicationVariables.getToken(), + applicationVariables.getAuthPropertiesDTO().getRoles(applicationVariables.getAuthPropertiesDTO().getClientResource())); } public void deleteReportFromUserById(Long reportId,CompanyUserDTO companyUserDTO) { diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java index d8deab0d..60ef5f23 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java @@ -31,7 +31,6 @@ import java.util.List; import java.util.Optional; -import java.util.stream.Collectors; @Service @Slf4j @@ -46,11 +45,11 @@ public class CountryLogicService { ExternalBusinessPartnersLogicService externalBusinessPartnersLogicService; - @Cacheable(value = "vas-country", key = "{#root.methodName , {#companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName}}", unless = "#result == null") - public List getAssociatedCountries (CompanyUserDTO companyUserDTO) { + @Cacheable(value = "vas-country", key = "{#root.methodName , {#companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName},#roles }", unless = "#result == null") + public List getAssociatedCountries (CompanyUserDTO companyUserDTO,String token,List roles) { log.debug("getAssociatedCountries filtered by companyUserDTO " + companyUserDTO); List countryList; - countryList = externalBusinessPartnersLogicService.getExternalPartnersCountry(companyUserDTO); + countryList = externalBusinessPartnersLogicService.getExternalPartnersCountry(companyUserDTO,token,roles); List countryDTOS; countryDTOS = countryService.findByCountryIn(countryList); @@ -60,11 +59,11 @@ public List getAssociatedCountries (CompanyUserDTO companyUserDTO) { - @Cacheable(value = "vas-country", key = "{#root.methodName , {#companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName}}", unless = "#result == null") - public List getCountryFilterByISO2(CompanyUserDTO companyUserDTO){ + @Cacheable(value = "vas-country", key = "{#root.methodName , {#companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName},#roles}", unless = "#result == null") + public List getCountryFilterByISO2(CompanyUserDTO companyUserDTO,String token,List roles){ log.debug("getCountryFilterByISO2 filtered by companyUserDTO "+ companyUserDTO); - List countryDTOList = countryService.findAll().stream().filter(MethodUtils.distinctByKey(CountryDTO::getIso2)).collect(Collectors.toList()); - countryDTOList.forEach(countryDTO -> countryDTO.setTotalBpn(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO,companyUserDTO))); + List countryDTOList = countryService.findAll().stream().filter(MethodUtils.distinctByKey(CountryDTO::getIso2)).toList(); + countryDTOList.forEach(countryDTO -> countryDTO.setTotalBpn(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO,companyUserDTO,token,roles))); return countryDTOList; } @@ -73,11 +72,11 @@ public List getCountryFilterByISO2(CompanyUserDTO companyUserDTO){ @Cacheable(value = "vas-country", key = "{#root.methodName , #countryName}", unless = "#result == null") public CountryDTO findCountryByName(String countryName){ Optional countryDTO = countryService.findCountryByName(countryName); - log.debug("findCountryByName filtered by countryName " + countryName); + log.debug("findCountryByName filtered by countryName {}", countryName); if(countryDTO.isPresent()){ return countryDTO.get(); }else{ - log.error("Country does not exists on country table " + countryName); + log.error("Country does not exists on country table {}", countryName); return new CountryDTO(); } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java index 95eb5aae..a442d731 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java @@ -41,6 +41,9 @@ import java.util.List; import java.util.stream.Collectors; +import static org.eclipse.tractusx.valueaddedservice.constants.VasConstants.CSV_ROLE_READ_CUSTOMER; +import static org.eclipse.tractusx.valueaddedservice.constants.VasConstants.CSV_ROLE_READ_SUPPLIER; + @Service @Slf4j public class ExternalBusinessPartnersLogicService { @@ -57,30 +60,51 @@ public class ExternalBusinessPartnersLogicService { @Autowired ApplicationVariables applicationVariables; - @Autowired - InvokeService invokeService; - - - @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#companyUser.name,#companyUser.email,#companyUser.companyName}}", unless = "#result == null") - public List getExternalBusinessPartners(CompanyUserDTO companyUser) { + @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#companyUser.name,#companyUser.email,#companyUser.companyName}, #roles}", unless = "#result == null") + public List getExternalBusinessPartners(CompanyUserDTO companyUser,String token, List roles) { log.debug("getExternalBusinessPartners for companyUserDTO {}",companyUser); try { var headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); - headers.setBearerAuth(applicationVariables.getToken()); + headers.setBearerAuth(token); HttpEntity httpEntity = new HttpEntity<>(headers); - return objectMapper.readValue(json.getInputStream(), new TypeReference<>() { + List businessPartnerDTOS = objectMapper.readValue(json.getInputStream(), new TypeReference<>() { }); + + + List filteredBusinessPartnerDTOS; + + if (roles.contains(CSV_ROLE_READ_SUPPLIER) && roles.contains(CSV_ROLE_READ_CUSTOMER)) { + // User has both roles, no need to filter + filteredBusinessPartnerDTOS = businessPartnerDTOS; + } else if (roles.contains(CSV_ROLE_READ_SUPPLIER)) { + // User can only read suppliers and those who are not customers + filteredBusinessPartnerDTOS = businessPartnerDTOS.stream() + .filter(bpn -> bpn.getSupplier() || !bpn.getCustomer()) + .toList(); + } else if (roles.contains(CSV_ROLE_READ_CUSTOMER)) { + // User can only read customers and those who are not suppliers + filteredBusinessPartnerDTOS = businessPartnerDTOS.stream() + .filter(bpn -> bpn.getCustomer() || !bpn.getSupplier()) + .toList(); + } else { + // User has neither role, can only see those who are neither suppliers nor customers + filteredBusinessPartnerDTOS = businessPartnerDTOS.stream() + .filter(bpn -> !bpn.getSupplier() && !bpn.getCustomer()) + .toList(); + } + return filteredBusinessPartnerDTOS; } catch (IOException e) { throw new RuntimeException(e); } } + - @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName}}", unless = "#result == null") - public List getExternalPartnersCountry (CompanyUserDTO companyUserDTO) { + @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName},#roles}", unless = "#result == null") + public List getExternalPartnersCountry (CompanyUserDTO companyUserDTO,String token,List roles) { log.debug("getExternalPartnersCountry for companyUserDTO {}",companyUserDTO); List businessPartnerDTOS; - businessPartnerDTOS = getExternalBusinessPartners(companyUserDTO); + businessPartnerDTOS = getExternalBusinessPartners(companyUserDTO,token,roles); List countryList = new ArrayList<>(); countryList.addAll(businessPartnerDTOS.stream().map(BusinessPartnerDTO::getCountry) .collect(Collectors.toSet())); @@ -88,10 +112,10 @@ public List getExternalPartnersCountry (CompanyUserDTO companyUserDTO) { } - @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#countryDTO.iso3, #companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName}}", unless = "#result == null") - public Long getTotalBpnByCountry(CountryDTO countryDTO,CompanyUserDTO companyUserDTO){ + @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#countryDTO.iso3, #companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName},#roles}", unless = "#result == null") + public Long getTotalBpnByCountry(CountryDTO countryDTO,CompanyUserDTO companyUserDTO,String token,List roles){ log.debug("getTotalBpnByCountry filtered by country {} and companyUser {}",countryDTO,companyUserDTO); - List businessPartnerDTOS = getExternalBusinessPartners(companyUserDTO); + List businessPartnerDTOS = getExternalBusinessPartners(companyUserDTO,token,roles); return businessPartnerDTOS.stream().filter(businessPartnerDTO -> businessPartnerDTO.getCountry().equalsIgnoreCase(countryDTO.getCountry())).count(); } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java index 3edb1f26..b860d29c 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java @@ -45,12 +45,13 @@ public class ShareLogicService { @Autowired ExternalBusinessPartnersLogicService externalBusinessPartnersLogicService; - public List findRatingsScoresForEachBpn(List datasource, List businessPartnerToMap, CompanyUserDTO companyUser) { + public List findRatingsScoresForEachBpn(List datasource, List businessPartnerToMap, CompanyUserDTO companyUser, + String token,List roles) { List shareDTOSList = new ArrayList<>(); List companyBusinessPartnerDTOS; - companyBusinessPartnerDTOS = externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUser); + companyBusinessPartnerDTOS = externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUser,token,roles); businessPartnerToMap.forEach(bp -> { if(bp.getCountry() == null){ diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java index b5cba175..292e3fd7 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java @@ -47,14 +47,14 @@ public class WorldMapAndTableLogicService { ExternalBusinessPartnersLogicService externalBusinessPartnersLogicService; - public List getTableInfo(Integer year, List ratingDTOList, CompanyUserDTO companyUser) { + public List getTableInfo(Integer year, List ratingDTOList, CompanyUserDTO companyUser,String token,List roles) { log.debug("Request to get Table Info"); List dataSources = ratingDTOList.stream().map(RatingDTO::getDataSourceName).toList(); List dataDTOS = new ArrayList<>(); List businessPartnerDTOS; - businessPartnerDTOS = externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUser); - List countryList = externalBusinessPartnersLogicService.getExternalPartnersCountry(companyUser); + businessPartnerDTOS = externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUser,token,roles); + List countryList = externalBusinessPartnersLogicService.getExternalPartnersCountry(companyUser,token,roles); if (!dataSources.isEmpty() && year != null && year > 0) { dataDTOS = dataSourceValueService.findByRatingAndCountryAndScoreGreaterThanAndYear(Float.valueOf(-1), countryList, dataSources, year); @@ -148,6 +148,8 @@ private DashBoardTableDTO setBusinessPartnerProps(BusinessPartnerDTO businessPar dashBoardTableDTO.setId(Long.valueOf(id)); dashBoardTableDTO.setLatitude(businessPartnerDTO.getLatitude()); dashBoardTableDTO.setLongitude(businessPartnerDTO.getLongitude()); + dashBoardTableDTO.setCustomer(businessPartnerDTO.getCustomer()); + dashBoardTableDTO.setSupplier(businessPartnerDTO.getSupplier()); return dashBoardTableDTO; } diff --git a/src/main/resources/config/application-local.yml b/src/main/resources/config/application-local.yml index 49f95940..4e9035f3 100644 --- a/src/main/resources/config/application-local.yml +++ b/src/main/resources/config/application-local.yml @@ -57,4 +57,7 @@ security: application: host: http://localhost:8080/api/dashboard partnersPoolUrl: - legalEntities: 'https://partners-pool.dev.demo.catena-x.net/api/catena/legal-entities' \ No newline at end of file + legalEntities: 'https://partners-pool.dev.demo.catena-x.net/api/catena/legal-entities' + +server: + port: 9090 \ No newline at end of file diff --git a/src/main/resources/config/liquibase/fake-data/dashboard.json b/src/main/resources/config/liquibase/fake-data/dashboard.json index c38903a1..ff1b5366 100644 --- a/src/main/resources/config/liquibase/fake-data/dashboard.json +++ b/src/main/resources/config/liquibase/fake-data/dashboard.json @@ -1,14 +1,16 @@ [ { - "bpn":"BPNL00000008KD5G", - "legalName":"Steering Wheel Foundation", - "street":"West Road", - "houseNumber":"12", - "zipCode":"AA67HR", - "city":"Mogadishu", - "country":"Somalia", + "bpn": "BPNL00000008KD5G", + "legalName": "Steering Wheel Foundation", + "street": "West Road", + "houseNumber": "12", + "zipCode": "AA67HR", + "city": "Mogadishu", + "country": "Somalia", "longitude": 45.3425, - "latitude": 2.0408 + "latitude": 2.0408, + "supplier": true, + "customer": false }, { "bpn": "BPNL00000012SR7T", @@ -19,7 +21,9 @@ "city": "Graubünden", "country": "Switzerland", "longitude": 7.4474, - "latitude": 46.9480 + "latitude": 46.9480, + "supplier": true, + "customer": true }, { "bpn": "BPNL00000025OT5F", @@ -30,12 +34,10 @@ "city": "San Francisco", "country": "United States of America", "longitude": -122.4430, - "latitude": 37.7562 + "latitude": 37.7562, + "supplier": false, + "customer": true }, - - - - { "bpn": "BPNL00000008KD5G", "legalName": "Williamson LLC", @@ -45,7 +47,9 @@ "city": "Ob’", "country": "Russia", "longitude": 82.6615789, - "latitude": 55.0214573 + "latitude": 55.0214573, + "supplier": false, + "customer": false }, { "bpn": "BPNL00000012SR7T", diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java index 1a520e4e..c3862f4a 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java @@ -19,25 +19,28 @@ ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.rest; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.eclipse.tractusx.valueaddedservice.ValueAddedServiceApplication; +import org.eclipse.tractusx.valueaddedservice.config.ApplicationVariables; import org.eclipse.tractusx.valueaddedservice.domain.Company; import org.eclipse.tractusx.valueaddedservice.domain.CompanyGates; import org.eclipse.tractusx.valueaddedservice.domain.CompanyGroup; import org.eclipse.tractusx.valueaddedservice.domain.CompanyUser; -import org.eclipse.tractusx.valueaddedservice.dto.BusinessPartnerDTO; -import org.eclipse.tractusx.valueaddedservice.dto.CompanyGatesDTO; -import org.eclipse.tractusx.valueaddedservice.dto.CompanyUserDTO; -import org.eclipse.tractusx.valueaddedservice.dto.CountryDTO; +import org.eclipse.tractusx.valueaddedservice.dto.*; import org.eclipse.tractusx.valueaddedservice.repository.CompanyGatesRepository; import org.eclipse.tractusx.valueaddedservice.repository.CompanyGroupRepository; import org.eclipse.tractusx.valueaddedservice.repository.CompanyRepository; import org.eclipse.tractusx.valueaddedservice.repository.CompanyUserRepository; import org.eclipse.tractusx.valueaddedservice.utils.PostgreSQLContextInitializer; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; @@ -54,6 +57,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.when; @Slf4j @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @@ -75,6 +79,27 @@ class BPNIntegartionTest { @Autowired CompanyUserRepository companyUserRepository; + @MockBean + ApplicationVariables applicationVariables; + + @BeforeEach + public void setUp() throws JsonProcessingException { + AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); + authPropertiesDTO.setCompanyName("TestCompany"); + authPropertiesDTO.setEmail("test@email.com"); + authPropertiesDTO.setName("TestName"); + + ObjectMapper mapper = new ObjectMapper(); + String json = "{ \"Cl16-CX-CRisk\": { \"roles\": [ \"User\", \"Company Admin\", \"read_suppliers\", \"read_customers\" ] } }"; + Map map = mapper.readValue(json, new TypeReference<>() { + }); + authPropertiesDTO.setResourceAccess(map); + + when(applicationVariables.getAuthPropertiesDTO()).thenReturn(authPropertiesDTO); + when(applicationVariables.getToken()).thenReturn(""); + } + + @AfterEach public void cleanGatesAndRelations(){ companyUserRepository.deleteAll(); @@ -110,7 +135,6 @@ void getCountryByAssociatedBPtoUser() throws Exception { } @Test - void getCompanyBpns() throws Exception { Map map = getMap(); diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java index 5e73cac7..0641f69d 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java @@ -19,17 +19,23 @@ ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.rest; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.eclipse.tractusx.valueaddedservice.ValueAddedServiceApplication; +import org.eclipse.tractusx.valueaddedservice.config.ApplicationVariables; +import org.eclipse.tractusx.valueaddedservice.dto.AuthPropertiesDTO; import org.eclipse.tractusx.valueaddedservice.dto.DashBoardTableDTO; import org.eclipse.tractusx.valueaddedservice.dto.DashBoardWorldMapDTO; import org.eclipse.tractusx.valueaddedservice.dto.RatingDTO; import org.eclipse.tractusx.valueaddedservice.utils.PostgreSQLContextInitializer; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.Resource; @@ -48,9 +54,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.when; @Slf4j -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = ValueAddedServiceApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class DashBoardResourceIntegrationTest { @@ -64,6 +71,25 @@ class DashBoardResourceIntegrationTest { @Autowired ObjectMapper objectMapper; + @MockBean + ApplicationVariables applicationVariables; + + @BeforeEach + public void setUp() throws JsonProcessingException { + AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); + authPropertiesDTO.setCompanyName("TestCompany"); + authPropertiesDTO.setEmail("test@email.com"); + authPropertiesDTO.setName("TestName"); + + ObjectMapper mapper = new ObjectMapper(); + String json = "{ \"Cl16-CX-CRisk\": { \"roles\": [ \"User\", \"Company Admin\", \"read_suppliers\", \"read_customers\" ] } }"; + Map map = mapper.readValue(json, new TypeReference>(){}); + authPropertiesDTO.setResourceAccess(map); + + when(applicationVariables.getAuthPropertiesDTO()).thenReturn(authPropertiesDTO); + } + + private Map getMap() throws IOException { RatingDTO ratingDTO = objectMapper.readValue(listRatingJson.getInputStream(), RatingDTO.class); diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RangeIntegartionTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RangeIntegartionTest.java index e5ad9cb3..bfe8a5b2 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RangeIntegartionTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RangeIntegartionTest.java @@ -50,7 +50,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; @Slf4j -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = ValueAddedServiceApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class RangeIntegartionTest { diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java index 255d424f..7e471d94 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java @@ -19,17 +19,23 @@ ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.rest; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.eclipse.tractusx.valueaddedservice.ValueAddedServiceApplication; +import org.eclipse.tractusx.valueaddedservice.config.ApplicationVariables; +import org.eclipse.tractusx.valueaddedservice.dto.AuthPropertiesDTO; import org.eclipse.tractusx.valueaddedservice.dto.BusinessPartnerDTO; import org.eclipse.tractusx.valueaddedservice.dto.DataSourceDTO; import org.eclipse.tractusx.valueaddedservice.dto.ShareDTOs.ShareDTO; import org.eclipse.tractusx.valueaddedservice.utils.PostgreSQLContextInitializer; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.Resource; @@ -46,9 +52,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.mockito.Mockito.when; @Slf4j -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = ValueAddedServiceApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class RatingApiIntegrationTest { @@ -73,6 +80,25 @@ private Map getMap() throws IOException { return map; } + @MockBean + ApplicationVariables applicationVariables; + + @BeforeEach + public void setUp() throws JsonProcessingException { + AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); + authPropertiesDTO.setCompanyName("TestCompany"); + authPropertiesDTO.setEmail("test@email.com"); + authPropertiesDTO.setName("TestName"); + + ObjectMapper mapper = new ObjectMapper(); + String json = "{ \"Cl16-CX-CRisk\": { \"roles\": [ \"User\", \"Company Admin\", \"read_suppliers\", \"read_customers\" ] } }"; + Map map = mapper.readValue(json, new TypeReference>(){}); + authPropertiesDTO.setResourceAccess(map); + + when(applicationVariables.getAuthPropertiesDTO()).thenReturn(authPropertiesDTO); + } + + @Test @Transactional void allYears() throws Exception { diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/ReportApiIntegrationTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/ReportApiIntegrationTest.java index 862e8c33..9218b2ee 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/ReportApiIntegrationTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/ReportApiIntegrationTest.java @@ -51,7 +51,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; @Slf4j -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = ValueAddedServiceApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class ReportApiIntegrationTest { diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/UploadAndDownloadApiIntegrationTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/UploadAndDownloadApiIntegrationTest.java index 4175c4b8..2e764e2a 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/UploadAndDownloadApiIntegrationTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/UploadAndDownloadApiIntegrationTest.java @@ -54,7 +54,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; @Slf4j -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = ValueAddedServiceApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class UploadAndDownloadApiIntegrationTest { diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java index 40a823c7..25164086 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java @@ -19,6 +19,8 @@ ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.service.logic; +import org.eclipse.tractusx.valueaddedservice.config.ApplicationVariables; +import org.eclipse.tractusx.valueaddedservice.dto.AuthPropertiesDTO; import org.eclipse.tractusx.valueaddedservice.dto.CompanyUserDTO; import org.eclipse.tractusx.valueaddedservice.dto.CountryDTO; import org.eclipse.tractusx.valueaddedservice.service.CountryService; @@ -51,6 +53,12 @@ class CountryLogicServiceTest { @InjectMocks CountryLogicService countryLogicService; + @Mock + ApplicationVariables applicationVariables; + + + + @Test @DisplayName("Should return a list of countries filtered by iso2") void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2() { @@ -58,16 +66,25 @@ void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2() { CountryDTO countryDTO1 = new CountryDTO(1L, "Germany", "DEU", "DE", "Europe","","",3L); CountryDTO countryDTO2 = new CountryDTO(2L, "Spain", "ESP", "ES", "Europe","","",3L); CountryDTO countryDTO3 = new CountryDTO(3L, "France", "FRA", "FR", "Europe","","",3L); + + AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); + authPropertiesDTO.setCompanyName("TestCompany"); + authPropertiesDTO.setEmail("test@email.com"); + authPropertiesDTO.setName("TestName"); + + + when(applicationVariables.getToken()).thenReturn(""); + List countryDTOList = Arrays.asList(countryDTO1, countryDTO2, countryDTO3); when(countryService.findAll()).thenReturn(countryDTOList); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO)) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) .thenReturn(1L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO)) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) .thenReturn(2L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO)) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) .thenReturn(3L); - List result = countryLogicService.getCountryFilterByISO2(companyUserDTO); + List result = countryLogicService.getCountryFilterByISO2(companyUserDTO,applicationVariables.getToken(),new ArrayList<>()); assertEquals(3, result.size()); assertEquals("Germany", result.get(0).getCountry()); @@ -89,14 +106,16 @@ void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2AndTotalBusi List countryDTOList = Arrays.asList(countryDTO1, countryDTO2, countryDTO3); when(countryService.findAll()).thenReturn(countryDTOList); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO)) + when(applicationVariables.getToken()).thenReturn(""); + + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) .thenReturn(1L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO)) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) .thenReturn(2L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO)) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) .thenReturn(3L); - List result = countryLogicService.getCountryFilterByISO2(companyUserDTO); + List result = countryLogicService.getCountryFilterByISO2(companyUserDTO,"",new ArrayList<>()); assertEquals(3, result.size()); assertEquals("Germany", result.get(0).getCountry()); @@ -121,7 +140,7 @@ void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2AndTotalBusi void getAssociatedCountriesWhenCompanyUserDTONullThenReturnEmptyList() { CompanyUserDTO companyUserDTO = null; List countryDTOList = - countryLogicService.getAssociatedCountries(companyUserDTO); + countryLogicService.getAssociatedCountries(companyUserDTO,"",new ArrayList<>()); assertTrue(countryDTOList.isEmpty()); } @@ -147,7 +166,7 @@ void getAssociatedCountriesWhenCompanyUserDTONotNullThenReturnListOfCountries() when(countryService.findByCountryIn(anyList())).thenReturn(countryDTOList); - List result = countryLogicService.getAssociatedCountries(companyUserDTO); + List result = countryLogicService.getAssociatedCountries(companyUserDTO,"",new ArrayList<>()); assertNotNull(result); assertEquals(1, result.size()); From 3cbce057d37f00638b542d01f3d412a4579ce7e1 Mon Sep 17 00:00:00 2001 From: "fabio.d.mota" Date: Wed, 5 Jul 2023 14:30:01 +0100 Subject: [PATCH 3/6] feat(Country Risk): Add mapping between Bpdm Gate and DTO Correct unit test to valid new models and logic --- .github/workflows/build.yml | 1 + CHANGELOG.md | 1 + .../config/ApplicationVariables.java | 5 + .../repository/CountryRepository.java | 2 + .../service/CountryService.java | 6 + .../service/DashboardService.java | 5 +- .../logic/BusinessPartnersLogicService.java | 278 +++++++++++++ .../service/logic/CountryLogicService.java | 17 +- .../ExternalBusinessPartnersLogicService.java | 66 +--- .../service/logic/InvokeService.java | 20 +- .../service/logic/ShareLogicService.java | 5 +- .../logic/WorldMapAndTableLogicService.java | 7 +- src/main/resources/config/application-dev.yml | 4 +- src/main/resources/config/application-int.yml | 5 + .../resources/config/application-local.yml | 4 +- src/main/resources/config/application.yml | 6 +- .../rest/BPNIntegartionTest.java | 23 +- .../DashBoardResourceIntegrationTest.java | 19 +- .../rest/RatingApiIntegrationTest.java | 18 +- .../service/InvokeServiceTest.java | 56 +-- .../service/mocks/ConfigServerMock.java | 371 +++++++++++++++++- .../utils/DataBaseJsonConverterTest.java | 92 +++++ .../utils/MockUtilsTest.java | 58 +++ src/test/resources/config/application.yml | 5 +- 24 files changed, 956 insertions(+), 118 deletions(-) create mode 100644 src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java create mode 100644 src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java create mode 100644 src/test/java/org/eclipse/tractusx/valueaddedservice/utils/MockUtilsTest.java diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index bde6757f..971d64b3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,6 +1,7 @@ name: Build Pipeline on: + workflow_dispatch: push: branches: - 'main' diff --git a/CHANGELOG.md b/CHANGELOG.md index 977f6e3b..27b146e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Add project name to sonar cloud properties - Added Suppliers and Customers fields for logic filtering +- Added new client id to get roles from the new country risk published app ### Changed - Map Between API and New Data Model for getting Suppliers and Customers diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java index 7e8e29b9..f7b62547 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.eclipse.tractusx.valueaddedservice.constants.VasConstants; import org.eclipse.tractusx.valueaddedservice.dto.AuthPropertiesDTO; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Base64; @@ -31,6 +32,9 @@ @Component public class ApplicationVariables { + @Value("${application.clientId}") + private String clientId; + private String token; private AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); @@ -57,6 +61,7 @@ public void decodeJWT() throws JsonProcessingException { Base64.Decoder decoder = Base64.getUrlDecoder(); String header = new String(decoder.decode(chunks[1])); this.authPropertiesDTO = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).readValue(header, AuthPropertiesDTO.class); + this.authPropertiesDTO.setClientResource(clientId); this.authPropertiesDTO.getRoles(this.authPropertiesDTO.getClientResource()); } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/repository/CountryRepository.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/repository/CountryRepository.java index 7c0d9a81..e4aa4d3e 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/repository/CountryRepository.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/repository/CountryRepository.java @@ -36,4 +36,6 @@ public interface CountryRepository extends JpaRepository { List findByCountryIn(List stringList); Optional findByCountry(String countryName); + + Optional findByIso2(String iso2); } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/CountryService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/CountryService.java index 0cfae294..5cd83356 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/CountryService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/CountryService.java @@ -61,6 +61,12 @@ public Optional findCountryByName(String countryName){ return countryRepository.findByCountry(countryName).map(countryMapper::toDto); } + @Transactional(readOnly = true) + public Optional findCountryByIso2(String iso2){ + return countryRepository.findByIso2(iso2).map(countryMapper::toDto); + } + + /** diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java index ba43bca6..95bbe4da 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/DashboardService.java @@ -76,6 +76,9 @@ public class DashboardService { @Autowired ApplicationVariables applicationVariables; + @Autowired + BusinessPartnersLogicService businessPartnersLogicService; + public List getTableInfo(Integer year, List ratingDTOList, CompanyUserDTO companyUser) { return worldMapAndTableLogicService.getTableInfo(year, ratingDTOList, companyUser,applicationVariables.getToken(), applicationVariables.getAuthPropertiesDTO().getRoles(applicationVariables.getAuthPropertiesDTO().getClientResource())); @@ -123,7 +126,7 @@ public List getCountryFilterByISO2(CompanyUserDTO companyUserDTO) { } public List getExternalBusinessPartners(CompanyUserDTO companyUserDTO) { - return externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUserDTO,applicationVariables.getToken(), + return businessPartnersLogicService.getExternalBusinessPartners(companyUserDTO,applicationVariables.getToken(), applicationVariables.getAuthPropertiesDTO().getRoles(applicationVariables.getAuthPropertiesDTO().getClientResource())); } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java new file mode 100644 index 00000000..f889edfb --- /dev/null +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java @@ -0,0 +1,278 @@ +/******************************************************************************** + * Copyright (c) 2022,2023 BMW Group AG + * Copyright (c) 2022,2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package org.eclipse.tractusx.valueaddedservice.service.logic; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.tractusx.valueaddedservice.dto.BusinessPartnerDTO; +import org.eclipse.tractusx.valueaddedservice.dto.CompanyUserDTO; +import org.eclipse.tractusx.valueaddedservice.dto.CountryDTO; +import org.eclipse.tractusx.valueaddedservice.service.CountryService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; + +import java.util.*; + +import static org.eclipse.tractusx.valueaddedservice.constants.VasConstants.CSV_ROLE_READ_CUSTOMER; +import static org.eclipse.tractusx.valueaddedservice.constants.VasConstants.CSV_ROLE_READ_SUPPLIER; + +@Service +@Slf4j +public class BusinessPartnersLogicService { + + @Autowired + ObjectMapper objectMapper; + + @Value(value = "classpath:config/liquibase/fake-data/dashboard.json") + private Resource json; + + @Value("${application.partnersPoolUrl.bpdmAddressUrl}") + private String bpdmAddressUrl; + + @Value("${application.partnersPoolUrl.bpdmLegalUrl}") + private String bpdmLegalUrl; + + @Value("${application.partnersPoolUrl.bpdmSiteUrl}") + private String bpdmSiteUrl; + + @Autowired + InvokeService invokeService; + + @Autowired + CountryService countryService; + + + @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#companyUser.name,#companyUser.email,#companyUser.companyName}, #roles}", unless = "#result == null") + public List getExternalBusinessPartners(CompanyUserDTO companyUser, String token, List roles) { + log.debug("getExternalBusinessPartners for companyUserDTO {}", companyUser); + + var headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setBearerAuth(token); + String body = "[]"; + HttpEntity httpEntity = new HttpEntity<>(body, headers); + + // Create a map to hold the externalId to legalName mappings + Map externalIdToLegalName = new HashMap<>(); + + // Call the first endpoint and create the DTOs + List businessPartnerDTOS = invokeService.executeRequest(bpdmLegalUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)); + + // Call the second endpoint and create the DTOs, but only if the externalId is not already present in the existing DTOs + List businessPartnerDTOS2 = invokeService.executeRequest(bpdmAddressUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)); + businessPartnerDTOS2.removeIf(dto -> isExternalIdPresent(dto.getBpn(), businessPartnerDTOS)); + businessPartnerDTOS.addAll(businessPartnerDTOS2); + businessPartnerDTOS2.clear(); + + // Call the third endpoint and create the DTOs, but only if the externalId is not already present in the existing DTOs + businessPartnerDTOS2 = invokeService.executeRequest(bpdmSiteUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)); + businessPartnerDTOS2.removeIf(dto -> isExternalIdPresent(dto.getBpn(), businessPartnerDTOS)); + businessPartnerDTOS.addAll(businessPartnerDTOS2); + + + // Update country names + updateCountryNames(businessPartnerDTOS); + + + // Filter based on roles + return filterBusinessPartnersByRole(businessPartnerDTOS, roles); + } + + private void updateCountryNames(List businessPartnerDTOS) { + businessPartnerDTOS.forEach(businessPartnerDTO -> { + Optional countryDTO = countryService.findCountryByIso2(businessPartnerDTO.getCountry()); + if(countryDTO.isPresent()){ + businessPartnerDTO.setCountry(countryDTO.get().getCountry()); + } + }); + } + + + private List customMappingLogic(String json, Map externalIdToLegalName) { + // Parse the JSON into a JsonNode object + JsonNode rootNode = parseJson(json); + + // Get the "content" array + JsonNode contentNode = rootNode.get("content"); + + // Create a list to hold the DTOs + List dtos = new ArrayList<>(); + + // Iterate over the elements in the "content" array + for (JsonNode elementNode : contentNode) { + // Get the "externalId" field + String externalId = getExternalId(elementNode, externalIdToLegalName); + + // Check if the "legalAddress" field exists + if (elementNode.has("legalAddress")) { + // Handle as the second type of JSON + handleSecondTypeJson(elementNode, externalId, dtos, externalIdToLegalName); + } else if (elementNode.has("mainAddress")) { + // Handle as the third type of JSON + handleThirdTypeJson(elementNode, externalId, dtos, externalIdToLegalName); + } else { + // Handle as the first type of JSON + handleFirstTypeJson(elementNode, externalId, dtos, externalIdToLegalName); + } + } + + return dtos; + } + + private JsonNode parseJson(String json) { + try { + return objectMapper.readTree(json); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + private String getExternalId(JsonNode elementNode, Map externalIdToLegalName) { + String externalId; + if (elementNode.has("legalNameParts")) { + externalId = elementNode.get("externalId").asText(); + String legalName = elementNode.get("legalNameParts").get(0).asText(); + externalIdToLegalName.put(externalId, legalName); + } else { + externalId = elementNode.get("legalEntityExternalId").asText(); + } + return externalId; + } + + private void handleSecondTypeJson(JsonNode elementNode, String externalId, List dtos, Map externalIdToLegalName) { + JsonNode legalAddressNode = elementNode.get("legalAddress"); + String bpn = legalAddressNode.get("bpn").asText(); + if (bpn != null) { + dtos.add(createDto(bpn, legalAddressNode, externalIdToLegalName.get(externalId))); + } + bpn = elementNode.get("bpn").asText(); + if (bpn != null) { + dtos.add(createDto(bpn, legalAddressNode, externalIdToLegalName.get(externalId))); + } + } + + private void handleFirstTypeJson(JsonNode elementNode, String externalId, List dtos, Map externalIdToLegalName) { + String bpn = elementNode.get("bpn").asText(); + if (bpn != null) { + dtos.add(createDto(bpn, elementNode, externalIdToLegalName.get(externalId))); + } + } + + private void handleThirdTypeJson(JsonNode elementNode, String externalId, List dtos, Map externalIdToLegalName) { + JsonNode mainAddressNode = elementNode.get("mainAddress"); + String bpn = mainAddressNode.get("bpn").asText(); + if (bpn != null) { + dtos.add(createDto(bpn, mainAddressNode, externalIdToLegalName.get(externalId))); + } + bpn = elementNode.get("bpn").asText(); + if (bpn != null) { + dtos.add(createDto(bpn, mainAddressNode, externalIdToLegalName.get(externalId))); + } + } + + + private BusinessPartnerDTO createDto(String bpn, JsonNode addressNode, String legalName) { + BusinessPartnerDTO dto = new BusinessPartnerDTO(); + dto.setBpn(bpn); + dto.setLegalName(legalName); + setFieldsFromAddress(dto, addressNode); + setRoles(dto, addressNode); + return dto; + } + + private void setFieldsFromAddress(BusinessPartnerDTO dto, JsonNode addressNode) { + JsonNode physicalPostalAddressNode = addressNode.get("physicalPostalAddress"); + if (physicalPostalAddressNode != null) { + dto.setStreet(physicalPostalAddressNode.get("street").get("name").asText()); + dto.setHouseNumber(physicalPostalAddressNode.get("street").get("houseNumber").asText()); + dto.setZipCode(physicalPostalAddressNode.get("postalCode").asText()); + dto.setCity(physicalPostalAddressNode.get("city").asText()); + dto.setCountry(physicalPostalAddressNode.get("country").asText()); + dto.setLongitude(physicalPostalAddressNode.get("geographicCoordinates").get("longitude").asText()); + dto.setLatitude(physicalPostalAddressNode.get("geographicCoordinates").get("latitude").asText()); + } + } + + private void setRoles(BusinessPartnerDTO dto, JsonNode addressNode) { + JsonNode rolesNode = addressNode.get("ROLES"); + if (rolesNode != null) { + for (JsonNode roleNode : rolesNode) { + String role = roleNode.asText(); + if ("Supplier".equals(role)) { + dto.setSupplier(true); + } else if ("Customer".equals(role)) { + dto.setCustomer(true); + } + } + } + } + + private boolean isExternalIdPresent(String externalId, List dtos) { + return dtos.stream().anyMatch(dto -> dto.getBpn().equals(externalId)); + } + + private List filterBusinessPartnersByRole(List businessPartnerDTOS, List roles) { + List filteredBusinessPartnerDTOS; + + if (roles.contains(CSV_ROLE_READ_SUPPLIER) && roles.contains(CSV_ROLE_READ_CUSTOMER)) { + // User has both roles, no need to filter + filteredBusinessPartnerDTOS = businessPartnerDTOS; + } else if (roles.contains(CSV_ROLE_READ_SUPPLIER)) { + // User can only read suppliers and those who are not customers + filteredBusinessPartnerDTOS = filterSuppliers(businessPartnerDTOS); + } else if (roles.contains(CSV_ROLE_READ_CUSTOMER)) { + // User can only read customers and those who are not suppliers + filteredBusinessPartnerDTOS = filterCustomers(businessPartnerDTOS); + } else { + // User has neither role, can only see those who are neither suppliers nor customers + filteredBusinessPartnerDTOS = filterNeither(businessPartnerDTOS); + } + return filteredBusinessPartnerDTOS; + } + + private List filterSuppliers(List businessPartnerDTOS) { + return businessPartnerDTOS.stream() + .filter(bpn -> bpn.getSupplier() || !bpn.getCustomer()) + .peek(bpn -> bpn.setCustomer(false)) + .toList(); + } + + private List filterCustomers(List businessPartnerDTOS) { + return businessPartnerDTOS.stream() + .filter(bpn -> bpn.getCustomer() || !bpn.getSupplier()) + .peek(bpn -> bpn.setSupplier(false)) + .toList(); + } + + private List filterNeither(List businessPartnerDTOS) { + return businessPartnerDTOS.stream() + .filter(bpn -> !bpn.getSupplier() && !bpn.getCustomer()) + .toList(); + } +} diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java index 60ef5f23..5fb02f33 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicService.java @@ -72,17 +72,30 @@ public List getCountryFilterByISO2(CompanyUserDTO companyUserDTO,Str @Cacheable(value = "vas-country", key = "{#root.methodName , #countryName}", unless = "#result == null") public CountryDTO findCountryByName(String countryName){ Optional countryDTO = countryService.findCountryByName(countryName); - log.debug("findCountryByName filtered by countryName {}", countryName); + log.debug("findCountryByName filtered by countryName"); if(countryDTO.isPresent()){ return countryDTO.get(); }else{ - log.error("Country does not exists on country table {}", countryName); + log.error("Country does not exists on country table"); return new CountryDTO(); } + } + + @Cacheable(value = "vas-country", key = "{#root.methodName , #iso2}", unless = "#result == null") + public CountryDTO findCountryByIso2(String iso2){ + Optional countryDTO = countryService.findCountryByIso2(iso2); + log.debug("findCountryByIso2 filtered by iso2"); + if(countryDTO.isPresent()){ + return countryDTO.get(); + }else{ + log.error("Country does not exists on country table"); + return new CountryDTO(); + } } + @CacheEvict(value = "vas-country", allEntries = true) public void invalidateAllCache() { log.debug("invalidateAllCache|vas-Country - invalidated cache - allEntries"); diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java index a442d731..13674508 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ExternalBusinessPartnersLogicService.java @@ -19,92 +19,32 @@ ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.service.logic; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; -import org.eclipse.tractusx.valueaddedservice.config.ApplicationVariables; import org.eclipse.tractusx.valueaddedservice.dto.BusinessPartnerDTO; import org.eclipse.tractusx.valueaddedservice.dto.CompanyUserDTO; import org.eclipse.tractusx.valueaddedservice.dto.CountryDTO; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; import org.springframework.stereotype.Service; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import static org.eclipse.tractusx.valueaddedservice.constants.VasConstants.CSV_ROLE_READ_CUSTOMER; -import static org.eclipse.tractusx.valueaddedservice.constants.VasConstants.CSV_ROLE_READ_SUPPLIER; - @Service @Slf4j public class ExternalBusinessPartnersLogicService { - @Autowired - ObjectMapper objectMapper; - - @Value(value = "classpath:config/liquibase/fake-data/dashboard.json") - private Resource json; - - @Value("${application.partnersPoolUrl.legalEntities}") - private String legalEntitiesUrl; @Autowired - ApplicationVariables applicationVariables; - - @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#companyUser.name,#companyUser.email,#companyUser.companyName}, #roles}", unless = "#result == null") - public List getExternalBusinessPartners(CompanyUserDTO companyUser,String token, List roles) { - log.debug("getExternalBusinessPartners for companyUserDTO {}",companyUser); - try { - var headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setBearerAuth(token); - HttpEntity httpEntity = new HttpEntity<>(headers); - List businessPartnerDTOS = objectMapper.readValue(json.getInputStream(), new TypeReference<>() { - }); - - - List filteredBusinessPartnerDTOS; - - if (roles.contains(CSV_ROLE_READ_SUPPLIER) && roles.contains(CSV_ROLE_READ_CUSTOMER)) { - // User has both roles, no need to filter - filteredBusinessPartnerDTOS = businessPartnerDTOS; - } else if (roles.contains(CSV_ROLE_READ_SUPPLIER)) { - // User can only read suppliers and those who are not customers - filteredBusinessPartnerDTOS = businessPartnerDTOS.stream() - .filter(bpn -> bpn.getSupplier() || !bpn.getCustomer()) - .toList(); - } else if (roles.contains(CSV_ROLE_READ_CUSTOMER)) { - // User can only read customers and those who are not suppliers - filteredBusinessPartnerDTOS = businessPartnerDTOS.stream() - .filter(bpn -> bpn.getCustomer() || !bpn.getSupplier()) - .toList(); - } else { - // User has neither role, can only see those who are neither suppliers nor customers - filteredBusinessPartnerDTOS = businessPartnerDTOS.stream() - .filter(bpn -> !bpn.getSupplier() && !bpn.getCustomer()) - .toList(); - } - return filteredBusinessPartnerDTOS; - } catch (IOException e) { - throw new RuntimeException(e); - } - } - + BusinessPartnersLogicService businessPartnersLogicService; @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName},#roles}", unless = "#result == null") public List getExternalPartnersCountry (CompanyUserDTO companyUserDTO,String token,List roles) { log.debug("getExternalPartnersCountry for companyUserDTO {}",companyUserDTO); List businessPartnerDTOS; - businessPartnerDTOS = getExternalBusinessPartners(companyUserDTO,token,roles); + businessPartnerDTOS = businessPartnersLogicService.getExternalBusinessPartners(companyUserDTO,token,roles); List countryList = new ArrayList<>(); countryList.addAll(businessPartnerDTOS.stream().map(BusinessPartnerDTO::getCountry) .collect(Collectors.toSet())); @@ -115,7 +55,7 @@ public List getExternalPartnersCountry (CompanyUserDTO companyUserDTO,St @Cacheable(value = "vas-bpn", key = "{#root.methodName , {#countryDTO.iso3, #companyUserDTO.name,#companyUserDTO.email,#companyUserDTO.companyName},#roles}", unless = "#result == null") public Long getTotalBpnByCountry(CountryDTO countryDTO,CompanyUserDTO companyUserDTO,String token,List roles){ log.debug("getTotalBpnByCountry filtered by country {} and companyUser {}",countryDTO,companyUserDTO); - List businessPartnerDTOS = getExternalBusinessPartners(companyUserDTO,token,roles); + List businessPartnerDTOS = businessPartnersLogicService.getExternalBusinessPartners(companyUserDTO,token,roles); return businessPartnerDTOS.stream().filter(businessPartnerDTO -> businessPartnerDTO.getCountry().equalsIgnoreCase(countryDTO.getCountry())).count(); } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java index 3d03530d..84c45f29 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java @@ -23,11 +23,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; @Service @Slf4j @@ -35,13 +38,16 @@ public class InvokeService { @Autowired RestTemplate restTemplate; - public Object executeRequest(String url, HttpMethod httpMethod, HttpEntity httpEntity,Object object){ - try{ - return restTemplate.exchange(url,httpMethod,httpEntity,object.getClass()); - }catch(HttpClientErrorException e){ - log.error("error url {} message {}",url,e.getMessage() ); + + public List executeRequest(String url, HttpMethod httpMethod, HttpEntity httpEntity, Class responseType, Function> mappingFunction) { + try { + ResponseEntity responseEntity = restTemplate.exchange(url, httpMethod, httpEntity, String.class); + String json = responseEntity.getBody(); + return mappingFunction.apply(json); + } catch (HttpClientErrorException e) { + log.error("error url {} message {}", url, e.getMessage()); + return new ArrayList<>(); } - return new ArrayList<>(); } - } + diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java index b860d29c..d32af78f 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/ShareLogicService.java @@ -45,13 +45,16 @@ public class ShareLogicService { @Autowired ExternalBusinessPartnersLogicService externalBusinessPartnersLogicService; + @Autowired + BusinessPartnersLogicService businessPartnersLogicService; + public List findRatingsScoresForEachBpn(List datasource, List businessPartnerToMap, CompanyUserDTO companyUser, String token,List roles) { List shareDTOSList = new ArrayList<>(); List companyBusinessPartnerDTOS; - companyBusinessPartnerDTOS = externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUser,token,roles); + companyBusinessPartnerDTOS = businessPartnersLogicService.getExternalBusinessPartners(companyUser,token,roles); businessPartnerToMap.forEach(bp -> { if(bp.getCountry() == null){ diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java index 292e3fd7..6645bb5b 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/WorldMapAndTableLogicService.java @@ -40,12 +40,13 @@ public class WorldMapAndTableLogicService { @Autowired DataSourceValueService dataSourceValueService; - @Autowired - CountryLogicService countryLogicService; @Autowired ExternalBusinessPartnersLogicService externalBusinessPartnersLogicService; + @Autowired + BusinessPartnersLogicService businessPartnersLogicService; + public List getTableInfo(Integer year, List ratingDTOList, CompanyUserDTO companyUser,String token,List roles) { log.debug("Request to get Table Info"); @@ -53,7 +54,7 @@ public List getTableInfo(Integer year, List rating List dataDTOS = new ArrayList<>(); List businessPartnerDTOS; - businessPartnerDTOS = externalBusinessPartnersLogicService.getExternalBusinessPartners(companyUser,token,roles); + businessPartnerDTOS = businessPartnersLogicService.getExternalBusinessPartners(companyUser,token,roles); List countryList = externalBusinessPartnersLogicService.getExternalPartnersCountry(companyUser,token,roles); if (!dataSources.isEmpty() && year != null && year > 0) { diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml index 16f86635..30f798b9 100644 --- a/src/main/resources/config/application-dev.yml +++ b/src/main/resources/config/application-dev.yml @@ -31,4 +31,6 @@ application: name: dev host: http://project-value-added-service-vas/api/schedule partnersPoolUrl: - legalEntities: 'https://partners-pool.dev.demo.catena-x.net/api/catena/legal-entities' \ No newline at end of file + bpdmAddressUrl: 'https://business-partners.dev.demo.catena-x.net/companies/test-company/api/catena/output/addresses/search?limit=10' + bpdmSiteUrl: 'https://business-partners.dev.demo.catena-x.net/companies/test-company/api/catena/output/sites/search?limit=10' + bpdmLegalUrl: 'https://business-partners.dev.demo.catena-x.net/companies/test-company/api/catena/output/legal-entities/search?limit=10' \ No newline at end of file diff --git a/src/main/resources/config/application-int.yml b/src/main/resources/config/application-int.yml index c20ec9ba..f1eb2140 100644 --- a/src/main/resources/config/application-int.yml +++ b/src/main/resources/config/application-int.yml @@ -32,3 +32,8 @@ spring: application: name: int + host: http://project-value-added-service-vas/api/schedule + partnersPoolUrl: + bpdmAddressUrl: 'https://business-partners.int.demo.catena-x.net/companies/test-company/api/catena/output/addresses/search?limit=10' + bpdmSiteUrl: 'https://business-partners.int.demo.catena-x.net/companies/test-company/api/catena/output/sites/search?limit=10' + bpdmLegalUrl: 'https://business-partners.int.demo.catena-x.net/companies/test-company/api/catena/output/legal-entities/search?limit=10' \ No newline at end of file diff --git a/src/main/resources/config/application-local.yml b/src/main/resources/config/application-local.yml index 4e9035f3..2781cc9e 100644 --- a/src/main/resources/config/application-local.yml +++ b/src/main/resources/config/application-local.yml @@ -57,7 +57,9 @@ security: application: host: http://localhost:8080/api/dashboard partnersPoolUrl: - legalEntities: 'https://partners-pool.dev.demo.catena-x.net/api/catena/legal-entities' + bpdmAddressUrl: 'http://localhost:8082/api/catena/output/addresses/search?size=100' + bpdmSiteUrl: 'http://localhost:8082/api/catena/output/sites/search?size=100' + bpdmLegalUrl: 'http://localhost:8082/api/catena/output/legal-entities/search?size=100' server: port: 9090 \ No newline at end of file diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index 322e5663..0b77501f 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -92,8 +92,10 @@ application: name: default host: project-value-added-service-vas/api/dashboard partnersPoolUrl: - legalEntities: 'http://localhost:8080/api/catena/legal-entities' - clientId: 'Cl16-CX-CRisk' + bpdmAddressUrl: 'http://localhost:8082/api/catena/output/addresses/search?size=100' + bpdmSiteUrl: 'http://localhost:8082/api/catena/output/sites/search?size=100' + bpdmLegalUrl: 'http://localhost:8082/api/catena/output/legal-entities/search?size=100' + clientId: 'app374' management: endpoints: diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java index c3862f4a..8c4451ff 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java @@ -34,10 +34,9 @@ import org.eclipse.tractusx.valueaddedservice.repository.CompanyGroupRepository; import org.eclipse.tractusx.valueaddedservice.repository.CompanyRepository; import org.eclipse.tractusx.valueaddedservice.repository.CompanyUserRepository; +import org.eclipse.tractusx.valueaddedservice.utils.MockUtilsTest; import org.eclipse.tractusx.valueaddedservice.utils.PostgreSQLContextInitializer; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -60,6 +59,7 @@ import static org.mockito.Mockito.when; @Slf4j +@TestInstance(TestInstance.Lifecycle.PER_CLASS) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class BPNIntegartionTest { @@ -82,6 +82,15 @@ class BPNIntegartionTest { @MockBean ApplicationVariables applicationVariables; + MockUtilsTest mockUtilsTest; + + @BeforeAll + public void beforeAll() { + mockUtilsTest = new MockUtilsTest(); + mockUtilsTest.beforeAll(); + } + + @BeforeEach public void setUp() throws JsonProcessingException { AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); @@ -97,6 +106,8 @@ public void setUp() throws JsonProcessingException { when(applicationVariables.getAuthPropertiesDTO()).thenReturn(authPropertiesDTO); when(applicationVariables.getToken()).thenReturn(""); + mockUtilsTest.openPorts(); + } @@ -109,6 +120,7 @@ public void cleanGatesAndRelations(){ } + private Map getMap() throws IOException { Map map = new HashMap<>(); map.put("companyName","TestCompany"); @@ -119,9 +131,8 @@ private Map getMap() throws IOException { } @Test - void getCountryByAssociatedBPtoUser() throws Exception { - + mockUtilsTest.openPorts(); Map map = getMap(); UriTemplate uritemplate= new UriTemplate("/api/dashboard/getBpnCountrys?name={name}&companyName={companyName}&email={email}"); URI uri = uritemplate.expand(map); @@ -136,7 +147,7 @@ void getCountryByAssociatedBPtoUser() throws Exception { @Test void getCompanyBpns() throws Exception { - + mockUtilsTest.openPorts(); Map map = getMap(); UriTemplate uritemplate= new UriTemplate("/api/dashboard/getCompanyBpns?name={name}&companyName={companyName}&email={email}"); URI uri = uritemplate.expand(map); diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java index 0641f69d..e13925ae 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/DashBoardResourceIntegrationTest.java @@ -29,9 +29,12 @@ import org.eclipse.tractusx.valueaddedservice.dto.DashBoardTableDTO; import org.eclipse.tractusx.valueaddedservice.dto.DashBoardWorldMapDTO; import org.eclipse.tractusx.valueaddedservice.dto.RatingDTO; +import org.eclipse.tractusx.valueaddedservice.utils.MockUtilsTest; import org.eclipse.tractusx.valueaddedservice.utils.PostgreSQLContextInitializer; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; @@ -57,6 +60,7 @@ import static org.mockito.Mockito.when; @Slf4j +@TestInstance(TestInstance.Lifecycle.PER_CLASS) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class DashBoardResourceIntegrationTest { @@ -74,8 +78,18 @@ class DashBoardResourceIntegrationTest { @MockBean ApplicationVariables applicationVariables; + MockUtilsTest mockUtilsTest; + + @BeforeAll + public void beforeAll() { + mockUtilsTest = new MockUtilsTest(); + mockUtilsTest.beforeAll(); + } + + @BeforeEach public void setUp() throws JsonProcessingException { + mockUtilsTest.openPorts(); AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); authPropertiesDTO.setCompanyName("TestCompany"); authPropertiesDTO.setEmail("test@email.com"); @@ -83,7 +97,8 @@ public void setUp() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String json = "{ \"Cl16-CX-CRisk\": { \"roles\": [ \"User\", \"Company Admin\", \"read_suppliers\", \"read_customers\" ] } }"; - Map map = mapper.readValue(json, new TypeReference>(){}); + Map map = mapper.readValue(json, new TypeReference<>() { + }); authPropertiesDTO.setResourceAccess(map); when(applicationVariables.getAuthPropertiesDTO()).thenReturn(authPropertiesDTO); @@ -112,6 +127,7 @@ private Map getMap() throws IOException { @Transactional void getTableInfo() throws Exception { + Map map = getMap(); UriTemplate uritemplate= new UriTemplate("/api/dashboard/getTableInfo?year={year}&ratings[]={ratings}&name={name}&companyName={companyName}&email={email}"); URI uri = uritemplate.expand(map); @@ -162,6 +178,7 @@ void getWorldMapInfoWithRatingNonExist() throws Exception { @Test @Transactional void getTableInfoInfoWithRatingTwoExistRating() throws Exception { + RatingDTO ratingDTO = new RatingDTO(); ratingDTO.setDataSourceName("Economist Intelligence Unit Country Ratings"); ratingDTO.setWeight(50F); diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java index 7e471d94..173105b7 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/RatingApiIntegrationTest.java @@ -29,9 +29,12 @@ import org.eclipse.tractusx.valueaddedservice.dto.BusinessPartnerDTO; import org.eclipse.tractusx.valueaddedservice.dto.DataSourceDTO; import org.eclipse.tractusx.valueaddedservice.dto.ShareDTOs.ShareDTO; +import org.eclipse.tractusx.valueaddedservice.utils.MockUtilsTest; import org.eclipse.tractusx.valueaddedservice.utils.PostgreSQLContextInitializer; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; @@ -55,6 +58,7 @@ import static org.mockito.Mockito.when; @Slf4j +@TestInstance(TestInstance.Lifecycle.PER_CLASS) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,classes = ValueAddedServiceApplication.class) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) class RatingApiIntegrationTest { @@ -83,8 +87,18 @@ private Map getMap() throws IOException { @MockBean ApplicationVariables applicationVariables; + MockUtilsTest mockUtilsTest; + + @BeforeAll + public void beforeAll() { + mockUtilsTest = new MockUtilsTest(); + mockUtilsTest.beforeAll(); + } + + @BeforeEach - public void setUp() throws JsonProcessingException { + public void setUp() throws JsonProcessingException, InterruptedException { + mockUtilsTest.openPorts(); AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); authPropertiesDTO.setCompanyName("TestCompany"); authPropertiesDTO.setEmail("test@email.com"); @@ -96,8 +110,8 @@ public void setUp() throws JsonProcessingException { authPropertiesDTO.setResourceAccess(map); when(applicationVariables.getAuthPropertiesDTO()).thenReturn(authPropertiesDTO); - } + } @Test @Transactional diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java index 161f3488..89e38f3a 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java @@ -21,18 +21,18 @@ import com.fasterxml.jackson.core.JsonProcessingException; -import com.github.tomakehurst.wiremock.WireMockServer; +import lombok.extern.slf4j.Slf4j; import org.eclipse.tractusx.valueaddedservice.ValueAddedServiceApplication; import org.eclipse.tractusx.valueaddedservice.service.logic.InvokeService; -import org.eclipse.tractusx.valueaddedservice.service.mocks.ConfigServerMock; +import org.eclipse.tractusx.valueaddedservice.utils.MockUtilsTest; import org.eclipse.tractusx.valueaddedservice.utils.PostgreSQLContextInitializer; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import java.util.ArrayList; @@ -42,25 +42,27 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; @SpringBootTest(classes = ValueAddedServiceApplication.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) @ContextConfiguration(initializers = PostgreSQLContextInitializer.class) +@Slf4j class InvokeServiceTest { - public static WireMockServer wireMockServer; - @Autowired InvokeService invokeService; - @BeforeEach - public void preSetup() throws InterruptedException { - wireMockServer = ConfigServerMock.openPort(wireMockServer); - } + MockUtilsTest mockUtilsTest; - @AfterEach - public void afterAll() throws InterruptedException { - wireMockServer = ConfigServerMock.closePort(wireMockServer); + @BeforeAll + public void beforeAll() { + mockUtilsTest = new MockUtilsTest(); + mockUtilsTest.beforeAll(); } + @BeforeEach + public void setUp() throws JsonProcessingException, InterruptedException { + mockUtilsTest.openPorts(); + } @Test @DisplayName("Should return the response when the request is success") @@ -70,12 +72,9 @@ void executeRequestWhenRequestIsSuccessThenReturnResponse() throws JsonProcessin httpHeaders.setContentType(MediaType.APPLICATION_JSON); HttpEntity httpEntity = new HttpEntity<>(httpHeaders); - List list = new ArrayList<>(); - list.add("oneElement"); - ConfigServerMock.mocKConnectionToExternalBpnApi(wireMockServer, list); - ResponseEntity response = - (ResponseEntity) invokeService.executeRequest(url, HttpMethod.GET, httpEntity, list); - assertNotEquals(0, response.getBody().size()); + List response = + invokeService.executeRequest(url, HttpMethod.GET, httpEntity, String.class, this::mockMappingFunction); + assertNotEquals(0, response.size()); } @Test @@ -85,11 +84,18 @@ void executeRequestWhenRequestIsFailedThenReturnEmptyList() throws JsonProcessin HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); HttpEntity httpEntity = new HttpEntity<>(httpHeaders); + List newEmptyList = invokeService.executeRequest(url, HttpMethod.GET, httpEntity, String.class, this::mockMappingFunction); + assertEquals(0, newEmptyList.size()); + } + + // Mock mapping function + private List mockMappingFunction(String json) { + // Implement your mock mapping logic here List list = new ArrayList<>(); list.add("oneElement"); - ConfigServerMock.mocKConnectionToExternalBpnApiError(wireMockServer); - List newEmptyList = (List) invokeService.executeRequest(url, HttpMethod.GET, httpEntity, list); - assertEquals(0, newEmptyList.size()); + return list; } + + } \ No newline at end of file diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/mocks/ConfigServerMock.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/mocks/ConfigServerMock.java index d1ac8fa5..cccc1db8 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/mocks/ConfigServerMock.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/mocks/ConfigServerMock.java @@ -26,8 +26,7 @@ import java.util.List; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; public class ConfigServerMock { @@ -72,5 +71,373 @@ public static void mocKConnectionToExternalBpnApiError(WireMockServer mockServer .withHeader("Content-Type", APPLICATION_JSON_VALUE))); } + public static void mocKConnectionToBpdmGateAddresses(WireMockServer mockServer) throws JsonProcessingException { + + mockServer.stubFor(post("/companies/test-company/api/catena/output/addresses/search") + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", APPLICATION_JSON_VALUE) + .withBody("{\n" + + " \"totalElements\": 1009,\n" + + " \"totalPages\": 1009,\n" + + " \"page\": 0,\n" + + " \"contentSize\": 1,\n" + + " \"content\": [\n" + + " {\n" + + " \"nameParts\": [\n" + + " \"WESTERN_LATIN_STANDARD\"\n" + + " ],\n" + + " \"states\": [\n" + + " {\n" + + " \"description\": \"Baden-Wuerttemberg\",\n" + + " \"validFrom\": \"2023-06-05T10:32:30.231\",\n" + + " \"validTo\": \"2023-06-05T10:32:30.231\",\n" + + " \"type\": \"ACTIVE\"\n" + + " }\n" + + " ],\n" + + " \"identifiers\": [],\n" + + " \"physicalPostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"SO\",\n" + + " \"postalCode\": \"70327\",\n" + + " \"city\": \"Mogadishu\",\n" + + " \"street\": {\n" + + " \"namePrefix\": null,\n" + + " \"additionalNamePrefix\": null,\n" + + " \"name\": \"Untertuerckheim Strasse 1\",\n" + + " \"additionalNameSuffix\": null,\n" + + " \"houseNumber\": \"1234\",\n" + + " \"milestone\": \"Untertuerckheim Strasse 1\",\n" + + " \"direction\": \"Untertuerckheim Strasse 1\",\n" + + " \"nameSuffix\": null\n" + + " },\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"administrativeAreaLevel2\": null,\n" + + " \"administrativeAreaLevel3\": null,\n" + + " \"district\": \"Stuttgart\",\n" + + " \"companyPostalCode\": \"71034\",\n" + + " \"industrialZone\": \"Sindelfinden\",\n" + + " \"building\": \"Building A\",\n" + + " \"floor\": \"A\",\n" + + " \"door\": \"1\"\n" + + " },\n" + + " \"alternativePostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"DE\",\n" + + " \"postalCode\": \"1234\",\n" + + " \"city\": \"Stuttgart\",\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"deliveryServiceNumber\": \"Untertuerckheim Strasse 1\",\n" + + " \"deliveryServiceType\": \"PO_BOX\",\n" + + " \"deliveryServiceQualifier\": \"test qualifier\"\n" + + " },\n" + + " \"roles\": [],\n" + + " \"externalId\": \"12044444_legalAddress\",\n" + + " \"legalEntityExternalId\": \"12044444\",\n" + + " \"siteExternalId\": null,\n" + + " \"bpn\": \"BPNA000000000001\"\n" + + " }\n" + + " ]\n" + + "}"))); + } + + public static void mocKConnectionToBpdmGateSite(WireMockServer mockServer) throws JsonProcessingException { + + mockServer.stubFor(post("/companies/test-company/api/catena/output/sites/search") + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", APPLICATION_JSON_VALUE) + .withBody("{\n" + + " \"totalElements\": 1,\n" + + " \"totalPages\": 1,\n" + + " \"page\": 0,\n" + + " \"contentSize\": 1,\n" + + " \"content\": [\n" + + " {\n" + + " \"nameParts\": [\n" + + " \"Factory UT\"\n" + + " ],\n" + + " \"states\": [\n" + + " {\n" + + " \"description\": \"Baden-Wuerttemberg\",\n" + + " \"validFrom\": \"2023-06-05T08:29:20.015\",\n" + + " \"validTo\": \"2023-06-05T08:29:20.015\",\n" + + " \"type\": \"ACTIVE\"\n" + + " }\n" + + " ],\n" + + " \"roles\": [],\n" + + " \"mainAddress\": {\n" + + " \"nameParts\": [\n" + + " \"SITE ADDRESS\"\n" + + " ],\n" + + " \"states\": [\n" + + " {\n" + + " \"description\": \"Baden-Wuerttemberg\",\n" + + " \"validFrom\": \"2023-06-05T08:29:20.015\",\n" + + " \"validTo\": \"2023-06-05T08:29:20.015\",\n" + + " \"type\": \"ACTIVE\"\n" + + " }\n" + + " ],\n" + + " \"identifiers\": [],\n" + + " \"physicalPostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"RU\",\n" + + " \"postalCode\": \"0000\",\n" + + " \"city\": \"Russs\",\n" + + " \"street\": {\n" + + " \"namePrefix\": null,\n" + + " \"additionalNamePrefix\": null,\n" + + " \"name\": \"Untertuerckheim Strasse 1\",\n" + + " \"additionalNameSuffix\": null,\n" + + " \"houseNumber\": \"1234\",\n" + + " \"milestone\": \"Untertuerckheim Strasse 1\",\n" + + " \"direction\": \"Untertuerckheim Strasse 1\",\n" + + " \"nameSuffix\": null\n" + + " },\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"administrativeAreaLevel2\": null,\n" + + " \"administrativeAreaLevel3\": null,\n" + + " \"district\": \"Stuttgart\",\n" + + " \"companyPostalCode\": \"71034\",\n" + + " \"industrialZone\": \"Sindelfinden\",\n" + + " \"building\": \"Building A\",\n" + + " \"floor\": \"A\",\n" + + " \"door\": \"1\"\n" + + " },\n" + + " \"alternativePostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"DE\",\n" + + " \"postalCode\": \"1234\",\n" + + " \"city\": \"Stuttgart\",\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"deliveryServiceNumber\": \"Untertuerckheim Strasse 1\",\n" + + " \"deliveryServiceType\": \"PO_BOX\",\n" + + " \"deliveryServiceQualifier\": \"test qualifier\"\n" + + " },\n" + + " \"roles\": [],\n" + + " \"externalId\": \"12044444_site\",\n" + + " \"legalEntityExternalId\": null,\n" + + " \"siteExternalId\": \"12044444\",\n" + + " \"bpn\": \"BPNA000000000001\"\n" + + " },\n" + + " \"externalId\": \"12044444\",\n" + + " \"legalEntityExternalId\": \"12044444\",\n" + + " \"bpn\": \"BPNS000000000001\"\n" + + " }\n" + + " ]\n" + + "}"))); + } + + public static void mocKConnectionToBpdmGateLegalEntity(WireMockServer mockServer) throws JsonProcessingException { + + mockServer.stubFor(post("/companies/test-company/api/catena/output/legal-entities/search") + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", APPLICATION_JSON_VALUE) + .withBody("{\n" + + " \"totalElements\": 2,\n" + + " \"totalPages\": 1,\n" + + " \"page\": 0,\n" + + " \"contentSize\": 2,\n" + + " \"content\": [\n" + + " {\n" + + " \"identifiers\": [],\n" + + " \"legalShortName\": \"NoC\",\n" + + " \"legalForm\": \"CUSTOM_LEGAL_FORM\",\n" + + " \"states\": [\n" + + " {\n" + + " \"officialDenotation\": \"Active\",\n" + + " \"validFrom\": \"2020-12-16T05:54:48.942\",\n" + + " \"validTo\": \"2023-06-05T07:31:01.213\",\n" + + " \"type\": \"ACTIVE\"\n" + + " }\n" + + " ],\n" + + " \"classifications\": [\n" + + " {\n" + + " \"value\": \"Farming of cattle, dairy farming\",\n" + + " \"code\": \"01.21\",\n" + + " \"type\": \"NACE\"\n" + + " }\n" + + " ],\n" + + " \"legalNameParts\": [\n" + + " \"Name of Company\"\n" + + " ],\n" + + " \"roles\": [],\n" + + " \"legalAddress\": {\n" + + " \"nameParts\": [\n" + + " \"WESTERN_LATIN_STANDARD\"\n" + + " ],\n" + + " \"states\": [\n" + + " {\n" + + " \"description\": \"Baden-Wuerttemberg\",\n" + + " \"validFrom\": \"2023-06-05T10:32:30.231\",\n" + + " \"validTo\": \"2023-06-05T10:32:30.231\",\n" + + " \"type\": \"ACTIVE\"\n" + + " }\n" + + " ],\n" + + " \"identifiers\": [],\n" + + " \"physicalPostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"SO\",\n" + + " \"postalCode\": \"70327\",\n" + + " \"city\": \"Mogadishu\",\n" + + " \"street\": {\n" + + " \"namePrefix\": null,\n" + + " \"additionalNamePrefix\": null,\n" + + " \"name\": \"Untertuerckheim Strasse 1\",\n" + + " \"additionalNameSuffix\": null,\n" + + " \"houseNumber\": \"1234\",\n" + + " \"milestone\": \"Untertuerckheim Strasse 1\",\n" + + " \"direction\": \"Untertuerckheim Strasse 1\",\n" + + " \"nameSuffix\": null\n" + + " },\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"administrativeAreaLevel2\": null,\n" + + " \"administrativeAreaLevel3\": null,\n" + + " \"district\": \"Stuttgart\",\n" + + " \"companyPostalCode\": \"71034\",\n" + + " \"industrialZone\": \"Sindelfinden\",\n" + + " \"building\": \"Building A\",\n" + + " \"floor\": \"A\",\n" + + " \"door\": \"1\"\n" + + " },\n" + + " \"alternativePostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"DE\",\n" + + " \"postalCode\": \"1234\",\n" + + " \"city\": \"Stuttgart\",\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"deliveryServiceNumber\": \"Untertuerckheim Strasse 1\",\n" + + " \"deliveryServiceType\": \"PO_BOX\",\n" + + " \"deliveryServiceQualifier\": \"test qualifier\"\n" + + " },\n" + + " \"roles\": [],\n" + + " \"externalId\": \"12044444_legalAddress\",\n" + + " \"legalEntityExternalId\": \"12044444\",\n" + + " \"siteExternalId\": null,\n" + + " \"bpn\": \"BPNA000000000001\"\n" + + " },\n" + + " \"externalId\": \"12044444\",\n" + + " \"bpn\": \"BPNL0000000001YN\"\n" + + " },\n" + + " {\n" + + " \"identifiers\": [],\n" + + " \"legalShortName\": \"NoC\",\n" + + " \"legalForm\": \"CUSTOM_LEGAL_FORM\",\n" + + " \"states\": [\n" + + " {\n" + + " \"officialDenotation\": \"Active\",\n" + + " \"validFrom\": \"2020-12-16T05:54:48.942\",\n" + + " \"validTo\": \"2023-06-05T07:31:01.213\",\n" + + " \"type\": \"ACTIVE\"\n" + + " }\n" + + " ],\n" + + " \"classifications\": [\n" + + " {\n" + + " \"value\": \"Farming of cattle, dairy farming\",\n" + + " \"code\": \"01.21\",\n" + + " \"type\": \"NACE\"\n" + + " }\n" + + " ],\n" + + " \"legalNameParts\": [\n" + + " \"Test Company\"\n" + + " ],\n" + + " \"roles\": [],\n" + + " \"legalAddress\": {\n" + + " \"nameParts\": [\n" + + " \"Not real address \"\n" + + " ],\n" + + " \"states\": [\n" + + " {\n" + + " \"description\": \"WESTERN_LATIN_STANDARD\",\n" + + " \"validFrom\": \"2020-12-16T05:54:48.942\",\n" + + " \"validTo\": \"2023-06-05T07:31:01.213\",\n" + + " \"type\": \"ACTIVE\"\n" + + " }\n" + + " ],\n" + + " \"identifiers\": [],\n" + + " \"physicalPostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"ES\",\n" + + " \"postalCode\": \"00000\",\n" + + " \"city\": \"Madrid\",\n" + + " \"street\": {\n" + + " \"namePrefix\": null,\n" + + " \"additionalNamePrefix\": null,\n" + + " \"name\": \"Stuttgarter Strasse\",\n" + + " \"additionalNameSuffix\": null,\n" + + " \"houseNumber\": \"1\",\n" + + " \"milestone\": \"Stuttgarter Strasse 1\",\n" + + " \"direction\": \"Stuttgarter Str.\",\n" + + " \"nameSuffix\": null\n" + + " },\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"administrativeAreaLevel2\": \"test1\",\n" + + " \"administrativeAreaLevel3\": \"test2\",\n" + + " \"district\": \"Stuttgart\",\n" + + " \"companyPostalCode\": \"GM01\",\n" + + " \"industrialZone\": \"HEADQUARTER\",\n" + + " \"building\": \"Building A\",\n" + + " \"floor\": \"A\",\n" + + " \"door\": \"test\"\n" + + " },\n" + + " \"alternativePostalAddress\": {\n" + + " \"geographicCoordinates\": {\n" + + " \"longitude\": 0.0,\n" + + " \"latitude\": 0.0,\n" + + " \"altitude\": 0.0\n" + + " },\n" + + " \"country\": \"DE\",\n" + + " \"postalCode\": \"1234\",\n" + + " \"city\": \"Stuttgart 1\",\n" + + " \"administrativeAreaLevel1\": null,\n" + + " \"deliveryServiceNumber\": \"1234\",\n" + + " \"deliveryServiceType\": \"PO_BOX\",\n" + + " \"deliveryServiceQualifier\": \"test\"\n" + + " },\n" + + " \"roles\": [],\n" + + " \"externalId\": \"test-cr_legalAddress\",\n" + + " \"legalEntityExternalId\": \"test-cr\",\n" + + " \"siteExternalId\": null,\n" + + " \"bpn\": \"BPNA000000000003\"\n" + + " },\n" + + " \"externalId\": \"test-cr\",\n" + + " \"bpn\": \"BPNL0000000001Y2\"\n" + + " }\n" + + " ]\n" + + "}"))); + } + + + + } diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java new file mode 100644 index 00000000..9bca3a40 --- /dev/null +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java @@ -0,0 +1,92 @@ +/******************************************************************************** + * Copyright (c) 2022,2023 BMW Group AG + * Copyright (c) 2022,2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ +package org.eclipse.tractusx.valueaddedservice.utils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; + +public class DataBaseJsonConverterTest { + + @InjectMocks + private DataBaseJsonConverter dataBaseJsonConverter; + + @Mock + private ObjectMapper objectMapper; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + + /** + * Should return null when a null JSON string is provided + */ + @Test + public void convertToEntityAttributeWithNullJsonString() { + String customerInfoJSON = null; + + Map result = dataBaseJsonConverter.convertToEntityAttribute(customerInfoJSON); + + assertNull(result); + } + + + + + + @Test + public void testConvertToDatabaseColumn() throws JsonProcessingException { + Map customerInfo = new HashMap<>(); + customerInfo.put("key", "value"); + + when(objectMapper.writeValueAsString(customerInfo)).thenReturn("{\"key\":\"value\"}"); + + String result = dataBaseJsonConverter.convertToDatabaseColumn(customerInfo); + + assertEquals("{\"key\":\"value\"}", result); + } + + + @Test + public void testConvertToDatabaseColumnException() throws JsonProcessingException { + Map customerInfo = new HashMap<>(); + customerInfo.put("key", "value"); + + when(objectMapper.writeValueAsString(customerInfo)).thenThrow(new JsonProcessingException("Exception") { + }); + + String result = dataBaseJsonConverter.convertToDatabaseColumn(customerInfo); + + assertNull(result); + } +} diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/MockUtilsTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/MockUtilsTest.java new file mode 100644 index 00000000..9d7a7c3e --- /dev/null +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/MockUtilsTest.java @@ -0,0 +1,58 @@ +/******************************************************************************** +* Copyright (c) 2022,2023 BMW Group AG +* Copyright (c) 2022,2023 Contributors to the Eclipse Foundation +* +* See the NOTICE file(s) distributed with this work for additional +* information regarding copyright ownership. +* +* This program and the accompanying materials are made available under the +* terms of the Apache License, Version 2.0 which is available at +* https://www.apache.org/licenses/LICENSE-2.0. +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +* License for the specific language governing permissions and limitations +* under the License. +* +* SPDX-License-Identifier: Apache-2.0 +********************************************************************************/ +package org.eclipse.tractusx.valueaddedservice.utils; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.github.tomakehurst.wiremock.WireMockServer; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.tractusx.valueaddedservice.service.mocks.ConfigServerMock; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; + +import java.util.ArrayList; +import java.util.List; + +@Slf4j +public class MockUtilsTest { + public static WireMockServer wireMockServer; + + @BeforeAll + public static void beforeAll() { + try { + log.info("Opening Mock Server"); + wireMockServer = ConfigServerMock.openPort(wireMockServer); + } catch (InterruptedException e) { + log.info("Error on opening port {} {}",e.getMessage(),e.getCause()); + throw new RuntimeException(e); + } + } + + @BeforeEach + public void openPorts() throws JsonProcessingException { + List list = new ArrayList<>(); + list.add("oneElement"); + ConfigServerMock.mocKConnectionToBpdmGateAddresses(wireMockServer); + ConfigServerMock.mocKConnectionToBpdmGateLegalEntity(wireMockServer); + ConfigServerMock.mocKConnectionToBpdmGateSite(wireMockServer); + ConfigServerMock.mocKConnectionToExternalBpnApi(wireMockServer, list); + ConfigServerMock.mocKConnectionToExternalBpnApiError(wireMockServer); + } + +} diff --git a/src/test/resources/config/application.yml b/src/test/resources/config/application.yml index 05a01a5c..42e6d39d 100644 --- a/src/test/resources/config/application.yml +++ b/src/test/resources/config/application.yml @@ -62,4 +62,7 @@ application: name: default host: project-value-added-service-vas/api/dashboard partnersPoolUrl: - legalEntities: 'http://localhost:8080/api/catena/legal-entities' \ No newline at end of file + bpdmAddressUrl: 'http://localhost:8585/companies/test-company/api/catena/output/addresses/search?' + bpdmSiteUrl: 'http://localhost:8585/companies/test-company/api/catena/output/sites/search?' + bpdmLegalUrl: 'http://localhost:8585/companies/test-company/api/catena/output/legal-entities/search?' + clientId: 'test-crisk' \ No newline at end of file From 8bd56942c3e33a69cdf7ce914edf11b519425a4f Mon Sep 17 00:00:00 2001 From: "fabio.d.mota" Date: Fri, 7 Jul 2023 14:06:17 +0100 Subject: [PATCH 4/6] feat(Country Risk): feat: Change name for sonar project on sonar cloud --- .github/workflows/sonar-scan.yml | 10 +++++++++- pom.xml | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sonar-scan.yml b/.github/workflows/sonar-scan.yml index e5605321..eff70808 100644 --- a/.github/workflows/sonar-scan.yml +++ b/.github/workflows/sonar-scan.yml @@ -37,8 +37,16 @@ jobs: key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar + - name: Set Sonar Project Name + run: | + if [[ "${{ github.repository }}" == "eclipse-tractusx/vas-country-risk-backend" ]]; then + echo "SONAR_PROJECT_NAME=vas-country-risk-backend" >> $GITHUB_ENV + else + echo "SONAR_PROJECT_NAME=tx-vas-country-risk-backend" >> $GITHUB_ENV + fi + - name: Build and analyze env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar + run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectName=$SONAR_PROJECT_NAME diff --git a/pom.xml b/pom.xml index 313b212d..680321f6 100644 --- a/pom.xml +++ b/pom.xml @@ -49,7 +49,7 @@ ${project.reporting.outputDirectory}/target/jacoco-report/jacoco.xml catenax-ng catenax-ng_tx-vas-country-risk-backend - tx-vas-country-risk-backend + vas-country-risk-backend src/main/java/org/eclipse/tractusx/valueaddedservice/dto//.,src/main/java/org/eclipse/tractusx/valueaddedservice/domain//.¨ 0.8.7 2.5.1.0 From 5302fc1e03e3aa3423f1c1c6d8e489e14779978a Mon Sep 17 00:00:00 2001 From: "fabio.d.mota" Date: Mon, 10 Jul 2023 11:02:14 +0100 Subject: [PATCH 5/6] feat(Country Risk): Replace RestTemplate with WebClient This commit replaces the use of RestTemplate with WebClient for non-blocking HTTP requests. --- CHANGELOG.md | 2 + pom.xml | 21 +++++++- .../config/ApplicationVariables.java | 41 +++++++-------- .../config/RestTemplateConfiguration.java | 33 ------------ .../config/WebClientConfiguration.java | 51 +++++++++++++++++++ .../dto/AuthPropertiesDTO.java | 2 +- .../interceptors/TokenAspect.java | 51 +++++++++---------- .../logic/BusinessPartnersLogicService.java | 7 ++- .../service/logic/InvokeService.java | 30 ++++++----- src/main/resources/config/application-dev.yml | 4 ++ .../resources/config/application-local.yml | 2 +- src/main/resources/config/application.yml | 20 +++++--- .../rest/BPNIntegartionTest.java | 5 ++ .../service/InvokeServiceTest.java | 8 +-- src/test/resources/config/application.yml | 40 +++++++++++---- 15 files changed, 194 insertions(+), 123 deletions(-) delete mode 100644 src/main/java/org/eclipse/tractusx/valueaddedservice/config/RestTemplateConfiguration.java create mode 100644 src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 27b146e7..4e76896c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Map Between API and New Data Model for getting Suppliers and Customers +- Changed restTemplate to WebClient for new +- Replaced RestTemplate with WebClient for non-blocking HTTP requests ## [1.1.1] - 2023-05-16 diff --git a/pom.xml b/pom.xml index 680321f6..3d12f5e7 100644 --- a/pom.xml +++ b/pom.xml @@ -53,7 +53,9 @@ src/main/java/org/eclipse/tractusx/valueaddedservice/dto//.,src/main/java/org/eclipse/tractusx/valueaddedservice/domain//.¨ 0.8.7 2.5.1.0 - 3.0.1 + 3.0.4 + 2.5.1.RELEASE + 2.5.1 6.0.3 42.5.1 @@ -190,7 +192,24 @@ org.springframework.boot spring-boot-starter-oauth2-resource-server ${spring-boot-starter-oauth2-resource-server} + + + + org.springframework.boot + spring-boot-starter-oauth2-client + ${spring-boot-starter-oauth2-resource-server} + + + org.springframework.boot + spring-boot-starter-webflux + ${spring-boot-starter-webflux-version} + + + + org.springframework.security.oauth + spring-security-oauth2 + ${spring-boot-starter-oauth2} diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java index f7b62547..8ab23b72 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ApplicationVariables.java @@ -1,22 +1,22 @@ /******************************************************************************** -* Copyright (c) 2022,2023 BMW Group AG -* Copyright (c) 2022,2023 Contributors to the Eclipse Foundation -* -* See the NOTICE file(s) distributed with this work for additional -* information regarding copyright ownership. -* -* This program and the accompanying materials are made available under the -* terms of the Apache License, Version 2.0 which is available at -* https://www.apache.org/licenses/LICENSE-2.0. -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -* License for the specific language governing permissions and limitations -* under the License. -* -* SPDX-License-Identifier: Apache-2.0 -********************************************************************************/ + * Copyright (c) 2022,2023 BMW Group AG + * Copyright (c) 2022,2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.config; import com.fasterxml.jackson.core.JsonProcessingException; @@ -24,7 +24,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.eclipse.tractusx.valueaddedservice.constants.VasConstants; import org.eclipse.tractusx.valueaddedservice.dto.AuthPropertiesDTO; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Base64; @@ -32,9 +31,6 @@ @Component public class ApplicationVariables { - @Value("${application.clientId}") - private String clientId; - private String token; private AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); @@ -61,7 +57,6 @@ public void decodeJWT() throws JsonProcessingException { Base64.Decoder decoder = Base64.getUrlDecoder(); String header = new String(decoder.decode(chunks[1])); this.authPropertiesDTO = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).readValue(header, AuthPropertiesDTO.class); - this.authPropertiesDTO.setClientResource(clientId); this.authPropertiesDTO.getRoles(this.authPropertiesDTO.getClientResource()); } diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/RestTemplateConfiguration.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/RestTemplateConfiguration.java deleted file mode 100644 index d2bbd5b9..00000000 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/RestTemplateConfiguration.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************** -* Copyright (c) 2022,2023 BMW Group AG -* Copyright (c) 2022,2023 Contributors to the Eclipse Foundation -* -* See the NOTICE file(s) distributed with this work for additional -* information regarding copyright ownership. -* -* This program and the accompanying materials are made available under the -* terms of the Apache License, Version 2.0 which is available at -* https://www.apache.org/licenses/LICENSE-2.0. -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -* License for the specific language governing permissions and limitations -* under the License. -* -* SPDX-License-Identifier: Apache-2.0 -********************************************************************************/ -package org.eclipse.tractusx.valueaddedservice.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.client.RestTemplate; - -@Configuration -public class RestTemplateConfiguration { - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } -} diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java new file mode 100644 index 00000000..c86f0299 --- /dev/null +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java @@ -0,0 +1,51 @@ +package org.eclipse.tractusx.valueaddedservice.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder; +import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction; +import org.springframework.web.reactive.function.client.WebClient; + +@Configuration +public class WebClientConfiguration { + + @Value("${security.enabled}") + private boolean isSecurityEnabled; + + @Value("${vas.clientName}") + private String clientName; + + + @Bean + @ConditionalOnProperty(prefix = "security", name = "enabled", havingValue = "true") + public WebClient webClient(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) { + OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build(); + AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, authorizedClientService); + authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); + + ServletOAuth2AuthorizedClientExchangeFilterFunction oauth = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); + oauth.setDefaultClientRegistrationId(clientName); + return WebClient.builder() + .apply(oauth.oauth2Configuration()) + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .build(); + } + + @Bean + @ConditionalOnProperty(prefix = "security", name = "enabled", havingValue = "false") + public WebClient webClientNoAuth() { + return WebClient.builder().build(); + + } + + +} + diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/AuthPropertiesDTO.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/AuthPropertiesDTO.java index b603cc2f..6751abb5 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/AuthPropertiesDTO.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/dto/AuthPropertiesDTO.java @@ -60,7 +60,7 @@ public class AuthPropertiesDTO implements Serializable { @Schema(example = "\"CX-CRISK\":{\"roles\":[\"GetUser\"]}") @NotNull @JsonProperty("resource_access") - private Object resourceAccess = ""; + private Object resourceAccess = new LinkedHashMap<>(); @Schema(example = "12XRisk") @NotNull diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/interceptors/TokenAspect.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/interceptors/TokenAspect.java index 6a118b03..8467a214 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/interceptors/TokenAspect.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/interceptors/TokenAspect.java @@ -79,38 +79,37 @@ public void restController() { @Before("restController()") public void validateToken() throws JsonProcessingException { - - // Get the specific header attribute - HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); - Enumeration headerValues = request.getHeaders(VasConstants.HEADERS_BEARER_TOKEN); - - // If exists the Header attribute, validate if it is correct - if (headerValues.hasMoreElements()) { - String token = headerValues.nextElement(); - applicationVariables.setToken(token); - + if (env.getProperty("security.enabled") != null && Boolean.parseBoolean(env.getProperty("security.enabled"))) { + // Get the specific header attribute + HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); + Enumeration headerValues = request.getHeaders(VasConstants.HEADERS_BEARER_TOKEN); + + // If exists the Header attribute, validate if it is correct + if (headerValues.hasMoreElements()) { + String token = headerValues.nextElement(); + applicationVariables.setToken(token); + } } - - } @Before("restController()") public void validateUserAndTokenAreTheSame() { - HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); - CompanyUserDTO companyUserDTO = new CompanyUserDTO(); - companyUserDTO.setName(request.getParameter(VasConstants.REQUEST_USER_NAME) != null ? request.getParameter(VasConstants.REQUEST_USER_NAME) : ""); - companyUserDTO.setCompanyName(request.getParameter(VasConstants.REQUEST_COMPANY_NAME) != null ? request.getParameter(VasConstants.REQUEST_COMPANY_NAME) : ""); - companyUserDTO.setEmail(request.getParameter(VasConstants.REQUEST_USER_EMAIL) != null ? request.getParameter(VasConstants.REQUEST_USER_EMAIL) : ""); - if (companyUserDTO.getName() == null || companyUserDTO.getName().isEmpty() - || companyUserDTO.getEmail() == null || companyUserDTO.getEmail().isEmpty() - || companyUserDTO.getCompanyName() == null || companyUserDTO.getCompanyName().isEmpty()) { - throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, VasConstants.VALIDATE_COMPANY_USER); - } - if (env.getProperty("security.enabled") != null && Boolean.valueOf(env.getProperty("security.enabled")) - && !companyUserLogicService.validateUserAndTokenAreTheSame(companyUserDTO) && !companyUserLogicService.isAdmin()) { - throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + if (env.getProperty("security.enabled") != null && Boolean.parseBoolean(env.getProperty("security.enabled"))) { + HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); + CompanyUserDTO companyUserDTO = new CompanyUserDTO(); + companyUserDTO.setName(request.getParameter(VasConstants.REQUEST_USER_NAME) != null ? request.getParameter(VasConstants.REQUEST_USER_NAME) : ""); + companyUserDTO.setCompanyName(request.getParameter(VasConstants.REQUEST_COMPANY_NAME) != null ? request.getParameter(VasConstants.REQUEST_COMPANY_NAME) : ""); + companyUserDTO.setEmail(request.getParameter(VasConstants.REQUEST_USER_EMAIL) != null ? request.getParameter(VasConstants.REQUEST_USER_EMAIL) : ""); + if (companyUserDTO.getName() == null || companyUserDTO.getName().isEmpty() + || companyUserDTO.getEmail() == null || companyUserDTO.getEmail().isEmpty() + || companyUserDTO.getCompanyName() == null || companyUserDTO.getCompanyName().isEmpty()) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, VasConstants.VALIDATE_COMPANY_USER); + } + if (!companyUserLogicService.validateUserAndTokenAreTheSame(companyUserDTO) && !companyUserLogicService.isAdmin()) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); + } } - } + } \ No newline at end of file diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java index f889edfb..39d189d6 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/BusinessPartnersLogicService.java @@ -74,7 +74,6 @@ public List getExternalBusinessPartners(CompanyUserDTO compa var headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); - headers.setBearerAuth(token); String body = "[]"; HttpEntity httpEntity = new HttpEntity<>(body, headers); @@ -82,16 +81,16 @@ public List getExternalBusinessPartners(CompanyUserDTO compa Map externalIdToLegalName = new HashMap<>(); // Call the first endpoint and create the DTOs - List businessPartnerDTOS = invokeService.executeRequest(bpdmLegalUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)); + List businessPartnerDTOS = invokeService.executeRequest(bpdmLegalUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)).block(); // Call the second endpoint and create the DTOs, but only if the externalId is not already present in the existing DTOs - List businessPartnerDTOS2 = invokeService.executeRequest(bpdmAddressUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)); + List businessPartnerDTOS2 = invokeService.executeRequest(bpdmAddressUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)).block(); businessPartnerDTOS2.removeIf(dto -> isExternalIdPresent(dto.getBpn(), businessPartnerDTOS)); businessPartnerDTOS.addAll(businessPartnerDTOS2); businessPartnerDTOS2.clear(); // Call the third endpoint and create the DTOs, but only if the externalId is not already present in the existing DTOs - businessPartnerDTOS2 = invokeService.executeRequest(bpdmSiteUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)); + businessPartnerDTOS2 = invokeService.executeRequest(bpdmSiteUrl, HttpMethod.POST, httpEntity, BusinessPartnerDTO.class, json -> customMappingLogic(json, externalIdToLegalName)).block(); businessPartnerDTOS2.removeIf(dto -> isExternalIdPresent(dto.getBpn(), businessPartnerDTOS)); businessPartnerDTOS.addAll(businessPartnerDTOS2); diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java index 84c45f29..80492a6f 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/service/logic/InvokeService.java @@ -23,10 +23,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.List; @@ -37,17 +37,21 @@ public class InvokeService { @Autowired - RestTemplate restTemplate; + WebClient webClient; - public List executeRequest(String url, HttpMethod httpMethod, HttpEntity httpEntity, Class responseType, Function> mappingFunction) { - try { - ResponseEntity responseEntity = restTemplate.exchange(url, httpMethod, httpEntity, String.class); - String json = responseEntity.getBody(); - return mappingFunction.apply(json); - } catch (HttpClientErrorException e) { - log.error("error url {} message {}", url, e.getMessage()); - return new ArrayList<>(); - } + public Mono> executeRequest(String url, HttpMethod httpMethod, HttpEntity httpEntity, Class responseType, Function> mappingFunction) { + return webClient.method(httpMethod) + .uri(url) + .headers(headers -> headers.addAll(httpEntity.getHeaders())) + .body(BodyInserters.fromValue(httpEntity.getBody())) + .retrieve() + .bodyToMono(String.class) + .map(mappingFunction) + .onErrorResume(e -> { + log.error("error url {} message {}", url, e.getMessage()); + return Mono.just(new ArrayList<>()); + }); } } + diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml index 30f798b9..4cc1f99c 100644 --- a/src/main/resources/config/application-dev.yml +++ b/src/main/resources/config/application-dev.yml @@ -25,6 +25,10 @@ vas: jwk-set-uri: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/certs auth-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/auth +spring: + config: + activate: + on-profile: dev application: diff --git a/src/main/resources/config/application-local.yml b/src/main/resources/config/application-local.yml index 2781cc9e..336152ae 100644 --- a/src/main/resources/config/application-local.yml +++ b/src/main/resources/config/application-local.yml @@ -62,4 +62,4 @@ application: bpdmLegalUrl: 'http://localhost:8082/api/catena/output/legal-entities/search?size=100' server: - port: 9090 \ No newline at end of file + port: 8080 \ No newline at end of file diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index 0b77501f..54c75a49 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -30,8 +30,11 @@ vas: host: localhost user: default pass: defaultpassword - keycloakClientSecret: - keycloakClientId: + + keycloak: + clientId: + clientSecret: + clientName: country-risk-client authentication-url: token-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/token jwk-set-uri: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/certs @@ -54,8 +57,13 @@ spring: registration: keycloak: authorization-grant-type: client_credentials - client-id: ${vas_keycloakClientId} - client-secret: ${vas_keycloakClientSecret} + client-id: ${vas.keycloak.clientId} + client-secret: ${vas.keycloak.clientSecret} + country-risk-client: + authorization-grant-type: client_credentials + client-id: ${vas.keycloak.clientId} + client-secret: ${vas.keycloak.clientSecret} + provider: keycloak provider: keycloak: token-uri: ${vas.authentication-url.token-url} @@ -93,9 +101,9 @@ application: host: project-value-added-service-vas/api/dashboard partnersPoolUrl: bpdmAddressUrl: 'http://localhost:8082/api/catena/output/addresses/search?size=100' + bpdmLegalUrl: 'http://localhost:8082/api/catena/output/addresses/search?size=100' bpdmSiteUrl: 'http://localhost:8082/api/catena/output/sites/search?size=100' - bpdmLegalUrl: 'http://localhost:8082/api/catena/output/legal-entities/search?size=100' - clientId: 'app374' + management: endpoints: diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java index 8c4451ff..bfe19155 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/rest/BPNIntegartionTest.java @@ -45,6 +45,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; +import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.web.util.UriTemplate; @@ -82,6 +83,10 @@ class BPNIntegartionTest { @MockBean ApplicationVariables applicationVariables; + @MockBean + ClientRegistrationRepository clientRegistrationRepository; + + MockUtilsTest mockUtilsTest; @BeforeAll diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java index 89e38f3a..9bca2490 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/InvokeServiceTest.java @@ -70,10 +70,10 @@ void executeRequestWhenRequestIsSuccessThenReturnResponse() throws JsonProcessin String url = "http://localhost:8585/api/dashboard/v1/users"; HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); - HttpEntity httpEntity = new HttpEntity<>(httpHeaders); + HttpEntity httpEntity = new HttpEntity<>("",httpHeaders); List response = - invokeService.executeRequest(url, HttpMethod.GET, httpEntity, String.class, this::mockMappingFunction); + invokeService.executeRequest(url, HttpMethod.GET, httpEntity, String.class, this::mockMappingFunction).block(); assertNotEquals(0, response.size()); } @@ -83,8 +83,8 @@ void executeRequestWhenRequestIsFailedThenReturnEmptyList() throws JsonProcessin String url = "http://localhost:8585/api/dashboard/v1/usersError"; HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); - HttpEntity httpEntity = new HttpEntity<>(httpHeaders); - List newEmptyList = invokeService.executeRequest(url, HttpMethod.GET, httpEntity, String.class, this::mockMappingFunction); + HttpEntity httpEntity = new HttpEntity<>("",httpHeaders); + List newEmptyList = invokeService.executeRequest(url, HttpMethod.GET, httpEntity, String.class, this::mockMappingFunction).block(); assertEquals(0, newEmptyList.size()); } diff --git a/src/test/resources/config/application.yml b/src/test/resources/config/application.yml index 42e6d39d..e9949c12 100644 --- a/src/test/resources/config/application.yml +++ b/src/test/resources/config/application.yml @@ -18,6 +18,19 @@ # SPDX-License-Identifier: Apache-2.0 #*******************************************************************************/ +vas: + datasource: + host: localhost + user: default + pass: defaultpassword + keycloakClientSecret: defautlSecret + keycloakClientId: country-risk-client + clientName: country-risk-client + authentication-url: + token-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/token + jwk-set-uri: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/certs + auth-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/auth + # Spring Boot configuration spring: config: @@ -32,18 +45,23 @@ server: relaxedPathChars: "|,{,},[,]" relaxedQueryChars: "|,{,},[,]" max-http-header-size: 40KB + security: + oauth2: + client: + registration: + keycloak: + authorization-grant-type: client_credentials + client-id: ${vas_keycloakClientId} + client-secret: ${vas_keycloakClientSecret} + country-risk-client: + authorization-grant-type: client_credentials + client-id: ${vas_keycloakClientId} + client-secret: ${vas_keycloakClientSecret} + provider: keycloak + provider: + keycloak: + token-uri: ${vas.authentication-url.token-url} -vas: - datasource: - host: localhost - user: default - pass: defaultpassword - keycloakClientSecret: - keycloakClientId: - authentication-url: - token-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/token - jwk-set-uri: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/certs - auth-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/auth bearer_token: From 2a490b1eb1b8b875565dff0f4cc66a81f516dcd1 Mon Sep 17 00:00:00 2001 From: "fabio.d.mota" Date: Wed, 12 Jul 2023 14:58:21 +0100 Subject: [PATCH 6/6] fix(Country Risk): Update DEPENDENCIES file , optimize and remove hardcoded urls, add license header for classes --- CHANGELOG.md | 1 + DEPENDENCIES | 49 +++++++++++--- pom.xml | 2 +- .../config/ObjectMapperConfig.java | 2 +- .../config/WebClientConfiguration.java | 19 ++++++ src/main/resources/config/application-dev.yml | 12 +--- src/main/resources/config/application-int.yml | 11 +--- src/main/resources/config/application.yml | 8 ++- .../logic/CountryLogicServiceTest.java | 65 +++++++++---------- .../utils/DataBaseJsonConverterTest.java | 3 - 10 files changed, 101 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e76896c..88d20bff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Map Between API and New Data Model for getting Suppliers and Customers - Changed restTemplate to WebClient for new - Replaced RestTemplate with WebClient for non-blocking HTTP requests +- Updated Dependencies file ## [1.1.1] - 2023-05-16 diff --git a/DEPENDENCIES b/DEPENDENCIES index dadc7a28..3e0362dd 100644 --- a/DEPENDENCIES +++ b/DEPENDENCIES @@ -10,7 +10,10 @@ maven/mavencentral/com.fasterxml.jackson.module/jackson-module-parameter-names/2 maven/mavencentral/com.fasterxml/classmate/1.5.1, Apache-2.0, approved, clearlydefined maven/mavencentral/com.github.stephenc.jcip/jcip-annotations/1.0-1, Apache-2.0, approved, CQ21949 maven/mavencentral/com.google.code.findbugs/jsr305/3.0.2, Apache-2.0, approved, #20 +maven/mavencentral/com.nimbusds/content-type/2.2, Apache-2.0, approved, clearlydefined +maven/mavencentral/com.nimbusds/lang-tag/1.7, Apache-2.0, approved, clearlydefined maven/mavencentral/com.nimbusds/nimbus-jose-jwt/9.24.4, Apache-2.0, approved, clearlydefined +maven/mavencentral/com.nimbusds/oauth2-oidc-sdk/9.43.1, Apache-2.0, approved, clearlydefined maven/mavencentral/com.opencsv/opencsv/5.7.1, Apache-2.0, approved, clearlydefined maven/mavencentral/com.zaxxer/HikariCP/5.0.1, Apache-2.0, approved, clearlydefined maven/mavencentral/commons-beanutils/commons-beanutils/1.9.4, Apache-2.0, approved, CQ12654 @@ -26,6 +29,26 @@ maven/mavencentral/io.hypersistence/hypersistence-utils-hibernate-60/3.1.0, Apac maven/mavencentral/io.micrometer/micrometer-commons/1.10.6, Apache-2.0 AND (Apache-2.0 AND MIT), approved, #7333 maven/mavencentral/io.micrometer/micrometer-core/1.10.6, Apache-2.0 AND (Apache-2.0 AND MIT), approved, #6977 maven/mavencentral/io.micrometer/micrometer-observation/1.10.6, Apache-2.0, approved, #7331 +maven/mavencentral/io.netty/netty-buffer/4.1.91.Final, Apache-2.0, approved, CQ21842 +maven/mavencentral/io.netty/netty-codec-dns/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-codec-http/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-codec-http2/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-codec-socks/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-codec/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-common/4.1.91.Final, Apache-2.0 AND MIT AND CC0-1.0, approved, CQ21843 +maven/mavencentral/io.netty/netty-handler-proxy/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-handler/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-resolver-dns-classes-macos/4.1.91.Final, Apache-2.0, approved, #6367 +maven/mavencentral/io.netty/netty-resolver-dns-native-macos/4.1.91.Final, Apache-2.0, approved, #7004 +maven/mavencentral/io.netty/netty-resolver-dns/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-resolver/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-transport-classes-epoll/4.1.91.Final, Apache-2.0, approved, #6366 +maven/mavencentral/io.netty/netty-transport-native-epoll/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-transport-native-unix-common/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.netty/netty-transport/4.1.91.Final, Apache-2.0 AND BSD-3-Clause AND MIT, approved, CQ20926 +maven/mavencentral/io.projectreactor.netty/reactor-netty-core/1.1.6, Apache-2.0, approved, #5946 +maven/mavencentral/io.projectreactor.netty/reactor-netty-http/1.1.6, Apache-2.0, approved, #6999 +maven/mavencentral/io.projectreactor/reactor-core/3.5.5, Apache-2.0, approved, #5934 maven/mavencentral/io.swagger.core.v3/swagger-annotations-jakarta/2.2.7, Apache-2.0, approved, #5947 maven/mavencentral/io.swagger.core.v3/swagger-core-jakarta/2.2.7, Apache-2.0, approved, #5929 maven/mavencentral/io.swagger.core.v3/swagger-models-jakarta/2.2.7, Apache-2.0, approved, #5919 @@ -38,6 +61,8 @@ maven/mavencentral/jakarta.xml.bind/jakarta.xml.bind-api/4.0.0, BSD-3-Clause, ap maven/mavencentral/javax.activation/javax.activation-api/1.2.0, (CDDL-1.1 OR GPL-2.0 WITH Classpath-exception-2.0) AND Apache-2.0, approved, CQ18740 maven/mavencentral/javax.validation/validation-api/2.0.1.Final, Apache-2.0, approved, CQ15302 maven/mavencentral/javax.xml.bind/jaxb-api/2.3.1, CDDL-1.1 OR GPL-2.0-only WITH Classpath-exception-2.0, approved, CQ16911 +maven/mavencentral/net.minidev/accessors-smart/2.4.9, Apache-2.0, approved, #7515 +maven/mavencentral/net.minidev/json-smart/2.4.10, Apache-2.0, approved, #3288 maven/mavencentral/net.sourceforge.htmlunit/neko-htmlunit/2.66.0, Apache-2.0, approved, clearlydefined maven/mavencentral/org.apache-extras.beanshell/bsh/2.0b6, Apache-2.0, approved, #1990 maven/mavencentral/org.apache.commons/commons-collections4/4.4, Apache-2.0, approved, clearlydefined @@ -57,7 +82,7 @@ maven/mavencentral/org.apache.xmlgraphics/batik-i18n/1.16, Apache-2.0, approved, maven/mavencentral/org.apache.xmlgraphics/batik-shared-resources/1.16, Apache-2.0, approved, #4290 maven/mavencentral/org.apache.xmlgraphics/batik-util/1.16, Apache-2.0, approved, #4279 maven/mavencentral/org.apache.xmlgraphics/xmlgraphics-commons/2.7, Apache-2.0, approved, #3367 -maven/mavencentral/org.apiguardian/apiguardian-api/1.1.2, Apache-2.0, approved, clearlydefined +maven/mavencentral/org.apiguardian/apiguardian-api/1.1.0, Apache-2.0, approved, clearlydefined maven/mavencentral/org.aspectj/aspectjweaver/1.9.19, EPL-1.0, approved, tools.aspectj maven/mavencentral/org.bouncycastle/bcpkix-jdk15on/1.69, MIT, approved, clearlydefined maven/mavencentral/org.bouncycastle/bcprov-jdk15on/1.69, MIT, approved, clearlydefined @@ -68,10 +93,12 @@ maven/mavencentral/org.jboss.logging/jboss-logging/3.5.0.Final, Apache-2.0, appr maven/mavencentral/org.liquibase/liquibase-core/4.18.0, Apache-2.0, approved, clearlydefined maven/mavencentral/org.mapstruct/mapstruct/1.5.3.Final, Apache-2.0, approved, #6277 maven/mavencentral/org.openapitools/jackson-databind-nullable/0.2.4, Apache-2.0, approved, #3294 +maven/mavencentral/org.ow2.asm/asm/9.3, BSD-3-Clause, approved, clearlydefined maven/mavencentral/org.owasp.antisamy/antisamy/1.7.2, BSD-3-Clause, approved, clearlydefined maven/mavencentral/org.owasp.esapi/esapi/2.5.1.0, BSD-3-Clause AND CC-BY-SA-3.0 AND LicenseRef-Public-Domain, approved, #6274 maven/mavencentral/org.postgresql/postgresql/42.5.1, BSD-2-Clause, approved, #3416 maven/mavencentral/org.projectlombok/lombok/1.18.24, MIT AND LicenseRef-Public-Domain, approved, CQ23907 +maven/mavencentral/org.reactivestreams/reactive-streams/1.0.4, CC0-1.0, approved, CQ16332 maven/mavencentral/org.slf4j/jul-to-slf4j/2.0.7, MIT, approved, #7698 maven/mavencentral/org.slf4j/slf4j-api/2.0.7, MIT, approved, #5915 maven/mavencentral/org.springdoc/springdoc-openapi-starter-common/2.0.2, Apache-2.0, approved, #5920 @@ -87,10 +114,13 @@ maven/mavencentral/org.springframework.boot/spring-boot-starter-data-jpa/3.0.6, maven/mavencentral/org.springframework.boot/spring-boot-starter-jdbc/3.0.6, Apache-2.0, approved, #6974 maven/mavencentral/org.springframework.boot/spring-boot-starter-json/3.0.6, Apache-2.0, approved, #7006 maven/mavencentral/org.springframework.boot/spring-boot-starter-logging/3.0.6, Apache-2.0, approved, #6982 -maven/mavencentral/org.springframework.boot/spring-boot-starter-oauth2-resource-server/3.0.1, Apache-2.0, approved, #6967 +maven/mavencentral/org.springframework.boot/spring-boot-starter-oauth2-client/3.0.4, Apache-2.0, approved, #5932 +maven/mavencentral/org.springframework.boot/spring-boot-starter-oauth2-resource-server/3.0.4, Apache-2.0, approved, #6967 +maven/mavencentral/org.springframework.boot/spring-boot-starter-reactor-netty/3.0.6, Apache-2.0, approved, #6989 maven/mavencentral/org.springframework.boot/spring-boot-starter-tomcat/3.0.6, Apache-2.0, approved, #6987 maven/mavencentral/org.springframework.boot/spring-boot-starter-validation/3.0.6, Apache-2.0, approved, #6971 maven/mavencentral/org.springframework.boot/spring-boot-starter-web/3.0.6, Apache-2.0, approved, #5945 +maven/mavencentral/org.springframework.boot/spring-boot-starter-webflux/2.5.1, Apache-2.0, approved, clearlydefined maven/mavencentral/org.springframework.boot/spring-boot-starter/3.0.6, Apache-2.0, approved, #7330 maven/mavencentral/org.springframework.boot/spring-boot/3.0.6, Apache-2.0, approved, #7327 maven/mavencentral/org.springframework.cloud/spring-cloud-commons/3.1.5, Apache-2.0, approved, #4726 @@ -99,9 +129,11 @@ maven/mavencentral/org.springframework.cloud/spring-cloud-starter-bootstrap/3.1. maven/mavencentral/org.springframework.cloud/spring-cloud-starter/3.1.5, Apache-2.0, approved, #4723 maven/mavencentral/org.springframework.data/spring-data-commons/3.0.5, Apache-2.0, approved, #5943 maven/mavencentral/org.springframework.data/spring-data-jpa/3.0.5, Apache-2.0, approved, #5935 +maven/mavencentral/org.springframework.security.oauth/spring-security-oauth2/2.5.1.RELEASE, Apache-2.0, approved, clearlydefined maven/mavencentral/org.springframework.security/spring-security-config/6.0.3, Apache-2.0, approved, #7338 maven/mavencentral/org.springframework.security/spring-security-core/6.0.3, Apache-2.0, approved, #7325 maven/mavencentral/org.springframework.security/spring-security-crypto/6.0.3, Apache-2.0 AND ISC, approved, #7326 +maven/mavencentral/org.springframework.security/spring-security-oauth2-client/6.0.3, Apache-2.0, approved, #5931 maven/mavencentral/org.springframework.security/spring-security-oauth2-core/6.0.3, Apache-2.0, approved, #7324 maven/mavencentral/org.springframework.security/spring-security-oauth2-jose/6.0.3, Apache-2.0, approved, #7337 maven/mavencentral/org.springframework.security/spring-security-oauth2-resource-server/6.0.3, Apache-2.0, approved, #7335 @@ -119,16 +151,17 @@ maven/mavencentral/org.springframework/spring-jdbc/6.0.8, Apache-2.0, approved, maven/mavencentral/org.springframework/spring-orm/6.0.8, Apache-2.0, approved, #5925 maven/mavencentral/org.springframework/spring-tx/6.0.8, Apache-2.0, approved, #5926 maven/mavencentral/org.springframework/spring-web/6.0.8, Apache-2.0, approved, #5942 +maven/mavencentral/org.springframework/spring-webflux/6.0.8, Apache-2.0, approved, #6964 maven/mavencentral/org.springframework/spring-webmvc/6.0.8, Apache-2.0, approved, #5944 maven/mavencentral/org.webjars/swagger-ui/4.15.5, Apache-2.0 AND MIT, approved, #5921 maven/mavencentral/org.webjars/webjars-locator-core/0.52, MIT, approved, clearlydefined maven/mavencentral/org.yaml/snakeyaml/2.0, Apache-2.0 AND (Apache-2.0 OR BSD-3-Clause OR EPL-1.0 OR GPL-2.0-or-later OR LGPL-2.1-or-later), approved, #7275 -maven/mavencentral/org.zalando/faux-pas/0.9.0, MIT, approved, clearlydefined -maven/mavencentral/org.zalando/jackson-datatype-problem/0.26.0, MIT, approved, clearlydefined -maven/mavencentral/org.zalando/problem-spring-common/0.27.0, MIT, approved, clearlydefined -maven/mavencentral/org.zalando/problem-spring-web/0.27.0, MIT, approved, clearlydefined -maven/mavencentral/org.zalando/problem-violations/0.27.0, MIT, approved, clearlydefined -maven/mavencentral/org.zalando/problem/0.26.0, MIT, approved, clearlydefined +maven/mavencentral/org.zalando/faux-pas/0.8.0, MIT, approved, clearlydefined +maven/mavencentral/org.zalando/jackson-datatype-problem/0.24.0, MIT, approved, clearlydefined +maven/mavencentral/org.zalando/problem-spring-common/0.26.0, MIT, approved, clearlydefined +maven/mavencentral/org.zalando/problem-spring-web/0.26.0, MIT, approved, clearlydefined +maven/mavencentral/org.zalando/problem-violations/0.26.0, MIT, approved, clearlydefined +maven/mavencentral/org.zalando/problem/0.24.0, MIT, approved, clearlydefined maven/mavencentral/xerces/xercesImpl/2.12.2, Apache-2.0 AND W3C, approved, CQ23076 maven/mavencentral/xml-apis/xml-apis-ext/1.3.04, Apache-2.0, approved, CQ1448 maven/mavencentral/xml-apis/xml-apis/1.4.01, Apache-2.0 OR LicenseRef-Public-Domain OR W3C, approved, CQ9621 diff --git a/pom.xml b/pom.xml index 3d12f5e7..b25e8965 100644 --- a/pom.xml +++ b/pom.xml @@ -41,7 +41,7 @@ 4.18.0 4.18.0 3.0.1 - 0.27.0 + 0.26.0 1.6.14 2.0.2 3.1.5 diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ObjectMapperConfig.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ObjectMapperConfig.java index 15939fab..626724d8 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ObjectMapperConfig.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/ObjectMapperConfig.java @@ -26,7 +26,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.zalando.problem.jackson.ProblemModule; +import org.zalando.problem.ProblemModule; import org.zalando.problem.violations.ConstraintViolationProblemModule; @Configuration diff --git a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java index c86f0299..cc392e2a 100644 --- a/src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java +++ b/src/main/java/org/eclipse/tractusx/valueaddedservice/config/WebClientConfiguration.java @@ -1,3 +1,22 @@ +/******************************************************************************** + * Copyright (c) 2022,2023 BMW Group AG + * Copyright (c) 2022,2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.config; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml index 4cc1f99c..bbba5b30 100644 --- a/src/main/resources/config/application-dev.yml +++ b/src/main/resources/config/application-dev.yml @@ -19,12 +19,6 @@ #*******************************************************************************/ # Spring Boot configuration -vas: - authentication-url: - token-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/token - jwk-set-uri: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/certs - auth-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/auth - spring: config: activate: @@ -33,8 +27,4 @@ spring: application: name: dev - host: http://project-value-added-service-vas/api/schedule - partnersPoolUrl: - bpdmAddressUrl: 'https://business-partners.dev.demo.catena-x.net/companies/test-company/api/catena/output/addresses/search?limit=10' - bpdmSiteUrl: 'https://business-partners.dev.demo.catena-x.net/companies/test-company/api/catena/output/sites/search?limit=10' - bpdmLegalUrl: 'https://business-partners.dev.demo.catena-x.net/companies/test-company/api/catena/output/legal-entities/search?limit=10' \ No newline at end of file + host: http://project-value-added-service-vas/api/schedule \ No newline at end of file diff --git a/src/main/resources/config/application-int.yml b/src/main/resources/config/application-int.yml index f1eb2140..0d48d92f 100644 --- a/src/main/resources/config/application-int.yml +++ b/src/main/resources/config/application-int.yml @@ -19,11 +19,6 @@ #*******************************************************************************/ # Spring Boot configuration -vas: - authentication-url: - token-url: https://centralidp.int.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/token - jwk-set-uri: https://centralidp.int.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/certs - auth-url: https://centralidp.int.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/auth spring: config: @@ -32,8 +27,4 @@ spring: application: name: int - host: http://project-value-added-service-vas/api/schedule - partnersPoolUrl: - bpdmAddressUrl: 'https://business-partners.int.demo.catena-x.net/companies/test-company/api/catena/output/addresses/search?limit=10' - bpdmSiteUrl: 'https://business-partners.int.demo.catena-x.net/companies/test-company/api/catena/output/sites/search?limit=10' - bpdmLegalUrl: 'https://business-partners.int.demo.catena-x.net/companies/test-company/api/catena/output/legal-entities/search?limit=10' \ No newline at end of file + host: http://project-value-added-service-vas/api/schedule \ No newline at end of file diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index 54c75a49..6d610e68 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -30,15 +30,17 @@ vas: host: localhost user: default pass: defaultpassword + auth: + url: http://localhost:8081 keycloak: clientId: clientSecret: clientName: country-risk-client authentication-url: - token-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/token - jwk-set-uri: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/certs - auth-url: https://centralidp.dev.demo.catena-x.net/auth/realms/CX-Central/protocol/openid-connect/auth + token-url: ${vas.auth.url}/auth/realms/CX-Central/protocol/openid-connect/token + jwk-set-uri: ${vas.auth.url}/auth/realms/CX-Central/protocol/openid-connect/certs + auth-url: ${vas.auth.url}/auth/realms/CX-Central/protocol/openid-connect/auth bearer_token: diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java index 25164086..b4fc9063 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/service/logic/CountryLogicServiceTest.java @@ -1,22 +1,22 @@ /******************************************************************************** -* Copyright (c) 2022,2023 BMW Group AG -* Copyright (c) 2022,2023 Contributors to the Eclipse Foundation -* -* See the NOTICE file(s) distributed with this work for additional -* information regarding copyright ownership. -* -* This program and the accompanying materials are made available under the -* terms of the Apache License, Version 2.0 which is available at -* https://www.apache.org/licenses/LICENSE-2.0. -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -* License for the specific language governing permissions and limitations -* under the License. -* -* SPDX-License-Identifier: Apache-2.0 -********************************************************************************/ + * Copyright (c) 2022,2023 BMW Group AG + * Copyright (c) 2022,2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ package org.eclipse.tractusx.valueaddedservice.service.logic; import org.eclipse.tractusx.valueaddedservice.config.ApplicationVariables; @@ -57,15 +57,13 @@ class CountryLogicServiceTest { ApplicationVariables applicationVariables; - - @Test @DisplayName("Should return a list of countries filtered by iso2") void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2() { CompanyUserDTO companyUserDTO = new CompanyUserDTO(); - CountryDTO countryDTO1 = new CountryDTO(1L, "Germany", "DEU", "DE", "Europe","","",3L); - CountryDTO countryDTO2 = new CountryDTO(2L, "Spain", "ESP", "ES", "Europe","","",3L); - CountryDTO countryDTO3 = new CountryDTO(3L, "France", "FRA", "FR", "Europe","","",3L); + CountryDTO countryDTO1 = new CountryDTO(1L, "Germany", "DEU", "DE", "Europe", "", "", 3L); + CountryDTO countryDTO2 = new CountryDTO(2L, "Spain", "ESP", "ES", "Europe", "", "", 3L); + CountryDTO countryDTO3 = new CountryDTO(3L, "France", "FRA", "FR", "Europe", "", "", 3L); AuthPropertiesDTO authPropertiesDTO = new AuthPropertiesDTO(); authPropertiesDTO.setCompanyName("TestCompany"); @@ -77,14 +75,14 @@ void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2() { List countryDTOList = Arrays.asList(countryDTO1, countryDTO2, countryDTO3); when(countryService.findAll()).thenReturn(countryDTOList); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO, applicationVariables.getToken(), new ArrayList<>())) .thenReturn(1L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO, applicationVariables.getToken(), new ArrayList<>())) .thenReturn(2L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO, applicationVariables.getToken(), new ArrayList<>())) .thenReturn(3L); - List result = countryLogicService.getCountryFilterByISO2(companyUserDTO,applicationVariables.getToken(),new ArrayList<>()); + List result = countryLogicService.getCountryFilterByISO2(companyUserDTO, applicationVariables.getToken(), new ArrayList<>()); assertEquals(3, result.size()); assertEquals("Germany", result.get(0).getCountry()); @@ -108,14 +106,14 @@ void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2AndTotalBusi when(countryService.findAll()).thenReturn(countryDTOList); when(applicationVariables.getToken()).thenReturn(""); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO1, companyUserDTO, applicationVariables.getToken(), new ArrayList<>())) .thenReturn(1L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO2, companyUserDTO, applicationVariables.getToken(), new ArrayList<>())) .thenReturn(2L); - when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO,applicationVariables.getToken(),new ArrayList<>())) + when(externalBusinessPartnersLogicService.getTotalBpnByCountry(countryDTO3, companyUserDTO, applicationVariables.getToken(), new ArrayList<>())) .thenReturn(3L); - List result = countryLogicService.getCountryFilterByISO2(companyUserDTO,"",new ArrayList<>()); + List result = countryLogicService.getCountryFilterByISO2(companyUserDTO, "", new ArrayList<>()); assertEquals(3, result.size()); assertEquals("Germany", result.get(0).getCountry()); @@ -140,7 +138,7 @@ void getCountryFilterByISO2ShouldReturnListOfCountriesFilteredByISO2AndTotalBusi void getAssociatedCountriesWhenCompanyUserDTONullThenReturnEmptyList() { CompanyUserDTO companyUserDTO = null; List countryDTOList = - countryLogicService.getAssociatedCountries(companyUserDTO,"",new ArrayList<>()); + countryLogicService.getAssociatedCountries(companyUserDTO, "", new ArrayList<>()); assertTrue(countryDTOList.isEmpty()); } @@ -166,14 +164,13 @@ void getAssociatedCountriesWhenCompanyUserDTONotNullThenReturnListOfCountries() when(countryService.findByCountryIn(anyList())).thenReturn(countryDTOList); - List result = countryLogicService.getAssociatedCountries(companyUserDTO,"",new ArrayList<>()); + List result = countryLogicService.getAssociatedCountries(companyUserDTO, "", new ArrayList<>()); assertNotNull(result); assertEquals(1, result.size()); } - @Test @DisplayName("Should return a country when the country exists") void findCountryByNameWhenCountryExistsThenReturnCountry() { diff --git a/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java b/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java index 9bca3a40..066bad21 100644 --- a/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java +++ b/src/test/java/org/eclipse/tractusx/valueaddedservice/utils/DataBaseJsonConverterTest.java @@ -61,9 +61,6 @@ public void convertToEntityAttributeWithNullJsonString() { } - - - @Test public void testConvertToDatabaseColumn() throws JsonProcessingException { Map customerInfo = new HashMap<>();