diff --git a/.env.template b/.env.template
index 0e768adcd..b8fe3e800 100644
--- a/.env.template
+++ b/.env.template
@@ -35,9 +35,9 @@ BRAPI_READ_TIMEOUT=60m
# Max number of records to POST to the BrAPI service per request
POST_CHUNK_SIZE=1000
-# Request cache records paginating through available records per program by CACHE_BRAPI_FETCH_PAGE_SIZE
-CACHE_PAGINATE_GERMPLASM=false
-CACHE_BRAPI_FETCH_PAGE_SIZE=65000
+# Amount of records to page at a time through a BrAPI search request result. See BrAPIDAOUtil.searchInternalReturnResponse.
+# Should not exceed 65k for now due to BrAPI limitations
+BRAPI_PAGE_THRU_PAGE_SIZE=65000
# BrAPI Server Variables
BRAPI_SERVER_PORT=8083
@@ -79,3 +79,5 @@ TRIAL_START_DELAY=15s
TRAIT_START_DELAY=20s
OBSERVATION_START_DELAY=25s
OBSERVATION_UNIT_START_DELAY=30s
+
+DATA_TABLE_MAX_SIZE=200
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 3afa66cab..1a24e322f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -89,7 +89,7 @@
31.0.1-jre
4.9.3
4.3.1
- 2.2-SNAPSHOT
+ 2.2.2-SNAPSHOT
2.11.0
2.2.1
diff --git a/src/main/java/org/breedinginsight/api/v1/controller/ExperimentController.java b/src/main/java/org/breedinginsight/api/v1/controller/ExperimentController.java
index 988402889..878a9441d 100644
--- a/src/main/java/org/breedinginsight/api/v1/controller/ExperimentController.java
+++ b/src/main/java/org/breedinginsight/api/v1/controller/ExperimentController.java
@@ -46,7 +46,6 @@
@Secured(SecurityRule.IS_AUTHENTICATED)
public class ExperimentController {
private final BrAPITrialService experimentService;
- private final ExperimentQueryMapper experimentQueryMapper;
private final ProgramService programService;
private final ExperimentalCollaboratorService experimentalCollaboratorService;
private final SecurityService securityService;
@@ -54,9 +53,8 @@ public class ExperimentController {
private final RoleService roleService;
@Inject
- public ExperimentController(BrAPITrialService experimentService, ExperimentQueryMapper experimentQueryMapper, ProgramService programService, ExperimentalCollaboratorService experimentalCollaboratorService, SecurityService securityService, ProgramUserService programUserService, RoleService roleService) {
+ public ExperimentController(BrAPITrialService experimentService, ProgramService programService, ExperimentalCollaboratorService experimentalCollaboratorService, SecurityService securityService, ProgramUserService programUserService, RoleService roleService) {
this.experimentService = experimentService;
- this.experimentQueryMapper = experimentQueryMapper;
this.programService = programService;
this.experimentalCollaboratorService = experimentalCollaboratorService;
this.securityService = securityService;
diff --git a/src/main/java/org/breedinginsight/brapi/v1/model/request/query/BrapiQuery.java b/src/main/java/org/breedinginsight/brapi/v1/model/request/query/BrapiQuery.java
index f51bcf317..1b4f9234e 100644
--- a/src/main/java/org/breedinginsight/brapi/v1/model/request/query/BrapiQuery.java
+++ b/src/main/java/org/breedinginsight/brapi/v1/model/request/query/BrapiQuery.java
@@ -26,6 +26,7 @@
import javax.validation.constraints.Positive;
import javax.validation.constraints.PositiveOrZero;
+import java.util.Map;
@Getter
@Setter
@@ -42,7 +43,7 @@ public class BrapiQuery implements PaginationParams {
private Integer page;
private String sortField;
- private SortOrder sortOrder;
+ private SortOrder sortOrder = SortOrder.ASC;
public Integer getDefaultPage() {
return DEFAULT_PAGE;
@@ -58,4 +59,26 @@ protected FilterRequest constructFilterRequest(String field, String value) {
.value(value)
.build();
}
+
+ /**
+ * For BrapiQuery objects that have implemented this method, this map is used by the BrAPIDAOUtil
+ * to iterate through all valid filter columns and their associated values that are submitted from the fe.
+ *
+ * See @ExperimentQuery for example implementation
+ */
+ public Map getFilterValuesByBrAPIColumnName() {
+ throw new UnsupportedOperationException(
+ String.format("Server side BrAPI filtering not implemented for class [%s]", this.getClass().getSimpleName())
+ );
+ }
+
+ /**
+ * For BrapiQuery objects that have implemented this method, this map is used by the BrAPIDAOUtil
+ * to match submitted sortField column names to the associated brapi column name for sorting.
+ *
+ * See @ExperimentQuery for example implementation
+ */
+ public Map getBrAPIColumnNamesByBiColumnName() {
+ throw new UnsupportedOperationException(String.format("Server side BrAPI sorting not implemented for class [%s]", this.getClass().getSimpleName()));
+ }
}
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java
index 7bcf71de6..16323867a 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIGermplasmController.java
@@ -1,6 +1,5 @@
package org.breedinginsight.brapi.v2;
-import com.drew.lang.annotations.Nullable;
import io.micronaut.context.annotation.Property;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
@@ -16,10 +15,7 @@
import org.brapi.client.v2.ApiResponse;
import org.brapi.client.v2.model.exceptions.ApiException;
import org.brapi.client.v2.modules.germplasm.GermplasmApi;
-import org.brapi.v2.model.BrAPIAcceptedSearchResponse;
-import org.brapi.v2.model.BrAPIIndexPagination;
-import org.brapi.v2.model.BrAPIMetadata;
-import org.brapi.v2.model.BrAPIStatus;
+import org.brapi.v2.model.*;
import org.brapi.v2.model.germ.*;
import org.brapi.v2.model.germ.request.BrAPIGermplasmSearchRequest;
import org.brapi.v2.model.germ.response.BrAPIGermplasmListResponse;
@@ -27,7 +23,6 @@
import org.brapi.v2.model.germ.response.BrAPIGermplasmProgenyResponse;
import org.breedinginsight.api.auth.ProgramSecured;
import org.breedinginsight.api.auth.ProgramSecuredRoleGroup;
-import org.breedinginsight.api.model.v1.request.query.SearchRequest;
import org.breedinginsight.api.model.v1.response.DataResponse;
import org.breedinginsight.api.model.v1.response.Response;
import org.breedinginsight.api.model.v1.validators.QueryValid;
@@ -37,6 +32,7 @@
import org.breedinginsight.brapi.v2.model.request.query.GermplasmQuery;
import org.breedinginsight.brapi.v2.services.BrAPIGermplasmService;
import org.breedinginsight.brapps.importer.model.exports.FileType;
+import org.breedinginsight.brapps.importer.services.ExternalReferenceSource;
import org.breedinginsight.daos.ProgramDAO;
import org.breedinginsight.model.DownloadFile;
import org.breedinginsight.model.GermplasmGenotype;
@@ -91,8 +87,8 @@ public BrAPIGermplasmController(@Property(name = "brapi.server.reference-source"
this.programService = programService;
}
- // NOTE: bypasses cache and makes api request directly to brapi service
- // Needs to convert DeltaBreed UUIDs to BrAPI Service DbIds and back
+ // NOTE: Makes api request directly to BrAPI service
+ // Needs to convert DeltaBreed program UUID to BrAPI programDbId and back
@Post("/programs/{programId}" + BrapiVersion.BRAPI_V2 + "/search/germplasm")
@Produces(MediaType.APPLICATION_JSON)
@ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES})
@@ -108,17 +104,8 @@ public HttpResponse searchGermplasm(
return HttpResponse.notFound();
}
- // Can't use BrAPI server programDbId filtering, think germplasm are linked to program through observation
- // units and doesn't work if don't have any loaded, use external refs instead for now
- // Just use DeltaBreed program UUID
- String extRefId = program.get().getId().toString();
- body.externalReferenceIds(List.of(extRefId));
-
- // convert request filter dbIds from DeltaBreed UUID to BrAPI service dbIds
- if (body.getGermplasmDbIds() != null && !body.getGermplasmDbIds().isEmpty()) {
- List convertedDbIds = germplasmService.getGermplasmDbIdsForUUIDs(program.get().getId(), body.getGermplasmDbIds());
- body.setGermplasmDbIds(convertedDbIds);
- }
+ String brapiProgramDbId = programService.getBrAPIProgramDbId(program.get().getId());
+ body.setProgramDbIds(List.of(brapiProgramDbId));
ApiResponse, Optional>> brapiGermplasm;
brapiGermplasm = brAPIEndpointProvider
@@ -128,8 +115,8 @@ public HttpResponse searchGermplasm(
return getObjectHttpResponse(brapiGermplasm, program.get().getKey());
}
- // NOTE: bypasses cache and makes api request directly to brapi service
- // Needs to convert BrAPIService dbIds to DeltaBreed UUIDs
+ // NOTE: Makes api request directly to BrAPI service
+ // Needs to convert DeltaBreed program UUID to BrAPI programDbId and back
@Get("/programs/{programId}" + BrapiVersion.BRAPI_V2 + "/search/germplasm/{searchResultId}{?queryParams*}")
@Produces(MediaType.APPLICATION_JSON)
@ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES})
@@ -179,10 +166,6 @@ private void batchProcessGermplasm(List germplasmList, String pr
// Prepare a regex pattern for program key removal
Pattern programKeyPattern = Utilities.getRegexPatternMatchAllProgramKeysAnyAccession(programKey);
germplasmList.parallelStream().forEach(germplasm -> {
- // Set dbId
- germplasm.germplasmDbId(Utilities.getExternalReference(germplasm.getExternalReferences(), "breedinginsight.org")
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceId());
// Process synonyms
if (germplasm.getSynonyms() != null) {
germplasm.getSynonyms().forEach(synonym -> {
@@ -199,7 +182,7 @@ private void batchProcessGermplasm(List germplasmList, String pr
@Get("/programs/{programId}" + BrapiVersion.BRAPI_V2 + "/germplasm{?queryParams*}")
@Produces(MediaType.APPLICATION_JSON)
@ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES})
- public HttpResponse>>> getGermplasm(
+ public HttpResponse>> getGermplasm(
@PathVariable("programId") UUID programId,
@QueryValue @QueryValid(using = GermplasmQueryMapper.class) @Valid GermplasmQuery queryParams) {
try {
@@ -212,15 +195,19 @@ public HttpResponse>>> getGermplasm(
}
// Fetch all germplasm in the program unless a list id is supplied to return only germplasm in that collection
- List germplasm = queryParams.getListDbId() == null ? germplasmService.getGermplasm(programId) : germplasmService.getGermplasmByList(programId, queryParams.getListDbId());
- SearchRequest searchRequest = queryParams.constructSearchRequest();
- return ResponseUtils.getBrapiQueryResponse(germplasm, germplasmQueryMapper, queryParams, searchRequest);
+ BrAPIGermplasmListResponse brapiResponse = queryParams.getListDbId() == null ? germplasmService.searchGermplasm(programId, queryParams) : germplasmService.getGermplasmByList(programId, queryParams);
+
+ List foundGermplasm = brapiResponse.getResult().getData();
+ return ResponseUtils.getBrapiQueryResponse(foundGermplasm, brapiResponse);
} catch (ApiException e) {
log.info(e.getMessage(), e);
return HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, "Error retrieving germplasm");
} catch (IllegalArgumentException e) {
log.info(e.getMessage(), e);
return HttpResponse.status(HttpStatus.UNPROCESSABLE_ENTITY, "Error parsing requested date format");
+ } catch (DoesNotExistException e) {
+ log.info(e.getMessage(), e);
+ return HttpResponse.status(HttpStatus.NOT_FOUND, "Supplied programId does not exist");
}
}
@@ -322,8 +309,7 @@ public HttpResponse getGermplasmPedigreeInfo(
metadata.setPagination(pagination);
response = new BrAPIGermplasmPedigreeResponse();
} else {
- BrAPIGermplasm germplasm = germplasmService.getGermplasmByDBID(programId, germplasmId)
- .orElseThrow(() -> new DoesNotExistException("DBID for this germplasm does not exist"));
+ BrAPIGermplasm germplasm = germplasmService.getGermplasmByUUID(programId, germplasmId);
//Forward the pedigree call to the backing BrAPI system of the program passing the germplasmDbId that came in the request
GermplasmApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), GermplasmApi.class);
@@ -440,15 +426,13 @@ public HttpResponse> getGermplasmGenotype(@PathVaria
@PathVariable("germplasmId") String germplasmId) {
try {
- BrAPIGermplasm germplasm = germplasmDAO.getGermplasmByUUID(germplasmId, programId);
-
GermplasmGenotype germplasmGenotype = genoService.retrieveGenotypeData(programId, UUID.fromString(germplasmId));
Response response = new Response(germplasmGenotype);
return HttpResponse.ok(response);
} catch (DoesNotExistException e) {
log.error(e.getMessage(), e);
- return HttpResponse.status(HttpStatus.NOT_FOUND, "Germplasm not found");
+ return HttpResponse.status(HttpStatus.NOT_FOUND, e.getMessage());
} catch (AuthorizationException | ApiException e) {
log.error(e.getMessage(), e);
return HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, "Error retrieving genotype data");
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationLevelsController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationLevelsController.java
index ed2ef1884..65fa2c278 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationLevelsController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationLevelsController.java
@@ -31,7 +31,6 @@
import org.brapi.client.v2.modules.phenotype.ObservationUnitsApi;
import org.brapi.v2.model.BrAPIIndexPagination;
import org.brapi.v2.model.BrAPIMetadata;
-import org.brapi.v2.model.core.BrAPIStudy;
import org.brapi.v2.model.core.BrAPITrial;
import org.brapi.v2.model.pheno.BrAPIObservationUnitHierarchyLevel;
import org.brapi.v2.model.pheno.response.BrAPIObservationLevelListResponse;
@@ -39,7 +38,6 @@
import org.breedinginsight.api.auth.ProgramSecured;
import org.breedinginsight.api.auth.ProgramSecuredRoleGroup;
import org.breedinginsight.brapi.v1.controller.BrapiVersion;
-import org.breedinginsight.brapi.v2.dao.BrAPIStudyDAO;
import org.breedinginsight.brapi.v2.dao.BrAPITrialDAO;
import org.breedinginsight.daos.ProgramDAO;
import org.breedinginsight.model.BrAPIConstants;
@@ -65,15 +63,13 @@ public class BrAPIObservationLevelsController {
private final ProgramDAO programDAO;
private final ProgramService programService;
private final BrAPITrialDAO trialDAO;
- private final BrAPIStudyDAO studyDAO;
@Inject
- public BrAPIObservationLevelsController(BrAPIEndpointProvider brAPIEndpointProvider, ProgramDAO programDAO, ProgramService programService, BrAPITrialDAO trialDAO, BrAPIStudyDAO studyDAO) {
+ public BrAPIObservationLevelsController(BrAPIEndpointProvider brAPIEndpointProvider, ProgramDAO programDAO, ProgramService programService, BrAPITrialDAO trialDAO) {
this.brAPIEndpointProvider = brAPIEndpointProvider;
this.programDAO = programDAO;
this.programService = programService;
this.trialDAO = trialDAO;
- this.studyDAO = studyDAO;
}
@Get("/observationlevels")
@@ -93,25 +89,13 @@ public HttpResponse observationlevelsGet(@Pat
}
String programDbId = program.get().getBrapiProgram().getProgramDbId();
- String studyDbId = null;
+ String studyDbId = environmentId;
String trialDbId = null;
- if(environmentId != null) {
- try {
- Optional study = studyDAO.getStudyByEnvironmentId(UUID.fromString(environmentId), program.get());
- if(study.isPresent()) {
- studyDbId = study.get().getStudyDbId();
- } else {
- studyDbId = environmentId;
- }
- } catch (ApiException e) {
- log.error(Utilities.generateApiExceptionLogMessage(e), "Error fetching environment");
- return HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, "Error finding observation levels");
- }
- } else if(experimentId != null) {
+ if(environmentId == null && experimentId != null) {
try {
List trial = trialDAO.getTrialsByExperimentIds(List.of(UUID.fromString(experimentId)), program.get());
- if(trial.size() == 1) {
+ if (trial.size() == 1) {
trialDbId = trial.get(0).getTrialDbId();
} else {
trialDbId = experimentId;
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationUnitController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationUnitController.java
index ca2b470f8..de22451b7 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationUnitController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationUnitController.java
@@ -127,7 +127,6 @@ public HttpResponse observationunitsGet(@PathV
Optional.ofNullable(studyDbId),
Optional.ofNullable(germplasmDbId))
.stream()
- .peek(this::setDbIds)
.collect(Collectors.toList());
return HttpResponse.ok(new BrAPIObservationUnitListResponse().metadata(new BrAPIMetadata().pagination(new BrAPIIndexPagination().currentPage(0)
@@ -149,7 +148,7 @@ public HttpResponse observationunitsGet(@PathV
@Get("/observationunits/{observationUnitDbId}")
@ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES})
public HttpResponse observationunitsObservationUnitDbIdGet(@PathVariable("programId") UUID programId, @PathVariable("observationUnitDbId") String observationUnitDbId) {
- log.debug("observationunitsObservationUnitDbIdGet: fetching ou by externalReferenceId: " + observationUnitDbId);
+ log.debug("observationunitsObservationUnitDbIdGet: fetching ou by dbId: " + observationUnitDbId);
Optional program = programService.getById(programId);
if(program.isEmpty()) {
log.warn("Program id: " + programId + " not found");
@@ -158,10 +157,9 @@ public HttpResponse observationunitsObservat
try {
List ous = observationUnitDAO.getObservationUnitsById(List.of(observationUnitDbId), program.get());
if(ous.size() != 1) {
- log.warn("did not find a single ou with externalReferenceId: " + observationUnitDbId);
+ log.warn("did not find a single ou with dbId: " + observationUnitDbId);
return HttpResponse.notFound();
}
- setDbIds(ous.get(0));
return HttpResponse.ok(new BrAPIObservationUnitSingleResponse().result(ous.get(0)));
} catch (ApiException e) {
log.error(Utilities.generateApiExceptionLogMessage(e), e);
@@ -218,26 +216,4 @@ public HttpResponse> observationunitsTableGet(@PathVariable("programId") UUID
@Nullable @QueryValue("observationUnitLevelRelationshipDbId") String observationUnitLevelRelationshipDbId) {
return HttpResponse.notFound();
}
-
- private void setDbIds(BrAPIObservationUnit ou) {
- ou.observationUnitDbId(Utilities.getExternalReference(ou.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.OBSERVATION_UNITS))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
- ou.studyDbId(Utilities.getExternalReference(ou.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.STUDIES))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
- ou.trialDbId(Utilities.getExternalReference(ou.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.TRIALS))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
- ou.programDbId(Utilities.getExternalReference(ou.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.PROGRAMS))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
- if (ou.getAdditionalInfo().has(BrAPIAdditionalInfoFields.GERMPLASM_UUID)) {
- ou.setGermplasmDbId(ou.getAdditionalInfo()
- .get(BrAPIAdditionalInfoFields.GERMPLASM_UUID)
- .getAsString());
- }
-
- //TODO update locationDbId
- }
}
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationVariableController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationVariableController.java
index 9727ad1be..ad1bed214 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationVariableController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationVariableController.java
@@ -150,23 +150,25 @@ public HttpResponse variablesGet(@PathVari
public HttpResponse variablesObservationVariableDbIdGet(@PathVariable("programId") UUID programId,
@PathVariable("observationVariableDbId") String observationVariableDbId) {
log.debug("fetching variable: " + observationVariableDbId);
- UUID traitId;
try {
- traitId = UUID.fromString(observationVariableDbId);
+ // Check if submitted ID is valid UUID
+ UUID.fromString(observationVariableDbId);
} catch (IllegalArgumentException e) {
return HttpResponse.notFound();
}
try {
- Optional trait = traitService.getById(programId, traitId);
+ List programTraits = traitService.getByProgramId(programId, true);
- if(trait.isEmpty()) {
+ if(programTraits.isEmpty()) {
return HttpResponse.notFound();
}
+ BrAPIObservationVariable observationVariable = observationVariableService.filterVariableById(programTraits, observationVariableDbId);
+
BrAPIObservationVariableSingleResponse response = new BrAPIObservationVariableSingleResponse()
.metadata(new BrAPIMetadata())
- .result(observationVariableService.convertToBrAPI(trait.get()));
+ .result(observationVariable);
return HttpResponse.ok(response);
} catch (DoesNotExistException e) {
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationsController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationsController.java
index 27ac4e34c..094880e4d 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationsController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIObservationsController.java
@@ -17,7 +17,6 @@
package org.breedinginsight.brapi.v2;
-
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.annotation.*;
@@ -28,13 +27,12 @@
import org.brapi.client.v2.ApiResponse;
import org.brapi.client.v2.model.exceptions.ApiException;
import org.brapi.client.v2.modules.phenotype.ObservationsApi;
-import org.brapi.v2.model.BrAPIIndexPagination;
import org.brapi.v2.model.BrAPIMetadata;
import org.brapi.v2.model.BrAPIStatus;
import org.brapi.v2.model.BrAPIWSMIMEDataTypes;
-import org.brapi.v2.model.core.BrAPIStudy;
import org.brapi.v2.model.pheno.BrAPIObservation;
-import org.brapi.v2.model.pheno.response.*;
+import org.brapi.v2.model.pheno.response.BrAPIObservationListResponse;
+import org.brapi.v2.model.pheno.response.BrAPIObservationTableResponse;
import org.breedinginsight.api.auth.ProgramSecured;
import org.breedinginsight.api.auth.ProgramSecuredRoleGroup;
import org.breedinginsight.brapi.v1.controller.BrapiVersion;
@@ -46,7 +44,7 @@
import org.breedinginsight.services.ProgramService;
import org.breedinginsight.services.brapi.BrAPIEndpointProvider;
import org.breedinginsight.utilities.Utilities;
-
+import org.breedinginsight.utilities.response.ResponseUtils;
import javax.annotation.Nullable;
import javax.inject.Inject;
@@ -61,20 +59,17 @@ public class BrAPIObservationsController {
private final ProgramService programService;
private final ProgramDAO programDAO;
- private final BrAPIStudyDAO brAPIStudyDAO;
private final BrAPIEndpointProvider brAPIEndpointProvider;
private final BrAPIObservationDAO observationDAO;
@Inject
public BrAPIObservationsController(ProgramService programService,
- ProgramDAO programDAO,
ProgramDAO programDAO1,
BrAPIStudyDAO brAPIStudyDAO,
BrAPIEndpointProvider brAPIEndpointProvider,
BrAPIObservationDAO brAPIObservationDAO) {
this.programService = programService;
this.programDAO = programDAO1;
- this.brAPIStudyDAO = brAPIStudyDAO;
this.brAPIEndpointProvider = brAPIEndpointProvider;
this.observationDAO = brAPIObservationDAO;
}
@@ -147,53 +142,37 @@ public HttpResponse observationsGet(@PathVariable("programId") UUID programId,
);
}
- // Get a filtered list of observations.
- List observations = observationDAO.getObservationsByFilters(program.get(), studyDbId);
-
- // If page is not provided, set it to the default value 0.
- if (page == null) page = 0;
- // If pageSize is not provided, set it to the default value 1000.
- if (pageSize == null) pageSize = 1000;
-
- // Total number of records in the unpaged super set.
- int totalCount = observations.size();
- // The least of pageSize and totalCount, unless pageSize is zero, in which case use totalCount.
- int requestedPageSize = pageSize > 0 ? Math.min(pageSize, totalCount) : totalCount;
- // Integer division and round up.
- int totalPages = totalCount / requestedPageSize + ((totalCount % requestedPageSize == 0) ? 0 : 1);
- log.info("(Pagination) totalCount: " + totalCount + " page (0-indexed): " + page + " requestedPageSize: " + requestedPageSize + " totalPages: " + totalPages);
+ boolean pageSizeValid = pageSize == null || pageSize > 0;
+ boolean pageValid = page == null || page >= 0;
- // Determine validity of pagination query parameters.
- boolean pageSizeValid = pageSize > 0;
- boolean pageValid = page >= 0 && page < totalPages;
-
- // Only paginate if valid pagination values were sent.
- if (pageSizeValid && pageValid) {
- int start = page * requestedPageSize;
- // Account for last page, which may have fewer than requestedPageSize items, or exactly requestedPageSize items.
- int end = (page == (totalPages - 1) && totalCount % requestedPageSize != 0) ? (start + (totalCount % requestedPageSize)) : Math.min(((page + 1) * requestedPageSize), totalCount);
- log.info("(Pagination) start " + start + " end " + end);
- // Sort observations so that paging is consistent and coherent.
- observations.sort(Comparator.comparing(BrAPIObservation::getObservationDbId));
- // Paginate response.
- observations = observations.subList(start, end);
- } else {
+ if (!pageSizeValid || !pageValid) {
String errorMessage = "Invalid query parameters: page, pageSize";
- return HttpResponse.badRequest(new BrAPIObservationListResponse().metadata(new BrAPIMetadata().status(List.of(new BrAPIStatus().messageType(BrAPIStatus.MessageTypeEnum.ERROR)
- .message(errorMessage)))));
+ return HttpResponse.badRequest(new BrAPIObservationListResponse()
+ .metadata(new BrAPIMetadata()
+ .status(List.of(new BrAPIStatus()
+ .messageType(BrAPIStatus.MessageTypeEnum.ERROR)
+ .message(errorMessage)))));
}
- return HttpResponse.ok(new BrAPIObservationListResponse().metadata(new BrAPIMetadata().pagination(new BrAPIIndexPagination()
- .currentPage(page)
- .totalPages(totalPages)
- .pageSize(observations.size())
- .totalCount(totalCount)))
- .result(new BrAPIObservationListResponseResult().data(observations)));
+ BrAPIObservationListResponse brAPIResponse = observationDAO.getObservationsByFilters(program.get(), studyDbId, page, pageSize);
+
+ List observations = brAPIResponse.getResult().getData();
+ return ResponseUtils.getBrapiQueryResponse(observations, brAPIResponse);
} catch (ApiException e) {
log.error(Utilities.generateApiExceptionLogMessage(e), e);
- return HttpResponse.serverError(new BrAPIObservationListResponse().metadata(new BrAPIMetadata().status(List.of(new BrAPIStatus().messageType(BrAPIStatus.MessageTypeEnum.ERROR)
- .message("Error fetching observations")))));
+
+ BrAPIObservationListResponse errorResponse = new BrAPIObservationListResponse()
+ .metadata(new BrAPIMetadata()
+ .status(List.of(new BrAPIStatus()
+ .messageType(BrAPIStatus.MessageTypeEnum.ERROR)
+ .message("Error fetching observations"))));
+
+ if (e.getCode() == HttpStatus.BAD_REQUEST.getCode()) {
+ return HttpResponse.badRequest(errorResponse);
+ }
+
+ return HttpResponse.serverError(errorResponse);
} catch (Exception e) {
log.error("Error fetching Observations", e);
return HttpResponse.serverError(new BrAPIObservationListResponse().metadata(new BrAPIMetadata().status(List.of(new BrAPIStatus().messageType(BrAPIStatus.MessageTypeEnum.ERROR)
@@ -253,16 +232,6 @@ public HttpResponse observationsTableGet(
}
try {
- // Translate studyDbId if provided.
- if (queryParams.getStudyDbId() != null) {
- Optional study = brAPIStudyDAO.getStudyByEnvironmentId(UUID.fromString(queryParams.getStudyDbId()), program.get());
- if (study.isEmpty()) {
- return HttpResponse.notFound();
- }
- queryParams.setStudyDbId(study.get().getStudyDbId());
- }
- // TODO: Translate other DbIds if provided as well (but studyDbId is sufficient for Mr. Bean).
-
ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ObservationsApi.class);
ApiResponse response = api.observationsTableGet(BrAPIWSMIMEDataTypes.APPLICATION_JSON, queryParams.toBrAPIQueryParams());
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIProgramsController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIProgramsController.java
index 4a5281c8b..2e4b67aa9 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIProgramsController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIProgramsController.java
@@ -24,6 +24,7 @@
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;
import lombok.extern.slf4j.Slf4j;
+import org.brapi.client.v2.model.exceptions.ApiException;
import org.brapi.v2.model.BrAPIIndexPagination;
import org.brapi.v2.model.BrAPIMetadata;
import org.brapi.v2.model.core.BrAPIProgram;
@@ -33,7 +34,6 @@
import org.breedinginsight.api.auth.ProgramSecured;
import org.breedinginsight.api.auth.ProgramSecuredRoleGroup;
import org.breedinginsight.api.auth.SecurityService;
-import org.breedinginsight.api.model.v1.response.DataResponse;
import org.breedinginsight.brapi.v1.controller.BrapiVersion;
import org.breedinginsight.model.Program;
import org.breedinginsight.services.ProgramService;
@@ -82,17 +82,28 @@ public HttpResponse rootProgramsGet(
Optional programDbIdOptional = Optional.ofNullable(programDbId);
Optional programNameOptional = Optional.ofNullable(programName);
- List programs = programService.getAll(securityService.getUser()).stream().filter(program -> {
+ List programs = programService.getAll(securityService.getUser());
+
+ for (Program program : programs) {
+ try {
+ program.setBrapiProgram(new BrAPIProgram().programDbId(programService.getBrAPIProgramDbId(program.getId())));
+ } catch (ApiException e) {
+ log.info(e.getMessage(), e);
+ return HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, String.format("Error retrieving programs: [%s]", e.getMessage()));
+ }
+ }
+
+ List brapiPrograms = programs.stream().filter(program -> {
boolean matches = abbreviationOptional.map(abbr -> abbr.equals(program.getKey())).orElse(true);
- matches = matches && programDbIdOptional.map(id -> id.equals(program.getId().toString())).orElse(true);
+ matches = matches && programDbIdOptional.map(id -> id.equals(program.getBrapiProgram().getProgramDbId())).orElse(true);
return matches && programNameOptional.map(name -> name.equals(program.getName())).orElse(true);
}).map(this::convertToBrAPI).collect(Collectors.toList());
return HttpResponse.ok(new BrAPIProgramListResponse().metadata(new BrAPIMetadata().pagination(new BrAPIIndexPagination().currentPage(0)
.totalPages(1)
- .totalCount(programs.size())
- .pageSize(programs.size())))
- .result(new BrAPIProgramListResponseResult().data(programs)));
+ .totalCount(brapiPrograms.size())
+ .pageSize(brapiPrograms.size())))
+ .result(new BrAPIProgramListResponseResult().data(brapiPrograms)));
}
@Post(BrapiVersion.BRAPI_V2 + "/programs")
@@ -140,35 +151,35 @@ public HttpResponse> rootProgramsProgramDbIdPut(@PathVariable("programDbId") S
@Produces(MediaType.APPLICATION_JSON)
@ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES})
public HttpResponse programsGet(@PathVariable("programId") UUID programId,
- @QueryValue("abbreviation") Optional abbreviation,
- @QueryValue("programType") Optional programType,
- @QueryValue("commonCropName") Optional commonCropName,
- @QueryValue("programDbId") Optional programDbId,
- @QueryValue("programName") Optional programName,
- @QueryValue("externalReferenceID") Optional externalReferenceID,
- @QueryValue("externalReferenceId") Optional externalReferenceId,
- @QueryValue("externalReferenceSource") Optional externalReferenceSource,
- @QueryValue("page") Optional page,
- @QueryValue("pageSize") Optional pageSize) {
+ @QueryValue("abbreviation") Optional abbreviation,
+ @QueryValue("programType") Optional programType,
+ @QueryValue("commonCropName") Optional commonCropName,
+ @QueryValue("programDbId") Optional programDbId,
+ @QueryValue("programName") Optional programName,
+ @QueryValue("externalReferenceID") Optional externalReferenceID,
+ @QueryValue("externalReferenceId") Optional externalReferenceId,
+ @QueryValue("externalReferenceSource") Optional externalReferenceSource,
+ @QueryValue("page") Optional page,
+ @QueryValue("pageSize") Optional pageSize) {
//If programId supplied, check if program exists
if (programId != null) {
Optional optProgram = programService.getById(programId);
- if (optProgram.isEmpty()) {
+ if (optProgram.isEmpty() || optProgram.get().getBrapiProgram() == null) {
return HttpResponse.status(HttpStatus.NOT_FOUND, "Program not found");
}
- List programs = optProgram.stream().filter(program -> {
- boolean matches = abbreviation.map(abbr -> abbr.equals(program.getKey())).orElse(true);
- matches = matches && programDbId.map(id -> id.equals(program.getId().toString())).orElse(true);
- return matches && programName.map(name -> name.equals(program.getName())).orElse(true);
- }).map(this::convertToBrAPI).collect(Collectors.toList());
-
- return HttpResponse.ok(new BrAPIProgramListResponse().metadata(new BrAPIMetadata().pagination(new BrAPIIndexPagination().currentPage(0)
- .totalPages(1)
- .totalCount(programs.size())
- .pageSize(programs.size())))
- .result(new BrAPIProgramListResponseResult().data(programs)));
+ List programs = optProgram.stream().filter(program -> {
+ boolean matches = abbreviation.map(abbr -> abbr.equals(program.getKey())).orElse(true);
+ matches = matches && programDbId.map(id -> id.equals(program.getBrapiProgram().getProgramDbId())).orElse(true);
+ return matches && programName.map(name -> name.equals(program.getName())).orElse(true);
+ }).map(this::convertToBrAPI).collect(Collectors.toList());
+
+ return HttpResponse.ok(new BrAPIProgramListResponse().metadata(new BrAPIMetadata().pagination(new BrAPIIndexPagination().currentPage(0)
+ .totalPages(1)
+ .totalCount(programs.size())
+ .pageSize(programs.size())))
+ .result(new BrAPIProgramListResponseResult().data(programs)));
} else {
return HttpResponse.status(HttpStatus.NOT_FOUND, "Program not found");
}
@@ -181,12 +192,13 @@ public HttpResponse> programsPost(@PathVariable("programId") UUID programId, @
return HttpResponse.notFound();
}
- @Get("/programs/{programId}" + BrapiVersion.BRAPI_V2 + "/programs/{programDbId}")
+ @Get("/programs/{programId}" + BrapiVersion.BRAPI_V2 + "/programs/{brapiProgramDbId}")
@ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES})
- public HttpResponse programsProgramDbIdGet(@PathVariable("programId") UUID programId, @PathVariable("programDbId") String programDbId) {
- Optional program = programService.getById(programId)
+ public HttpResponse programsProgramDbIdGet(@PathVariable("programId") UUID biProgramId,
+ @PathVariable("brapiProgramDbId") String brapiProgramDbId) {
+ Optional program = programService.getById(biProgramId)
.stream()
- .filter(p -> programDbId.equals(programId.toString()))
+ .filter(p -> p.getBrapiProgram() != null && brapiProgramDbId.equals(p.getBrapiProgram().getProgramDbId()))
.map(this::convertToBrAPI)
.findFirst();
@@ -203,7 +215,8 @@ public HttpResponse> programsProgramDbIdPut(@PathVariable("programId") UUID pr
private BrAPIProgram convertToBrAPI(Program program) {
return new BrAPIProgram().programName(program.getName())
- .programDbId(program.getId().toString())
+ // Assumes brapiProgram is always set with the BrAPI programDbId
+ .programDbId(program.getBrapiProgram().getProgramDbId())
.abbreviation(program.getKey())
.commonCropName(program.getSpecies().getCommonName());
}
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPIStudiesController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPIStudiesController.java
index daadea133..88f7095c4 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPIStudiesController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPIStudiesController.java
@@ -17,7 +17,6 @@
package org.breedinginsight.brapi.v2;
-import io.micronaut.context.annotation.Property;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
@@ -29,22 +28,23 @@
import org.brapi.v2.model.BrAPIMetadata;
import org.brapi.v2.model.BrAPIStatus;
import org.brapi.v2.model.core.BrAPIStudy;
+import org.brapi.v2.model.core.response.BrAPIStudyListResponse;
import org.brapi.v2.model.core.response.BrAPIStudySingleResponse;
-import org.breedinginsight.api.auth.*;
-import org.breedinginsight.api.model.v1.request.query.SearchRequest;
+import org.breedinginsight.api.auth.ProgramSecured;
+import org.breedinginsight.api.auth.ProgramSecuredRole;
+import org.breedinginsight.api.auth.ProgramSecuredRoleGroup;
+import org.breedinginsight.api.auth.SecurityService;
import org.breedinginsight.api.model.v1.response.DataResponse;
import org.breedinginsight.api.model.v1.response.Response;
import org.breedinginsight.api.model.v1.validators.QueryValid;
import org.breedinginsight.brapi.v1.controller.BrapiVersion;
import org.breedinginsight.brapi.v2.model.request.query.StudyQuery;
import org.breedinginsight.brapi.v2.services.BrAPIStudyService;
-import org.breedinginsight.brapps.importer.services.ExternalReferenceSource;
import org.breedinginsight.model.Program;
import org.breedinginsight.model.ProgramUser;
import org.breedinginsight.services.ExperimentalCollaboratorService;
import org.breedinginsight.services.ProgramService;
import org.breedinginsight.services.ProgramUserService;
-import org.breedinginsight.services.exceptions.DoesNotExistException;
import org.breedinginsight.utilities.Utilities;
import org.breedinginsight.utilities.response.ResponseUtils;
import org.breedinginsight.utilities.response.mappers.StudyQueryMapper;
@@ -54,14 +54,12 @@
import java.util.List;
import java.util.Optional;
import java.util.UUID;
-import java.util.stream.Collectors;
@Slf4j
@Controller("/${micronaut.bi.api.version}/programs/{programId}" + BrapiVersion.BRAPI_V2)
@Secured(SecurityRule.IS_AUTHENTICATED)
public class BrAPIStudiesController {
- private final String referenceSource;
private final BrAPIStudyService studyService;
private final StudyQueryMapper studyQueryMapper;
private final ProgramService programService;
@@ -73,14 +71,12 @@ public class BrAPIStudiesController {
@Inject
public BrAPIStudiesController(BrAPIStudyService studyService,
StudyQueryMapper studyQueryMapper,
- @Property(name = "brapi.server.reference-source") String referenceSource,
ProgramService programService,
SecurityService securityService,
ProgramUserService programUserService,
ExperimentalCollaboratorService experimentalCollaboratorService) {
this.studyService = studyService;
this.studyQueryMapper = studyQueryMapper;
- this.referenceSource = referenceSource;
this.programService = programService;
this.securityService = securityService;
this.programUserService = programUserService;
@@ -91,34 +87,40 @@ public BrAPIStudiesController(BrAPIStudyService studyService,
@Produces(MediaType.APPLICATION_JSON)
@ProgramSecured( roles = {ProgramSecuredRole.SYSTEM_ADMIN, ProgramSecuredRole.READ_ONLY, ProgramSecuredRole.PROGRAM_ADMIN
,ProgramSecuredRole.EXPERIMENTAL_COLLABORATOR} )
- public HttpResponse>>> getStudies(
+ public HttpResponse>> getStudies(
@PathVariable("programId") UUID programId,
@QueryValue @QueryValid(using = StudyQueryMapper.class) @Valid StudyQuery queryParams) {
try {
Optional program = programService.getById(programId);
if (program.isEmpty()) { return HttpResponse.notFound(); }
- queryParams.setSortField(studyQueryMapper.getDefaultSortField());
- queryParams.setSortOrder(studyQueryMapper.getDefaultSortOrder());
- SearchRequest searchRequest = queryParams.constructSearchRequest();
+ if (queryParams.getSortField() == null) {
+ queryParams.setSortField(studyQueryMapper.getDefaultSortField());
+ }
+ if (queryParams.getSortOrder() == null) {
+ queryParams.setSortOrder(studyQueryMapper.getDefaultSortOrder());
+ }
log.debug("fetching studies for program: " + programId);
// If the program user is an experimental collaborator, filter results for only authorized studies.
Optional experimentalCollaborator = programUserService.getIfExperimentalCollaborator(programId, securityService.getUser().getId());
if (experimentalCollaborator.isPresent()) {
List authorizedExperimentIds = experimentalCollaboratorService.getAuthorizedExperimentIds(experimentalCollaborator.get().getId());
- List authorizedStudies = studyService.getStudiesByExperimentIds(program.get(), authorizedExperimentIds)
- .stream()
- .peek(this::setDbIds)
- .collect(Collectors.toList());
- return ResponseUtils.getBrapiQueryResponse(authorizedStudies, studyQueryMapper, queryParams, searchRequest);
+ if (authorizedExperimentIds.isEmpty()) {
+ return ResponseUtils.getEmptyBrapiQueryResponse();
+ }
+
+ BrAPIStudyListResponse brapiResponse = studyService.searchStudies(
+ program.get(),
+ authorizedExperimentIds,
+ queryParams);
+ List foundStudies = brapiResponse.getResult().getData();
+ return ResponseUtils.getBrapiQueryResponse(foundStudies, brapiResponse);
}
- List studies = studyService.getStudies(programId)
- .stream()
- .peek(this::setDbIds)
- .collect(Collectors.toList());
- return ResponseUtils.getBrapiQueryResponse(studies, studyQueryMapper, queryParams, searchRequest);
+ BrAPIStudyListResponse brapiResponse = studyService.searchStudies(program.get(), queryParams);
+ List foundStudies = brapiResponse.getResult().getData();
+ return ResponseUtils.getBrapiQueryResponse(foundStudies, brapiResponse);
} catch (ApiException e) {
log.info(e.getMessage(), e);
return HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, "Error retrieving study");
@@ -137,25 +139,31 @@ public HttpResponse studiesPost(@PathVariable("programId") UUID programId, @Body
@Get("/studies/{studyDbId}")
@ProgramSecured(roleGroups = {ProgramSecuredRoleGroup.PROGRAM_SCOPED_ROLES})
- public HttpResponse studiesStudyDbIdGet(@PathVariable("programId") UUID programId, @PathVariable("studyDbId") String environmentId) {
+ public HttpResponse studiesStudyDbIdGet(@PathVariable("programId") UUID programId, @PathVariable("studyDbId") String studyDbId) {
Optional program = programService.getById(programId);
- if(program.isEmpty()) {
+ if (program.isEmpty()) {
log.warn("program id: " + programId + " not found");
return HttpResponse.notFound();
}
+
try {
- Optional study = studyService.getStudyByEnvironmentId(program.get(), UUID.fromString(environmentId));
- if(study.isPresent()) {
- setDbIds(study.get());
- return HttpResponse.ok(new BrAPIStudySingleResponse().result(study.get()));
+ Optional study = studyService.getStudyByDbId(program.get(), studyDbId);
+
+ if (study.isPresent()) {
+ return HttpResponse.ok(
+ new BrAPIStudySingleResponse()
+ .result(study.get()));
} else {
- log.warn("studyDbId: " + environmentId + " not found");
+ log.warn("studyDbId: " + studyDbId + " not found");
return HttpResponse.notFound();
}
} catch (ApiException e) {
log.error(Utilities.generateApiExceptionLogMessage(e), e);
- return HttpResponse.serverError(new BrAPIStudySingleResponse().metadata(new BrAPIMetadata().addStatusItem(new BrAPIStatus().message("Error fetching study")
- .messageType(BrAPIStatus.MessageTypeEnum.ERROR))));
+ return HttpResponse.serverError(new BrAPIStudySingleResponse()
+ .metadata(new BrAPIMetadata()
+ .addStatusItem(new BrAPIStatus()
+ .message("Error fetching study")
+ .messageType(BrAPIStatus.MessageTypeEnum.ERROR))));
}
}
@@ -167,15 +175,4 @@ public HttpResponse studiesStudyDbIdPut(@PathVariable("programId") UUID programI
return HttpResponse.notFound();
}
- private void setDbIds(BrAPIStudy study) {
- study.studyDbId(Utilities.getExternalReference(study.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.STUDIES))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
-
- study.trialDbId(Utilities.getExternalReference(study.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.TRIALS))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
-
- //TODO update locationDbId
- }
}
diff --git a/src/main/java/org/breedinginsight/brapi/v2/BrAPITrialsController.java b/src/main/java/org/breedinginsight/brapi/v2/BrAPITrialsController.java
index 1ad489d91..60bd66dfa 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/BrAPITrialsController.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/BrAPITrialsController.java
@@ -27,6 +27,7 @@
import lombok.extern.slf4j.Slf4j;
import org.brapi.client.v2.model.exceptions.ApiException;
import org.brapi.v2.model.core.BrAPITrial;
+import org.brapi.v2.model.core.response.BrAPITrialListResponse;
import org.brapi.v2.model.core.response.BrAPITrialSingleResponse;
import org.breedinginsight.api.auth.*;
import org.breedinginsight.api.model.v1.request.query.SearchRequest;
@@ -42,8 +43,6 @@
import org.breedinginsight.services.ExperimentalCollaboratorService;
import org.breedinginsight.services.ProgramService;
import org.breedinginsight.services.ProgramUserService;
-import org.breedinginsight.model.ProgramUser;
-import org.breedinginsight.model.Role;
import org.breedinginsight.services.exceptions.DoesNotExistException;
import org.breedinginsight.utilities.Utilities;
import org.breedinginsight.utilities.response.ResponseUtils;
@@ -64,7 +63,6 @@ public class BrAPITrialsController {
private final String referenceSource;
private final BrAPITrialService experimentService;
- private final ExperimentQueryMapper experimentQueryMapper;
private final SecurityService securityService;
private final ProgramUserService programUserService;
private final ExperimentalCollaboratorService experimentalCollaboratorService;
@@ -72,14 +70,12 @@ public class BrAPITrialsController {
@Inject
public BrAPITrialsController(BrAPITrialService experimentService,
- ExperimentQueryMapper experimentQueryMapper,
@Property(name = "brapi.server.reference-source") String referenceSource,
SecurityService securityService,
ProgramUserService programUserService,
ExperimentalCollaboratorService experimentalCollaboratorService,
ProgramService programService) {
this.experimentService = experimentService;
- this.experimentQueryMapper = experimentQueryMapper;
this.referenceSource = referenceSource;
this.securityService = securityService;
this.programUserService = programUserService;
@@ -91,26 +87,37 @@ public BrAPITrialsController(BrAPITrialService experimentService,
@Produces(MediaType.APPLICATION_JSON)
@ProgramSecured(roles = {ProgramSecuredRole.SYSTEM_ADMIN, ProgramSecuredRole.READ_ONLY, ProgramSecuredRole.PROGRAM_ADMIN
,ProgramSecuredRole.EXPERIMENTAL_COLLABORATOR })
- public HttpResponse>>> getExperiments(
+ public HttpResponse>> getExperiments(
@PathVariable("programId") UUID programId,
@QueryValue @QueryValid(using = ExperimentQueryMapper.class) @Valid ExperimentQuery queryParams) {
try {
Optional program = programService.getById(programId);
if (program.isEmpty()) { return HttpResponse.notFound(); }
- SearchRequest searchRequest = queryParams.constructSearchRequest();
log.debug("fetching trials for program: " + programId);
// If the program user is an experimental collaborator, filter results for only authorized experiments.
Optional experimentalCollaborator = programUserService.getIfExperimentalCollaborator(programId, securityService.getUser().getId());
if (experimentalCollaborator.isPresent()) {
- List experimentIds = experimentalCollaboratorService.getAuthorizedExperimentIds(experimentalCollaborator.get().getId());
- List authorizedExperiments = experimentService.getTrialsByExperimentIds(program.get(), experimentIds).stream().peek(this::setDbIds).collect(Collectors.toList());
- return ResponseUtils.getBrapiQueryResponse(authorizedExperiments, experimentQueryMapper, queryParams, searchRequest);
+ List authorizedExperimentIds = experimentalCollaboratorService.getAuthorizedExperimentIds(experimentalCollaborator.get().getId());
+
+ if (authorizedExperimentIds.isEmpty()) {
+ // User is not authorized for any experiments, return empty response.
+ return ResponseUtils.getEmptyBrapiQueryResponse();
+ } else {
+ // User is authorized. Grab the experiment data from BrAPI.
+ BrAPITrialListResponse brapiResponse = experimentService.searchTrials(program.get(), authorizedExperimentIds, queryParams);
+
+ List foundTrials = brapiResponse.getResult().getData();
+
+ return ResponseUtils.getBrapiQueryResponse(foundTrials, brapiResponse);
+ }
}
- List experiments = experimentService.getExperiments(programId).stream().peek(this::setDbIds).collect(Collectors.toList());
- return ResponseUtils.getBrapiQueryResponse(experiments, experimentQueryMapper, queryParams, searchRequest);
+ BrAPITrialListResponse brapiResponse = experimentService.searchTrials(program.get(), queryParams);
+
+ List foundTrials = brapiResponse.getResult().getData();
+ return ResponseUtils.getBrapiQueryResponse(foundTrials, brapiResponse);
} catch (ApiException e) {
log.info(e.getMessage(), e);
return HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, "Error retrieving experiments");
@@ -135,7 +142,6 @@ public HttpResponse getExperimentById(
}
log.debug(logMsg);
BrAPITrial trial = experimentService.getTrialDataByUUID(programId, trialId, stats);
- setDbIds(trial);
return HttpResponse.ok(new BrAPITrialSingleResponse().result(trial));
} catch (DoesNotExistException e) {
log.info(e.getMessage(), e);
@@ -157,15 +163,4 @@ public HttpResponse> trialsTrialDbIdPut(@PathVariable("programId") UUID progra
//DO NOT IMPLEMENT - Users are only able to update trials via the DeltaBreed UI
return HttpResponse.notFound();
}
-
- private void setDbIds(BrAPITrial trial) {
- trial.trialDbId(Utilities.getExternalReference(trial.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.TRIALS))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
- trial.programDbId(Utilities.getExternalReference(trial.getExternalReferences(), Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.PROGRAMS))
- .orElseThrow(() -> new IllegalStateException("No BI external reference found"))
- .getReferenceID());
-
- //TODO update locationDbId
- }
}
diff --git a/src/main/java/org/breedinginsight/brapi/v2/constants/BrAPIAdditionalInfoFields.java b/src/main/java/org/breedinginsight/brapi/v2/constants/BrAPIAdditionalInfoFields.java
index 010bb15e9..4296b2c0b 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/constants/BrAPIAdditionalInfoFields.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/constants/BrAPIAdditionalInfoFields.java
@@ -52,7 +52,6 @@ public final class BrAPIAdditionalInfoFields {
public static final String GERMPLASM_UUID = "germplasmId";
public static final String SAMPLE_ORGANISM = "organism";
public static final String SAMPLE_SPECIES = "species";
- public static final String OBS_UNIT_ID = "obsUnitID";
public static final String GERMPLASM_NAME = "germplasmName";
public static final String SUBMISSION_NAME = "submissionName";
public static final String EXP_UNIT_ID = "expUnitID";
diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPICachedDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPICachedDAO.java
deleted file mode 100644
index 2d623b02b..000000000
--- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPICachedDAO.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package org.breedinginsight.brapi.v2.dao;
-
-import org.breedinginsight.daos.cache.ProgramCache;
-
-import java.util.UUID;
-
-public abstract class BrAPICachedDAO {
-
- protected ProgramCache programCache;
-
- public void repopulateCache(UUID programId) {
- this.programCache.invalidate(programId);
- this.programCache.populate(programId);
- }
-}
diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIGermplasmDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIGermplasmDAO.java
index 58910396b..bfe529e48 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIGermplasmDAO.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIGermplasmDAO.java
@@ -17,27 +17,31 @@
package org.breedinginsight.brapi.v2.dao;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
-import io.micronaut.context.annotation.Context;
import io.micronaut.context.annotation.Property;
+import io.micronaut.http.HttpStatus;
import io.micronaut.http.server.exceptions.InternalServerException;
-import io.micronaut.scheduling.annotation.Scheduled;
import lombok.extern.slf4j.Slf4j;
import org.brapi.client.v2.ApiResponse;
import org.brapi.client.v2.model.exceptions.ApiException;
+import org.brapi.client.v2.model.queryParams.germplasm.GermplasmQueryParams;
import org.brapi.client.v2.modules.germplasm.GermplasmApi;
import org.brapi.v2.model.BrAPIExternalReference;
+import org.brapi.v2.model.core.BrAPIListItemWithFullItem;
+import org.brapi.v2.model.core.BrAPIProgram;
+import org.brapi.v2.model.core.response.BrAPIListItemsListResponse;
import org.brapi.v2.model.germ.BrAPIGermplasm;
import org.brapi.v2.model.germ.BrAPIGermplasmSynonyms;
import org.brapi.v2.model.germ.request.BrAPIGermplasmSearchRequest;
+import org.brapi.v2.model.germ.response.BrAPIGermplasmListResponse;
import org.brapi.v2.model.germ.response.BrAPIGermplasmSingleResponse;
import org.breedinginsight.brapi.v2.constants.BrAPIAdditionalInfoFields;
+import org.breedinginsight.brapi.v2.model.request.query.GermplasmQuery;
import org.breedinginsight.brapps.importer.daos.ImportDAO;
import org.breedinginsight.brapps.importer.model.ImportUpload;
-import org.breedinginsight.brapps.importer.services.ExternalReferenceSource;
import org.breedinginsight.daos.ProgramDAO;
-import org.breedinginsight.daos.cache.ProgramCache;
-import org.breedinginsight.daos.cache.ProgramCacheProvider;
import org.breedinginsight.model.Program;
import org.breedinginsight.services.brapi.BrAPIEndpointProvider;
import org.breedinginsight.services.exceptions.DoesNotExistException;
@@ -47,61 +51,39 @@
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.*;
-import java.util.concurrent.Callable;
import java.util.stream.Collectors;
@Slf4j
@Singleton
-@Context
public class BrAPIGermplasmDAO {
private final ProgramDAO programDAO;
private final ImportDAO importDAO;
private final BrAPIDAOUtil brAPIDAOUtil;
+ private final ObjectMapper objectMapper;
+ private final BrAPIListDAO brAPIListDAO;
@Property(name = "brapi.server.reference-source")
private String referenceSource;
- @Property(name = "micronaut.bi.api.run-scheduled-tasks")
- private boolean runScheduledTasks;
-
- @Property(name = "brapi.paginate.germplasm")
- private boolean paginateGermplasm;
-
- private final ProgramCache programGermplasmCache;
+ @Property(name = "data-table.max-size")
+ private int dataTableMaxSize;
private final BrAPIEndpointProvider brAPIEndpointProvider;
@Inject
- public BrAPIGermplasmDAO(ProgramDAO programDAO, ImportDAO importDAO, BrAPIDAOUtil brAPIDAOUtil, ProgramCacheProvider programCacheProvider, BrAPIEndpointProvider brAPIEndpointProvider) {
+ public BrAPIGermplasmDAO(ProgramDAO programDAO,
+ ImportDAO importDAO,
+ BrAPIDAOUtil brAPIDAOUtil,
+ BrAPIEndpointProvider brAPIEndpointProvider,
+ ObjectMapper objectMapper,
+ BrAPIListDAO brAPIListDAO) {
this.programDAO = programDAO;
this.importDAO = importDAO;
this.brAPIDAOUtil = brAPIDAOUtil;
- this.programGermplasmCache = programCacheProvider.getProgramCache(this::fetchProgramGermplasm, BrAPIGermplasm.class);
this.brAPIEndpointProvider = brAPIEndpointProvider;
- }
-
- @Scheduled(initialDelay = "${startup.delay.germplasm}")
- public void setup() {
- if(!runScheduledTasks) {
- return;
- }
- // Populate germplasm cache for all programs on startup
- log.debug("populating germplasm cache");
- List programs = programDAO.getActive();
- if(programs != null) {
- programGermplasmCache.populate(programs.stream().map(Program::getId).collect(Collectors.toList()));
- }
- }
-
- /**
- * Fetch the germplasm for this program, and process it to remove storage specific values
- * @param programId
- * @return this program's germplasm
- * @throws ApiException
- */
- public List getGermplasm(UUID programId) throws ApiException {
- return new ArrayList<>(programGermplasmCache.get(programId).values());
+ this.objectMapper = objectMapper;
+ this.brAPIListDAO = brAPIListDAO;
}
/**
@@ -111,9 +93,10 @@ public List getGermplasm(UUID programId) throws ApiException {
* @throws ApiException
*/
public List getRawGermplasm(UUID programId) throws ApiException {
+ // TODO: This method is used for checking if germplasm already exist in the system. Once a generalized BrAPI exists check is made, we should update this method to optimize it [BI-2938]
Program program = new Program(programDAO.fetchOneById(programId));
- List cacheList = new ArrayList<>(programGermplasmCache.get(programId).values());
- return cacheList.stream().map(germplasm -> {
+ List programGermplasm = brapiGermplasmSearchReturnList(program, new BrAPIGermplasmSearchRequest());
+ return programGermplasm.stream().map(germplasm -> {
germplasm.setGermplasmName(Utilities.appendProgramKey(germplasm.getDefaultDisplayName(), program.getKey(), germplasm.getAccessionNumber()));
if(germplasm.getAdditionalInfo() != null && germplasm.getAdditionalInfo().has(BrAPIAdditionalInfoFields.GERMPLASM_RAW_PEDIGREE)
&& !(germplasm.getAdditionalInfo().get(BrAPIAdditionalInfoFields.GERMPLASM_RAW_PEDIGREE).isJsonNull())) {
@@ -124,59 +107,17 @@ public List getRawGermplasm(UUID programId) throws ApiException
}).collect(Collectors.toList());
}
-
- /**
- * Fetch formatted germplasm for this program
- * @param programId
- * @return Map
- * @throws ApiException
- */
- private Map fetchProgramGermplasm(UUID programId) throws ApiException {
- GermplasmApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), GermplasmApi.class);
- // Get the program key
- List programs = programDAO.get(programId);
- if (programs.size() != 1) {
- throw new InternalServerException("Program was not found for given key");
- }
- Program program = programs.get(0);
-
- // Set query params and make call
- BrAPIGermplasmSearchRequest germplasmSearch = new BrAPIGermplasmSearchRequest();
- germplasmSearch.externalReferenceIDs(List.of(programId.toString()));
- germplasmSearch.externalReferenceSources(List.of(Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.PROGRAMS)));
-
- if (paginateGermplasm) {
- log.debug("Fetching germplasm with pagination to BrAPI");
- return processGermplasmForDisplay(brAPIDAOUtil.search(
- api::searchGermplasmPost,
- api::searchGermplasmSearchResultsDbIdGet,
- germplasmSearch),
- program.getKey());
- } else {
- log.debug("Fetching germplasm without pagination to BrAPI");
- return processGermplasmForDisplay(brAPIDAOUtil.searchNoPaging(
- api::searchGermplasmPost,
- api::searchGermplasmSearchResultsDbIdGet,
- germplasmSearch),
- program.getKey());
- }
- }
-
- public void repopulateGermplasmCacheForProgram(UUID programId) {
- programGermplasmCache.populate(programId);
- }
-
/**
* Process germplasm into a format for display
- * @param programGermplasm
+ * @param germplasmToProcess
* @return Map
* @throws ApiException
*/
- private Map processGermplasmForDisplay(List programGermplasm, String programKey) {
+ private List processGermplasmForDisplay(List germplasmToProcess,
+ Program program) throws ApiException {
// Process the germplasm
- Map programGermplasmMap = new HashMap<>();
- log.trace("processing germ for display: " + programGermplasm);
- for (BrAPIGermplasm germplasm: programGermplasm) {
+ log.trace("processing germ for display: " + germplasmToProcess);
+ for (BrAPIGermplasm germplasm: germplasmToProcess) {
JsonObject additionalInfo = germplasm.getAdditionalInfo();
if (additionalInfo != null && additionalInfo.has(BrAPIAdditionalInfoFields.GERMPLASM_BREEDING_METHOD_ID)) {
@@ -190,14 +131,34 @@ private Map processGermplasmForDisplay(Listmale/femaleParentUUID. (See GermplasmProcessor.constructPedigreeString() for assignment of this data)
+ // To avoid completely re-working the importer to create pedigree nodes and associated germplasm referenced first, this "hack" relates the bi-generated exrefs
+ // to the brapi-generated germplasmDbId via an extra lookup and processing to the database.
+ // This is necessary because we need to overwrite bi-generated ids in the pedigree string to use the brapi germplasmDbIds so that front end reference links work properly.
+ // This should always work because processGermplasmForDisplay is only ever called once Germplasm data has been created in the database, and provided we improve lookups to not fetch
+ // all program germplasm at once, the performance hit should be negligible.
+ // TODO: This hack can be removed once/if we implement [BI-2588/BI-2452]
+ Map pedigreeBrAPIGermplasmDbIdByBICreatedExRef = null;
+
+ // This should ease concerns for extra time pulling this data. The intended usage is for the Germplasm data table,
+ // but any usage under 200 germs (current data table max size) should not be too large of a hit to the server or database.
+ boolean pedigreeExRefMutation = germplasmToProcess.size() <= dataTableMaxSize;
+
+ if (pedigreeExRefMutation) {
+ // Only perform this operation for callers that require it
+ pedigreeBrAPIGermplasmDbIdByBICreatedExRef = getPedigreeGermplasmDbIdByBICreatedExRef(germplasmToProcess, program);
+ }
+
// Update pedigree string
- for (BrAPIGermplasm germplasm: programGermplasm) {
+ for (BrAPIGermplasm germplasm: germplasmToProcess) {
JsonObject additionalInfo = germplasm.getAdditionalInfo();
if(additionalInfo == null) {
additionalInfo = new JsonObject();
@@ -222,7 +183,7 @@ private Map processGermplasmForDisplay(List processGermplasmForDisplay(List processGermplasmForDisplay(List processGermplasmForDisplay(List getPedigreeGermplasmDbIdByBICreatedExRef(List brAPIGermplasm, Program program) throws ApiException {
+ Map germplasmDbIdByGeneratedExRef = new HashMap<>();
+
+ // First, utilize initialized map to store all related parent bi-generated exref IDs.
+ for (BrAPIGermplasm germplasm : brAPIGermplasm) {
+ if (germplasm.getAdditionalInfo() == null) {
+ continue;
+ }
+ if (germplasm.getAdditionalInfo().has(BrAPIAdditionalInfoFields.GERMPLASM_FEMALE_PARENT_UUID)) {
+ try {
+ UUID.fromString(germplasm.getAdditionalInfo().get(BrAPIAdditionalInfoFields.GERMPLASM_FEMALE_PARENT_UUID).getAsString());
+ } catch (IllegalArgumentException e) {
+ throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), String.format("Germplasm with BrAPI dbId [%s] has an additionalInfo.femaleParentUUID that is not a UUID", germplasm.getGermplasmDbId()));
+ }
+ germplasmDbIdByGeneratedExRef.put(germplasm.getAdditionalInfo().get(BrAPIAdditionalInfoFields.GERMPLASM_FEMALE_PARENT_UUID).getAsString(), null);
+ }
+ if (germplasm.getAdditionalInfo().has(BrAPIAdditionalInfoFields.GERMPLASM_MALE_PARENT_UUID)) {
+ try {
+ UUID.fromString(germplasm.getAdditionalInfo().get(BrAPIAdditionalInfoFields.GERMPLASM_MALE_PARENT_UUID).getAsString());
+ } catch (IllegalArgumentException e) {
+ throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR.getCode(), String.format("Germplasm with BrAPI dbId [%s] has an additionalInfo.maleParentUUID that is not a UUID", germplasm.getGermplasmDbId()));
+ }
+ germplasmDbIdByGeneratedExRef.put(germplasm.getAdditionalInfo().get(BrAPIAdditionalInfoFields.GERMPLASM_MALE_PARENT_UUID).getAsString(), null);
+ }
+ }
- BrAPIExternalReference extRef = germplasm.getExternalReferences().stream().filter(reference -> referenceSource.equals(reference.getReferenceSource())).findFirst().orElseThrow(() -> new IllegalStateException("No BI external reference found"));
- String germplasmId = extRef.getReferenceID();
- programGermplasmMap.put(germplasmId, germplasm);
+ if (germplasmDbIdByGeneratedExRef.isEmpty()) {
+ // If there are none, no reason to proceed with a BrAPI search.
+ return germplasmDbIdByGeneratedExRef;
}
- return programGermplasmMap;
+ // Now grab all male/female exrefs and search for them to get their germplasmDbIds
+ List exRefIds = new ArrayList<>(germplasmDbIdByGeneratedExRef.keySet());
+
+ BrAPIGermplasmSearchRequest searchRequest = new BrAPIGermplasmSearchRequest();
+ searchRequest.setExternalReferenceIds(exRefIds);
+ searchRequest.setExternalReferenceSources(List.of(referenceSource));
+
+ // Reuse some code to properly set searchRequest with brapiProgramDbId, and proper paging
+ searchRequest = buildSearchRequest(program, searchRequest, null);
+
+ GermplasmApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(program.getId()), GermplasmApi.class);
+
+
+ // This will use CACHE_BRAPI_FETCH_PAGE_SIZE env variable to lookup at maximum 65k pedigree germplasm at once.
+ // This should not be normal though, as we should try not to exceed 1k lookups at once using this code.
+ // If there is a need to look up a large amount of germplasm records at once, alternative methods should be used.
+ List germplasmSearchedWithExRef = brAPIDAOUtil.searchNoPageThru(
+ api::searchGermplasmPost,
+ api::searchGermplasmSearchResultsDbIdGet,
+ searchRequest);
+
+ for (BrAPIGermplasm germplasm : germplasmSearchedWithExRef) {
+ Optional exRef = Utilities.getExternalReference(germplasm.getExternalReferences(), referenceSource);
+
+ if (exRef.isPresent()) {
+ germplasmDbIdByGeneratedExRef.put(exRef.get().getReferenceId(), germplasm.getGermplasmDbId());
+ } else {
+ throw new IllegalStateException("External references wasn't found for germplasm (dbid): " + germplasm.getGermplasmDbId());
+ }
+ }
+
+ return germplasmDbIdByGeneratedExRef;
}
public List createBrAPIGermplasm(List postBrAPIGermplasmList, UUID programId, ImportUpload upload) {
GermplasmApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), GermplasmApi.class);
- var program = programDAO.fetchOneById(programId);
+ var program = new Program(programDAO.fetchOneById(programId));
try {
if (!postBrAPIGermplasmList.isEmpty()) {
List postResponse = brAPIDAOUtil.post(postBrAPIGermplasmList, upload, api::germplasmPost, importDAO::update);
- return new ArrayList<>(processGermplasmForDisplay(postResponse, program.getKey()).values());
+ return processGermplasmForDisplay(postResponse, program);
}
return new ArrayList<>();
} catch (Exception e) {
@@ -296,14 +330,11 @@ public List createBrAPIGermplasm(List postBrAPIG
public List updateBrAPIGermplasm(List putBrAPIGermplasmList, UUID programId, ImportUpload upload) {
GermplasmApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), GermplasmApi.class);
- var program = programDAO.fetchOneById(programId);
+ var program = new Program(programDAO.fetchOneById(programId));
try {
if (!putBrAPIGermplasmList.isEmpty()) {
- Callable> postFunction = () -> {
- List putResponse = putGermplasm(putBrAPIGermplasmList, api);
- return processGermplasmForDisplay(putResponse, program.getKey());
- };
- return programGermplasmCache.post(programId, postFunction);
+ List putResponse = putGermplasm(putBrAPIGermplasmList, api);
+ return processGermplasmForDisplay(putResponse, program);
}
return new ArrayList<>();
} catch (Exception e) {
@@ -313,58 +344,110 @@ public List updateBrAPIGermplasm(List putBrAPIGe
public List getGermplasmByRawName(List germplasmNames, UUID programId) throws ApiException {
Program program = new Program(programDAO.fetchOneById(programId));
- return getGermplasm(programId)
- .stream()
- .filter(brAPIGermplasm -> germplasmNames.contains(Utilities.appendProgramKey(brAPIGermplasm.getGermplasmName(),program.getKey(),brAPIGermplasm.getAccessionNumber())))
- .collect(Collectors.toList());
- }
- public BrAPIGermplasm getGermplasmByUUID(String germplasmId, UUID programId) throws ApiException, DoesNotExistException {
- Map cache = programGermplasmCache.get(programId);
- BrAPIGermplasm germplasm = null;
- if (cache != null) {
- germplasm = cache.get(germplasmId);
- }
- if (germplasm == null) {
- throw new DoesNotExistException("UUID for this germplasm does not exist");
+ if (germplasmNames.isEmpty()) {
+ return new ArrayList<>();
}
- return germplasm;
+
+ BrAPIGermplasmSearchRequest searchRequest = new BrAPIGermplasmSearchRequest();
+ searchRequest.setGermplasmNames(germplasmNames);
+
+ searchRequest = buildSearchRequest(program, searchRequest, null);
+
+ GermplasmApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(program.getId()), GermplasmApi.class);
+
+ List germplasm = brAPIDAOUtil.search(
+ api::searchGermplasmPost,
+ api::searchGermplasmSearchResultsDbIdGet,
+ searchRequest);
+
+ return processGermplasmForDisplay(germplasm, program);
}
- public List getGermplasmDbIdsForUUIDs(List germplasmUUIDs, UUID programId) throws ApiException, DoesNotExistException {
- Map cache = programGermplasmCache.get(programId);
- List germplasmList = new ArrayList<>();
- if (cache != null) {
- // not using streams because want to throw checked exception
- for (String germplasmUUID : germplasmUUIDs) {
- BrAPIGermplasm germplasm = cache.get(germplasmUUID);
- if (germplasm == null) {
- throw new DoesNotExistException("UUID for this germplasm does not exist: " + germplasmUUID);
- }
- germplasmList.add(germplasm.getGermplasmDbId());
- }
+ public BrAPIListItemsListResponse searchGermplasmByList(String listDbId, UUID programId, GermplasmQuery germplasmQuery) throws ApiException {
+ Program program = new Program(programDAO.fetchOneById(programId));
+
+ BrAPIGermplasmSearchRequest searchRequest = buildSearchRequest(program, null, germplasmQuery);
+
+ // Because the list item search endpoint is generalized, a typed BrAPISearchRequest won't work, so convert it to JsonNode.
+ // The search request type is derived by the client/prod server based off of the type of the submitted list dbId.
+ JsonNode listRequestBody = objectMapper.valueToTree(searchRequest);
+
+ BrAPIListItemsListResponse response = brAPIListDAO.searchBrAPIListItemsByList(listDbId, programId, listRequestBody);
+
+ processGermplasmForDisplay(response.getResult().getData().stream().map(BrAPIListItemWithFullItem::getItem).collect(Collectors.toList()), program);
+
+ return response;
+ }
+
+ public List brapiGermplasmSearchReturnList(Program program,
+ BrAPIGermplasmSearchRequest searchRequest) throws ApiException {
+ return brapiGermplasmSearchReturnResponse(program, searchRequest, null).getResult().getData();
+ }
+
+ public BrAPIGermplasmListResponse brapiGermplasmSearchReturnResponse(Program program,
+ BrAPIGermplasmSearchRequest searchRequest,
+ GermplasmQuery germplasmQuery) throws ApiException {
+
+ GermplasmApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(program.getId()), GermplasmApi.class);
+
+ BrAPIGermplasmSearchRequest brAPIGermplasmSearchRequest = buildSearchRequest(program, searchRequest, germplasmQuery);
+
+ BrAPIGermplasmListResponse brAPIResponse =
+ brAPIDAOUtil.searchReturnResponse(
+ api::searchGermplasmPost,
+ api::searchGermplasmSearchResultsDbIdGet,
+ brAPIGermplasmSearchRequest
+ );
+
+ List processedGermplasm = processGermplasmForDisplay(brAPIDAOUtil.getListResult(brAPIResponse), program);
+
+ brAPIResponse.getResult().setData(processedGermplasm);
+
+ return brAPIResponse;
+ }
+
+ private BrAPIGermplasmSearchRequest buildSearchRequest(Program program, BrAPIGermplasmSearchRequest searchRequestPassThru, GermplasmQuery germplasmQuery) throws ApiException {
+ BrAPIGermplasmSearchRequest searchRequest;
+
+ if (searchRequestPassThru == null) {
+ searchRequest = new BrAPIGermplasmSearchRequest();
+ } else {
+ searchRequest = searchRequestPassThru;
}
- return germplasmList;
+
+ searchRequest.programDbIds(List.of(brAPIDAOUtil.getBrAPIProgramDbId(program.getId())));
+
+ brAPIDAOUtil.setGenericSearchParameters(searchRequest, germplasmQuery);
+
+ return searchRequest;
}
- public Optional getGermplasmByDBID(String germplasmDbId, UUID programId) throws ApiException {
- Map cache = programGermplasmCache.get(programId);
- //key is UUID, want to filter by DBID
- BrAPIGermplasm germplasm = null;
- if (cache != null) {
- germplasm = cache.values().stream().filter(x -> x.getGermplasmDbId().equals(germplasmDbId)).collect(Collectors.toList()).get(0);
+ public BrAPIGermplasm getGermplasmByUUID(String germplasmId, UUID programId) throws ApiException, DoesNotExistException {
+ Program program = new Program(programDAO.fetchOneById(programId));
+
+ BrAPIGermplasmSearchRequest searchRequest = new BrAPIGermplasmSearchRequest();
+ searchRequest.setGermplasmDbIds(List.of(germplasmId));
+
+ List result = brapiGermplasmSearchReturnList(program, searchRequest);
+
+ if (result.size() > 1) {
+ throw new ApiException(String.format("Multiple germplasms found for germplasm with ID: [%s]", germplasmId));
+ } else if (result.isEmpty()) {
+ throw new DoesNotExistException(String.format("Germplasm with ID: [%s] does not exist", germplasmId));
}
- return Optional.ofNullable(germplasm);
+
+ return result.get(0);
}
public List getGermplasmsByDBID(Collection germplasmDbIds, UUID programId) throws ApiException {
- Map cache = programGermplasmCache.get(programId);
- //key is UUID, want to filter by DBID
- List germplasm = new ArrayList<>();
- if (cache != null) {
- germplasm = cache.values().stream().filter(x -> germplasmDbIds.contains(x.getGermplasmDbId())).collect(Collectors.toList());
- }
- return germplasm;
+ // This method is mainly used by the download experiment export tool.
+ Program program = new Program(programDAO.fetchOneById(programId));
+
+ BrAPIGermplasmSearchRequest searchRequest = new BrAPIGermplasmSearchRequest();
+ searchRequest.setGermplasmDbIds(new ArrayList<>(germplasmDbIds));
+
+ return brapiGermplasmSearchReturnList(program, searchRequest);
}
public List putGermplasm(List germplasmList, GermplasmApi api) throws ApiException {
diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIListDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIListDAO.java
index 4f6cfdec7..be9b3fcd3 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIListDAO.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIListDAO.java
@@ -17,6 +17,7 @@
package org.breedinginsight.brapi.v2.dao;
+import com.fasterxml.jackson.databind.JsonNode;
import io.micronaut.http.HttpResponse;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
@@ -27,14 +28,13 @@
import org.brapi.v2.model.BrAPIExternalReference;
import org.brapi.v2.model.BrAPIResponse;
import org.brapi.v2.model.BrAPIResponseResult;
+import org.brapi.v2.model.core.BrAPIListItemWithFullItem;
import org.brapi.v2.model.core.BrAPIListSummary;
import org.brapi.v2.model.core.BrAPIListTypes;
import org.brapi.v2.model.core.request.BrAPIListNewRequest;
import org.brapi.v2.model.core.request.BrAPIListSearchRequest;
-import org.brapi.v2.model.core.response.BrAPIListDetails;
-import org.brapi.v2.model.core.response.BrAPIListsListResponse;
-import org.brapi.v2.model.core.response.BrAPIListsListResponseResult;
-import org.brapi.v2.model.core.response.BrAPIListsSingleResponse;
+import org.brapi.v2.model.core.response.*;
+import org.brapi.v2.model.germ.BrAPIGermplasm;
import org.breedinginsight.brapps.importer.daos.ImportDAO;
import org.breedinginsight.brapps.importer.model.ImportUpload;
import org.breedinginsight.daos.ProgramDAO;
@@ -71,7 +71,7 @@ public BrAPIListDAO(ProgramDAO programDAO,
}
public List getListsByName(List listNames, UUID programId) throws ApiException {
- if(listNames.isEmpty()) {
+ if (listNames.isEmpty()) {
return Collections.emptyList();
}
@@ -122,11 +122,11 @@ private List processListsForProgram(List pro
// check that all lists were created via the BI UI in case the BrAPI service silently ignores the search by
// externalReference source and ID
List filteredLists = new ArrayList<>();
- for (BrAPIListSummary list: programLists) {
+ for (BrAPIListSummary list : programLists) {
if (list.getExternalReferences() == null || list.getExternalReferences().size() == 0) {
continue;
} else {
- for (BrAPIExternalReference ref: list.getExternalReferences()) {
+ for (BrAPIExternalReference ref : list.getExternalReferences()) {
if (ref.getReferenceID().equals(externalReferenceId.toString()) &&
ref.getReferenceSource().equals(externalReferenceSource)) {
filteredLists.add(list);
@@ -136,6 +136,7 @@ private List processListsForProgram(List pro
}
return filteredLists;
}
+
public List updateBrAPIList(String brAPIListDbId, BrAPIListDetails mutatedList, UUID programId) throws ApiException {
ListsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ListsApi.class);
BrAPIListNewRequest request = new BrAPIListNewRequest();
@@ -160,7 +161,7 @@ public List updateBrAPIList(String brAPIListDbId, BrAPIListDetails mutat
log.error(Utilities.generateApiExceptionLogMessage(e));
throw e;
}
- if(response != null) {
+ if (response != null) {
BrAPIListsSingleResponse body = response.getBody();
if (body == null) {
throw new ApiException("Response is missing body", 0, response.getHeaders(), null);
@@ -188,7 +189,7 @@ public List createBrAPILists(List brapiLi
log.warn(Utilities.generateApiExceptionLogMessage(e));
throw e;
}
- if(response != null) {
+ if (response != null) {
BrAPIResponse body = response.getBody();
if (body == null) {
throw new ApiException("Response is missing body", 0, response.getHeaders(), null);
@@ -220,4 +221,32 @@ public HttpResponse deleteBrAPIList(String listDbId, UUID programId, boo
return brAPIDAOUtil.makeCall(brapiRequest);
}
+ public BrAPIListItemsListResponse searchBrAPIListItemsByList(String listDbId, UUID programId, JsonNode requestBody) throws ApiException {
+ ListsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ListsApi.class);
+ // Do manually, it doesn't like List to List for some reason
+ ApiResponse> response;
+ try {
+ response = api.searchListItemsByList(listDbId, requestBody);
+ } catch (ApiException e) {
+ log.warn(Utilities.generateApiExceptionLogMessage(e));
+ throw e;
+ }
+
+ if (response != null) {
+ BrAPIResponse> body = response.getBody();
+ if (body == null) {
+ throw new ApiException("Response is missing body", 0, response.getHeaders(), null);
+ }
+ BrAPIResponseResult> result = body.getResult();
+ if (result == null) {
+ throw new ApiException("Response body is missing result", 0, response.getHeaders(), response.getBody().toString());
+ }
+ if (result.getData() == null) {
+ throw new ApiException("Response result is missing data", 0, response.getHeaders(), response.getBody().toString());
+ }
+ return response.getBody();
+ }
+
+ throw new ApiException("No response for BrAPI list item search");
+ }
}
diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java
index 10048564c..dfc041da8 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationDAO.java
@@ -18,129 +18,59 @@
import io.micronaut.context.annotation.Property;
import io.micronaut.http.server.exceptions.InternalServerException;
-import io.micronaut.scheduling.annotation.Scheduled;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.tuple.Pair;
-import org.brapi.client.v2.ApiResponse;
import org.brapi.client.v2.model.exceptions.ApiException;
+import org.brapi.client.v2.model.queryParams.phenotype.ObservationQueryParams;
import org.brapi.client.v2.modules.phenotype.ObservationsApi;
-import org.brapi.v2.model.BrAPIAcceptedSearchResponse;
-import org.brapi.v2.model.BrAPIExternalReference;
+import org.brapi.v2.model.core.BrAPIProgram;
import org.brapi.v2.model.pheno.BrAPIObservation;
import org.brapi.v2.model.pheno.BrAPIObservationUnit;
import org.brapi.v2.model.pheno.request.BrAPIObservationSearchRequest;
import org.brapi.v2.model.pheno.response.BrAPIObservationListResponse;
-import org.brapi.v2.model.pheno.response.BrAPIObservationSingleResponse;
import org.breedinginsight.brapps.importer.daos.ImportDAO;
import org.breedinginsight.brapps.importer.model.ImportUpload;
-import org.breedinginsight.brapps.importer.services.ExternalReferenceSource;
import org.breedinginsight.daos.ProgramDAO;
-import org.breedinginsight.daos.cache.ProgramCacheProvider;
import org.breedinginsight.model.Program;
-import org.breedinginsight.model.Trait;
import org.breedinginsight.services.TraitService;
import org.breedinginsight.services.brapi.BrAPIEndpointProvider;
import org.breedinginsight.services.exceptions.DoesNotExistException;
import org.breedinginsight.utilities.BrAPIDAOUtil;
import org.breedinginsight.utilities.Utilities;
-import org.jetbrains.annotations.NotNull;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.*;
-import java.util.concurrent.Callable;
import java.util.stream.Collectors;
-import static org.brapi.v2.model.BrAPIWSMIMEDataTypes.APPLICATION_JSON;
-
@Singleton
@Slf4j
-public class BrAPIObservationDAO extends BrAPICachedDAO {
+public class BrAPIObservationDAO {
private ProgramDAO programDAO;
private ImportDAO importDAO;
private BrAPIObservationUnitDAO observationUnitDAO;
private final BrAPIDAOUtil brAPIDAOUtil;
private final BrAPIEndpointProvider brAPIEndpointProvider;
- private final String referenceSource;
- private boolean runScheduledTasks;
private final TraitService traitService;
+ private final int brapiMaxPageSize;
+
@Inject
public BrAPIObservationDAO(ProgramDAO programDAO,
ImportDAO importDAO,
BrAPIObservationUnitDAO observationUnitDAO,
BrAPIDAOUtil brAPIDAOUtil,
BrAPIEndpointProvider brAPIEndpointProvider,
- @Property(name = "brapi.server.reference-source") String referenceSource,
- @Property(name = "micronaut.bi.api.run-scheduled-tasks") boolean runScheduledTasks,
- ProgramCacheProvider programCacheProvider, TraitService traitService) {
+ @Property(name = "brapi.page-thru.page-size") int brapiFetchPageSize,
+ TraitService traitService) {
this.programDAO = programDAO;
this.importDAO = importDAO;
this.observationUnitDAO = observationUnitDAO;
this.brAPIDAOUtil = brAPIDAOUtil;
this.brAPIEndpointProvider = brAPIEndpointProvider;
- this.referenceSource = referenceSource;
- this.runScheduledTasks = runScheduledTasks;
this.traitService = traitService;
- this.programCache = programCacheProvider.getProgramCache(this::fetchProgramObservations, BrAPIObservation.class);
- }
-
- @Scheduled(initialDelay = "${startup.delay.observation}")
- public void setup() {
- if(!runScheduledTasks) {
- return;
- }
- // Populate the observation cache for all programs on startup.
- log.debug("populating observation cache");
- List programs = programDAO.getActive();
- if (programs != null) {
- programCache.populate(programs.stream().map(Program::getId).collect(Collectors.toList()));
- }
- }
-
- /**
- * Fetch formatted observations for this program.
- */
- private Map fetchProgramObservations(UUID programId) throws ApiException {
- ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ObservationsApi.class);
- // Get the program.
- List programs = programDAO.get(programId);
- if (programs.size() != 1) {
- throw new InternalServerException("Program was not found for given id");
- }
- Program program = programs.get(0);
-
- // Set query params and make call.
- BrAPIObservationSearchRequest observationSearch = new BrAPIObservationSearchRequest();
- observationSearch.externalReferenceIds(List.of(programId.toString()));
- observationSearch.externalReferenceSources(List.of(Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.PROGRAMS)));
- return processObservationsForCache(brAPIDAOUtil.search(
- api::searchObservationsPost,
- api::searchObservationsSearchResultsDbIdGet,
- observationSearch
- ), program.getKey());
- }
-
- /**
- * Process a list of observations for insertion into the cache.
- */
- private Map processObservationsForCache(List programObservations, String programKey) {
- // Process programObservations in place (strip program key, etc.).
- processObservations(programKey, programObservations);
- // Build map.
- Map programObservationsMap = new HashMap<>();
- log.trace("processing observationUnits for cache: " + programObservations);
- for (BrAPIObservation observation: programObservations) {
- BrAPIExternalReference xref = observation
- .getExternalReferences()
- .stream()
- .filter(reference -> String.format("%s/%s", referenceSource, ExternalReferenceSource.OBSERVATIONS.getName()).equals(reference.getReferenceSource()))
- .findFirst().orElseThrow(() -> new IllegalStateException("No BI external reference found"));
- programObservationsMap.put(xref.getReferenceId(), observation);
- }
- return programObservationsMap;
+ this.brapiMaxPageSize = brapiFetchPageSize;
}
/**
@@ -162,14 +92,6 @@ private void processObservations(String programKey, List obser
}
}
- /**
- * Get all observations for a program from the cache.
- */
- private Map getProgramObservations(UUID programId) throws ApiException {
- return programCache.get(programId);
- }
-
- // Note: not using cache, because unique studyName (with "[ProgramKey-ExtraInfo]") is not stored directly on Observation.
public List getObservationsByStudyName(List studyNames, Program program) throws ApiException {
if(studyNames.isEmpty()) {
return Collections.emptyList();
@@ -181,9 +103,23 @@ public List getObservationsByStudyName(List studyNames
ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(program.getId()), ObservationsApi.class);
return brAPIDAOUtil.search(
api::searchObservationsPost,
- (brAPIWSMIMEDataTypes, searchResultsDbId, page, pageSize) -> searchObservationsSearchResultsDbIdGet(program.getId(), searchResultsDbId, page, pageSize),
+ api::searchObservationsSearchResultsDbIdGet,
+ observationSearchRequest
+ );
+ }
+
+ private List searchBrapiObservations(BrAPIObservationSearchRequest observationSearchRequest, Program program) throws ApiException {
+ ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(program.getId()), ObservationsApi.class);
+
+ List observations = brAPIDAOUtil.search(
+ api::searchObservationsPost,
+ api::searchObservationsSearchResultsDbIdGet,
observationSearchRequest
);
+
+ processObservations(program.getKey(), observations);
+
+ return observations;
}
/**
@@ -196,97 +132,80 @@ public List getObservationsByStudyName(List studyNames
*/
public List getObservationsByDbIds(List dbIds, Program program) throws ApiException {
// Check if the dbIds list is empty and return an empty list if so
- if(dbIds.isEmpty()) {
+ if (dbIds.isEmpty()) {
return Collections.emptyList();
}
- // Filter the observations based on the provided program ID and the provided list of dbIds
- // Collect the filtered observations into a List and return the result
- return getProgramObservations(program.getId()).values().stream()
- .filter(o -> dbIds.contains(o.getObservationDbId()))
- .collect(Collectors.toList());
+ BrAPIObservationSearchRequest observationSearchRequest = new BrAPIObservationSearchRequest()
+ .programDbIds(List.of(program.getBrapiProgram().getProgramDbId()))
+ .observationDbIds(new ArrayList<>(dbIds));
+
+ return searchBrapiObservations(observationSearchRequest, program);
}
public List getObservationsByTrialDbId(List trialDbIds, Program program) throws ApiException {
- if(trialDbIds.isEmpty()) {
+ if (trialDbIds.isEmpty()) {
return Collections.emptyList();
}
// First, get all ObservationUnits for the given trialDbIds.
List observationUnitDbIds = observationUnitDAO.getObservationUnitsForTrialDbIds(program.getId(), trialDbIds)
.stream().map(BrAPIObservationUnit::getObservationUnitDbId).collect(Collectors.toList());
- // Finally, return all Observations for those ObservationUnits (Observations are linked to Trial through ObservationUnits).
- return getProgramObservations(program.getId()).values().stream()
- .filter(o -> observationUnitDbIds.contains(o.getObservationUnitDbId()))
- .collect(Collectors.toList());
+
+ if (observationUnitDbIds.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ BrAPIObservationSearchRequest observationSearchRequest = new BrAPIObservationSearchRequest()
+ .programDbIds(List.of(program.getBrapiProgram().getProgramDbId()))
+ .observationUnitDbIds(observationUnitDbIds);
+
+ return searchBrapiObservations(observationSearchRequest, program);
}
public List getObservationsByObservationUnitsAndVariables(Collection ouDbIds, Collection variableDbIds, Program program) throws ApiException {
- if(ouDbIds.isEmpty() || variableDbIds.isEmpty()) {
+ if (ouDbIds.isEmpty() || variableDbIds.isEmpty()) {
return Collections.emptyList();
}
- return getProgramObservations(program.getId()).values().stream()
- .filter(o -> ouDbIds.contains(o.getObservationUnitDbId()) && variableDbIds.contains(o.getObservationVariableDbId()))
- .collect(Collectors.toList());
+
+ BrAPIObservationSearchRequest observationSearchRequest = new BrAPIObservationSearchRequest()
+ .programDbIds(List.of(program.getBrapiProgram().getProgramDbId()))
+ .observationUnitDbIds(new ArrayList<>(ouDbIds))
+ .observationVariableDbIds(new ArrayList<>(variableDbIds));
+
+ return searchBrapiObservations(observationSearchRequest, program);
}
public List getObservationsByObservationUnits(Collection ouDbIds, Program program) throws ApiException {
- if(ouDbIds.isEmpty()) {
+
+ if (ouDbIds.isEmpty()) {
return Collections.emptyList();
}
- return getProgramObservations(program.getId()).values().stream()
- .filter(o -> ouDbIds.contains(o.getObservationUnitDbId()))
- .collect(Collectors.toList());
+
+ BrAPIObservationSearchRequest observationSearchRequest = new BrAPIObservationSearchRequest()
+ .programDbIds(List.of(program.getBrapiProgram().getProgramDbId()))
+ .observationUnitDbIds(new ArrayList<>(ouDbIds));
+
+ return searchBrapiObservations(observationSearchRequest, program);
}
- public List getObservationsByObservationUnitsAndStudies(Collection ouDbIds, Collection studyDbIds, Program program) throws ApiException {
- if(ouDbIds.isEmpty()) {
- return Collections.emptyList();
+ public BrAPIObservationListResponse getObservationsByFilters(Program program, String studyDbId, Integer page, Integer pageSize) throws ApiException {
+ BrAPIObservationSearchRequest observationSearchRequest = new BrAPIObservationSearchRequest()
+ .programDbIds(List.of(program.getBrapiProgram().getProgramDbId()));
+
+ if (studyDbId != null) {
+ observationSearchRequest.setStudyDbIds(List.of(studyDbId));
}
- return getProgramObservations(program.getId()).values().stream()
- .filter(o -> ouDbIds.contains(o.getObservationUnitDbId()) && studyDbIds.contains(o.getStudyDbId()))
- .collect(Collectors.toList());
- }
+ observationSearchRequest.setPage(page);
+ observationSearchRequest.setPageSize(pageSize);
- // TODO: implement other filters in BI-2506.
- public List getObservationsByFilters(Program program, String studyDbId) throws ApiException, DoesNotExistException {
-
- String studySource = Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.STUDIES);
- String observationUnitSource = Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.OBSERVATION_UNITS);
- String observationSource = Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.OBSERVATIONS);
-
- // Get all observations for the program.
- Collection observations = getProgramObservations(program.getId()).values();
- // Build a hashmap of traits for fast lookup. The key is ObservationVariableDbId, the value is the Trait Id.
- HashMap traitIdsByObservationVariableDbId = traitService.getIdsByObservationVariableDbIds(program.getId(), observations.stream().map(BrAPIObservation::getObservationVariableDbId).collect(Collectors.toList()));
-
- // Lookup studyDbId.
- return observations.stream()
- .filter(o -> {
- // Short circuit if filter is null.
- if (studyDbId == null) return true;
- Optional xref = Utilities.getExternalReference(o.getExternalReferences(), studySource);
- return xref.filter(brAPIExternalReference -> studyDbId.equals(brAPIExternalReference.getReferenceId())).isPresent();
- })
- .peek(o -> {
- // Translate ObservationVariableDbId.
- o.setObservationVariableDbId(traitIdsByObservationVariableDbId.get(o.getObservationVariableDbId()));
- // Translate ObservationUnitDbId.
- o.setObservationUnitDbId(Utilities.getExternalReference(o.getExternalReferences(), observationUnitSource)
- .orElseThrow(() -> new RuntimeException("observationUnit xref not found on observation")).getReferenceId());
- // Translate ObservationId.
- o.setObservationDbId(Utilities.getExternalReference(o.getExternalReferences(), observationSource)
- .orElseThrow(() -> new RuntimeException("observation xref not found on observation")).getReferenceId());
- // Translate StudyDbId.
- o.setStudyDbId(Utilities.getExternalReference(o.getExternalReferences(), studySource)
- .orElseThrow(() -> new RuntimeException("study xref not found on observation")).getReferenceId());
- // TODO: consider translating germplasmDbId in BI-2506.
- }).collect(Collectors.toList());
- }
+ ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(program.getId()), ObservationsApi.class);
- @NotNull
- private ApiResponse, Optional>> searchObservationsSearchResultsDbIdGet(UUID programId, String searchResultsDbId, Integer page, Integer pageSize) throws ApiException {
- ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ObservationsApi.class);
- return api.searchObservationsSearchResultsDbIdGet(APPLICATION_JSON, searchResultsDbId, page, pageSize);
+ BrAPIObservationListResponse brAPIResponse = brAPIDAOUtil.searchReturnResponse(api::searchObservationsPost, api::searchObservationsSearchResultsDbIdGet, observationSearchRequest);
+
+ List observations = brAPIDAOUtil.getListResult(brAPIResponse);
+ processObservations(program.getKey(), observations);
+
+ return brAPIResponse;
}
public List createBrAPIObservations(List brAPIObservationList, UUID programId, ImportUpload upload) throws ApiException {
@@ -294,11 +213,9 @@ public List createBrAPIObservations(List brA
var program = programDAO.fetchOneById(programId);
try {
if (!brAPIObservationList.isEmpty()) {
- Callable> postFunction = () -> {
List postResponse = brAPIDAOUtil.post(brAPIObservationList, upload, api::observationsPost, importDAO::update);
- return processObservationsForCache(postResponse, program.getKey());
- };
- return programCache.post(programId, postFunction);
+ processObservations(program.getKey(), postResponse);
+ return postResponse;
}
return new ArrayList<>();
} catch (Exception e) {
@@ -306,44 +223,13 @@ public List createBrAPIObservations(List brA
}
}
- public BrAPIObservation updateBrAPIObservation(String dbId, BrAPIObservation observation, UUID programId) throws ApiException {
- ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ObservationsApi.class);
- var program = programDAO.fetchOneById(programId);
- try {
- Callable> postFunction = () -> {
- ApiResponse response = api.observationsObservationDbIdPut(dbId, observation);
- if (response == null)
- {
- throw new ApiException("Response is null", 0, null, null);
- }
- BrAPIObservationSingleResponse body = response.getBody();
- if (body == null) {
- throw new ApiException("Response is missing body", 0, response.getHeaders(), null);
- }
- BrAPIObservation updatedObservation = body.getResult();
- if (updatedObservation == null) {
- throw new ApiException("Response body is missing result", 0, response.getHeaders(), response.getBody().toString());
- }
- return processObservationsForCache(List.of(updatedObservation), program.getKey());
- };
- return programCache.post(programId, postFunction).get(0);
- } catch (ApiException e) {
- log.error(Utilities.generateApiExceptionLogMessage(e));
- throw new InternalServerException("Unknown error has occurred: " + e.getMessage(), e);
- } catch (Exception e) {
- throw new InternalServerException("Unknown error has occurred: " + e.getMessage(), e);
- }
- }
-
- // This method overloads updateBrAPIObservation(String dbId, BrAPIObservation observation, UUID programId)
- // It was added to increase efficiency. It insures that ProgramCache.populate() is called only once
- // not once per observation.
public List updateBrAPIObservation(Map mutatedObservationByDbId, UUID programId) throws ApiException {
ObservationsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ObservationsApi.class);
var program = programDAO.fetchOneById(programId);
List updatedObservations = new ArrayList<>();
try {
+ // TODO: Instead of a for loop, utilize BrAPI Observations put to do all updates in one request. [BI-2969]
for (Map.Entry entry : mutatedObservationByDbId.entrySet()) {
String dbId = entry.getKey();
BrAPIObservation observation = entry.getValue();
@@ -351,23 +237,13 @@ public List updateBrAPIObservation(Map response = null;
+ BrAPIObservation updatedObservation;
+
try {
- response = api.observationsObservationDbIdPut(dbId, observation);
+ updatedObservation = brAPIDAOUtil.put(dbId, observation, api::observationsObservationDbIdPut);
} catch (ApiException e) {
throw new RuntimeException(e);
}
- if (response == null) {
- throw new ApiException("Response is null", 0, null, null);
- }
- BrAPIObservationSingleResponse body = response.getBody();
- if (body == null) {
- throw new ApiException("Response is missing body", 0, response.getHeaders(), null);
- }
- BrAPIObservation updatedObservation = body.getResult();
- if (updatedObservation == null) {
- throw new ApiException("Response body is missing result", 0, response.getHeaders(), response.getBody().toString());
- }
updatedObservations.add(updatedObservation);
if (!Objects.equals(observation.getValue(), updatedObservation.getValue())
@@ -381,8 +257,8 @@ public List updateBrAPIObservation(Map processedObservations = processObservationsForCache(updatedObservations, program.getKey());
- return programCache.postThese(programId,processedObservations);
+ processObservations(program.getKey(), updatedObservations);
+ return updatedObservations;
} catch (ApiException e) {
log.error("Error updating observation: " + Utilities.generateApiExceptionLogMessage(e), e);
throw e;
diff --git a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java
index 76acb8076..44244bf2b 100644
--- a/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java
+++ b/src/main/java/org/breedinginsight/brapi/v2/dao/BrAPIObservationUnitDAO.java
@@ -17,31 +17,27 @@
package org.breedinginsight.brapi.v2.dao;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
-import com.google.gson.reflect.TypeToken;
import io.micronaut.context.annotation.Property;
import io.micronaut.http.server.exceptions.InternalServerException;
-import io.micronaut.scheduling.annotation.Scheduled;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
-import org.brapi.client.v2.JSON;
import org.brapi.client.v2.model.exceptions.ApiException;
+import org.brapi.client.v2.model.queryParams.phenotype.ObservationUnitQueryParams;
import org.brapi.client.v2.modules.phenotype.ObservationUnitsApi;
import org.brapi.v2.model.BrAPIExternalReference;
+import org.brapi.v2.model.core.BrAPIProgram;
import org.brapi.v2.model.germ.BrAPIGermplasm;
-import org.brapi.v2.model.pheno.BrAPIObservationTreatment;
import org.brapi.v2.model.pheno.BrAPIObservationUnit;
import org.brapi.v2.model.pheno.BrAPIObservationUnitLevelRelationship;
import org.brapi.v2.model.pheno.request.BrAPIObservationUnitSearchRequest;
+import org.brapi.v2.model.pheno.response.BrAPIObservationUnitListResponse;
import org.breedinginsight.brapi.v2.constants.BrAPIAdditionalInfoFields;
import org.breedinginsight.brapi.v2.services.BrAPIGermplasmService;
import org.breedinginsight.brapps.importer.daos.ImportDAO;
import org.breedinginsight.brapps.importer.model.ImportUpload;
import org.breedinginsight.brapps.importer.services.ExternalReferenceSource;
import org.breedinginsight.daos.ProgramDAO;
-import org.breedinginsight.daos.cache.ProgramCacheProvider;
import org.breedinginsight.model.Program;
import org.breedinginsight.services.ProgramService;
import org.breedinginsight.services.brapi.BrAPIEndpointProvider;
@@ -52,15 +48,13 @@
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
-import java.lang.reflect.Type;
import java.util.*;
-import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
@Slf4j
@Singleton
-public class BrAPIObservationUnitDAO extends BrAPICachedDAO {
+public class BrAPIObservationUnitDAO {
private final ProgramDAO programDAO;
private final ImportDAO importDAO;
private final BrAPIDAOUtil brAPIDAOUtil;
@@ -69,10 +63,8 @@ public class BrAPIObservationUnitDAO extends BrAPICachedDAO>(){}.getType();
+ private final int brapiMaxPageSize;
@Inject
public BrAPIObservationUnitDAO(ProgramDAO programDAO,
@@ -82,88 +74,37 @@ public BrAPIObservationUnitDAO(ProgramDAO programDAO,
BrAPIGermplasmService germplasmService,
ProgramService programService,
@Property(name = "brapi.server.reference-source") String referenceSource,
- @Property(name = "micronaut.bi.api.run-scheduled-tasks") boolean runScheduledTasks,
- ProgramCacheProvider programCacheProvider) {
+ @Property(name = "brapi.page-thru.page-size") int brapiFetchPageSize) {
this.programDAO = programDAO;
this.importDAO = importDAO;
this.brAPIDAOUtil = brAPIDAOUtil;
this.brAPIEndpointProvider = brAPIEndpointProvider;
this.referenceSource = referenceSource;
- this.runScheduledTasks = runScheduledTasks;
this.programService = programService;
this.germplasmService = germplasmService;
- this.programCache = programCacheProvider.getProgramCache(this::fetchProgramObservationUnits, BrAPIObservationUnit.class);
+ this.brapiMaxPageSize = brapiFetchPageSize;
}
- @Scheduled(initialDelay = "${startup.delay.observation_unit}")
- public void setup() {
- if(!runScheduledTasks) {
- return;
- }
- // Populate observation unit cache for all programs on startup.
- log.debug("populating observation unit cache");
- List programs = programDAO.getActive();
- if(programs != null) {
- programCache.populate(programs.stream().map(Program::getId).collect(Collectors.toList()));
- }
- }
+ public List searchBrapiObservationUnits(BrAPIObservationUnitSearchRequest observationUnitSearchRequest,
+ Program program) throws ApiException {
+ ObservationUnitsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(program.getId()), ObservationUnitsApi.class);
- /**
- * Fetch formatted observation units for this program.
- */
- private Map fetchProgramObservationUnits(UUID programId) throws ApiException {
- ObservationUnitsApi api = brAPIEndpointProvider.get(programDAO.getCoreClient(programId), ObservationUnitsApi.class);
- // Get the program.
- List programs = programDAO.get(programId);
- if (programs.size() != 1) {
- throw new InternalServerException("Program was not found for given id");
+ if (observationUnitSearchRequest.getProgramDbIds() == null || observationUnitSearchRequest.getProgramDbIds().isEmpty()) {
+ String brapiProgramDbId = brAPIDAOUtil.getBrAPIProgramDbId(program.getId());
+ observationUnitSearchRequest.setProgramDbIds(List.of(brapiProgramDbId));
}
- Program program = programs.get(0);
-
- // Set query params and make call.
- BrAPIObservationUnitSearchRequest observationUnitSearch = new BrAPIObservationUnitSearchRequest();
- observationUnitSearch.externalReferenceIds(List.of(programId.toString()));
- observationUnitSearch.externalReferenceSources(List.of(Utilities.generateReferenceSource(referenceSource, ExternalReferenceSource.PROGRAMS)));
- return processObservationUnitsForCache(brAPIDAOUtil.search(
- api::searchObservationunitsPost,
- api::searchObservationunitsSearchResultsDbIdGet,
- observationUnitSearch
- ), program, true);
- }
- /**
- * Process a list of observation units for insertion into the cache.
- */
- private Map processObservationUnitsForCache(List programObservationUnits, Program program, boolean withGID) throws ApiException {
- // Process programObservationUnits in place (strip program key, etc.).
- processObservationUnits(program, programObservationUnits, withGID);
- // Build map.
- Map programObservationUnitsMap = new HashMap<>();
- for (BrAPIObservationUnit observationUnit: programObservationUnits) {
- BrAPIExternalReference xref = observationUnit
- .getExternalReferences()
- .stream()
- .filter(reference -> String.format("%s/%s", referenceSource, ExternalReferenceSource.OBSERVATION_UNITS.getName()).equals(reference.getReferenceSource()))
- .findFirst().orElseThrow(() -> new IllegalStateException("No BI external reference found"));
- programObservationUnitsMap.put(xref.getReferenceId(), observationUnit);
- }
- return programObservationUnitsMap;
- }
+ BrAPIObservationUnitListResponse brAPIResponse =
+ brAPIDAOUtil.searchReturnResponse(
+ api::searchObservationunitsPost,
+ api::searchObservationunitsSearchResultsDbIdGet,
+ observationUnitSearchRequest
+ );
- /**
- * Get all observation units for a program from the cache.
- */
- private Map getProgramObservationUnits(UUID programId) throws ApiException {
- return programCache.get(programId);
- }
+ List observationUnits = brAPIDAOUtil.getListResult(brAPIResponse);
+ processObservationUnits(program, observationUnits, false);
- public List getObservationUnitByName(List observationUnitNames, Program program) throws ApiException {
- if(observationUnitNames.isEmpty()) {
- return Collections.emptyList();
- }
- return getProgramObservationUnits(program.getId()).values().stream()
- .filter(ou -> observationUnitNames.contains(ou.getObservationUnitName()))
- .collect(Collectors.toList());
+ return observationUnits;
}
/**
@@ -175,11 +116,9 @@ public List createBrAPIObservationUnits(List> postFunction = () -> {
- List ous = brAPIDAOUtil.post(brAPIObservationUnitList, upload, api::observationunitsPost, importDAO::update);
- return processObservationUnitsForCache(ous, program, false);
- };
- return programCache.post(programId, postFunction);
+ List ous = brAPIDAOUtil.post(brAPIObservationUnitList, upload, api::observationunitsPost, importDAO::update);
+ processObservationUnits(program, ous, false);
+ return ous;
}
return new ArrayList<>();
} catch (Exception e) {
@@ -196,11 +135,9 @@ public List createBrAPIObservationUnits(List> postFunction = () -> {
- List