diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/StorageManager.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/StorageManager.java index c2c9ef0f092..9ca3b344afa 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/StorageManager.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/StorageManager.java @@ -75,13 +75,13 @@ protected StorageManager(CatalogManager catalogManager, CacheManager cacheManage public void clearCache(String sessionId) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); } public void clearCache(String studyId, String sessionId) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); } @@ -99,7 +99,7 @@ protected StudyInfo getStudyInfo(@Nullable String studyIdStr, List fileI throws CatalogException { StudyInfo studyInfo = new StudyInfo().setSessionId(sessionId); - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().get(organizationId, studyIdStr, QueryOptions.empty(), sessionId).first(); List files; diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/annotations/TsvAnnotationLoader.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/annotations/TsvAnnotationLoader.java index 7bdf356b66d..48e145378b2 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/annotations/TsvAnnotationLoader.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/annotations/TsvAnnotationLoader.java @@ -71,7 +71,7 @@ public void setStudy(String study) { @Override protected void check() throws Exception { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); OpenCGAResult fileResult = catalogManager.getFileManager().get(organizationId, study, path, FileManager.INCLUDE_FILE_URI_PATH, token); if (fileResult.getNumResults() == 0) { diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/clinical/ClinicalInterpretationManager.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/clinical/ClinicalInterpretationManager.java index 4856a65803f..ee181e391a6 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/clinical/ClinicalInterpretationManager.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/clinical/ClinicalInterpretationManager.java @@ -820,8 +820,8 @@ public List getPrimaryFindings(String clinicalAnalysisId, Query public ClinicalAnalyst getAnalyst(String token) throws ToolException { try { - String userId = catalogManager.getUserManager().getUserId(token); - OpenCGAResult userQueryResult = catalogManager.getUserManager().get(userId, new QueryOptions(QueryOptions.INCLUDE, + String userId = catalogManager.getUserManager().getUserId(organizationId, token); + OpenCGAResult userQueryResult = catalogManager.getUserManager().get(organizationId, userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(UserDBAdaptor.QueryParams.EMAIL.key(), UserDBAdaptor.QueryParams.ORGANIZATION.key())), token); User user = userQueryResult.first(); return new ClinicalAnalyst(userId, user.getName(), user.getEmail(), "", ""); @@ -877,7 +877,7 @@ private Query checkQueryPermissions(Query query, String token) throws ClinicalVa } // Get userId from token and Study numeric IDs from the query - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); List studyIds = getStudyIds(userId, query); // If one specific clinical analysis, sample or individual is provided we expect a single valid study as well diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/family/qc/FamilyQcAnalysis.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/family/qc/FamilyQcAnalysis.java index 8dfd48174f8..b45a4ec1dde 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/family/qc/FamilyQcAnalysis.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/family/qc/FamilyQcAnalysis.java @@ -68,7 +68,7 @@ protected void check() throws Exception { // Check permissions try { Study study = catalogManager.getStudyManager().get(organizationId, studyId, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); catalogManager.getAuthorizationManager().checkStudyPermission(study.getUid(), userId, WRITE_FAMILIES); } catch (CatalogException e) { throw new ToolException(e); diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/file/FetchAndRegisterTask.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/file/FetchAndRegisterTask.java index a08322448cc..4409cfe1efb 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/file/FetchAndRegisterTask.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/file/FetchAndRegisterTask.java @@ -85,7 +85,7 @@ protected void check() throws Exception { throw new CatalogException("Parent path " + parents.first().getPath() + " is external. Cannot download to mounted folders"); } - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); // Check write permissions over the path catalogManager.getAuthorizationManager() .checkFilePermission(study.getUid(), parents.first().getUid(), userId, FilePermissions.WRITE); diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/individual/qc/IndividualQcAnalysis.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/individual/qc/IndividualQcAnalysis.java index ee373a74184..4287ef1ee42 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/individual/qc/IndividualQcAnalysis.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/individual/qc/IndividualQcAnalysis.java @@ -83,7 +83,7 @@ protected void check() throws Exception { // Check permissions try { Study study = catalogManager.getStudyManager().get(organizationId, studyId, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); catalogManager.getAuthorizationManager().checkStudyPermission(study.getUid(), userId, WRITE_INDIVIDUALS); } catch (CatalogException e) { throw new ToolException(e); diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/panel/PanelImportTask.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/panel/PanelImportTask.java index b5a0642d41e..3d4106a473b 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/panel/PanelImportTask.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/panel/PanelImportTask.java @@ -30,7 +30,7 @@ protected void check() throws Exception { @Override protected void run() throws Exception { - step(() -> catalogManager.getPanelManager().importFromSource(studyFqn, params.getSource(), params.getId(), token)); + step(() -> catalogManager.getPanelManager().importFromSource(organizationId, studyFqn, params.getSource(), params.getId(), token)); } } diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/rga/RgaManager.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/rga/RgaManager.java index 035fb32ee71..88ea3449a9a 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/rga/RgaManager.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/rga/RgaManager.java @@ -142,7 +142,7 @@ public void index(String studyStr, String fileStr, String token) throws CatalogE */ public void index(String study, Path file, String token) throws CatalogException, IOException, RgaException { checkStorageReadMode(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study studyObject = catalogManager.getStudyManager().get(organizationId, study, QueryOptions.empty(), token).first(); try { catalogManager.getAuthorizationManager().isOwnerOrAdmin(studyObject.getUid(), userId); @@ -225,7 +225,7 @@ private void load(String study, Path file, String token) throws RgaException { public void generateAuxiliarCollection(String studyStr, String token) throws CatalogException, RgaException, IOException { checkStorageReadMode(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); try { catalogManager.getAuthorizationManager().isOwnerOrAdmin(study.getUid(), userId); @@ -433,7 +433,7 @@ private AuxiliarRgaDataModel getAuxiliarRgaDataModel(String mainCollection, Stri private OpenCGAResult updateRgaInternalIndexStatus(String studyStr, List sampleIds, RgaIndex.Status status, String token) throws CatalogException, RgaException { Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); String collection = getMainCollectionName(study.getFqn()); catalogManager.getAuthorizationManager().checkIsOwnerOrAdmin(study.getUid(), userId); @@ -454,7 +454,7 @@ private OpenCGAResult updateRgaInternalIndexStatus(String studyStr, List update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), tmpSampleIds, rgaIndex, + OpenCGAResult update = catalogManager.getSampleManager().updateRgaIndexes(organizationId, study.getFqn(), tmpSampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); @@ -464,7 +464,7 @@ private OpenCGAResult updateRgaInternalIndexStatus(String studyStr, List update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), tmpSampleIds, rgaIndex, + OpenCGAResult update = catalogManager.getSampleManager().updateRgaIndexes(organizationId, study.getFqn(), tmpSampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); } @@ -476,7 +476,7 @@ private OpenCGAResult updateRgaInternalIndexStatus(String studyStr, List updateRgaInternalIndexStatus(String studyStr, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); String collection = getMainCollectionName(study.getFqn()); catalogManager.getAuthorizationManager().checkIsOwnerOrAdmin(study.getUid(), userId); @@ -497,7 +497,7 @@ private OpenCGAResult updateRgaInternalIndexStatus(String studyStr, String int updatedSamples = 0; // Before doing anything, we first reset all the sample rga indexes - OpenCGAResult resetResult = catalogManager.getSampleManager().resetRgaIndexes(studyStr, token); + OpenCGAResult resetResult = catalogManager.getSampleManager().resetRgaIndexes(organizationId, studyStr, token); logger.debug("Resetting RGA indexes for " + resetResult.getNumMatches() + " samples took " + resetResult.getTime() + " ms."); // Update samples in batches of 100 @@ -507,7 +507,7 @@ private OpenCGAResult updateRgaInternalIndexStatus(String studyStr, String for (FacetField.Bucket bucket : result.first().getBuckets()) { sampleIds.add(bucket.getValue()); if (sampleIds.size() == 100) { - OpenCGAResult update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), sampleIds, rgaIndex, + OpenCGAResult update = catalogManager.getSampleManager().updateRgaIndexes(organizationId, study.getFqn(), sampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); @@ -517,7 +517,7 @@ private OpenCGAResult updateRgaInternalIndexStatus(String studyStr, String if (!sampleIds.isEmpty()) { // Update last batch - OpenCGAResult update = catalogManager.getSampleManager().updateRgaIndexes(study.getFqn(), sampleIds, rgaIndex, token); + OpenCGAResult update = catalogManager.getSampleManager().updateRgaIndexes(organizationId, study.getFqn(), sampleIds, rgaIndex, token); updatedSamples += update.getNumUpdated(); } @@ -619,7 +619,7 @@ public OpenCGAResult geneQuery(String studyStr, Query query, } Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); String collection = getMainCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); @@ -753,7 +753,7 @@ public OpenCGAResult variantQuery(String studyStr, Query quer } Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); String collection = getMainCollectionName(study.getFqn()); String auxCollection = getAuxCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { @@ -1048,7 +1048,7 @@ public OpenCGAResult geneSummary(String studyStr, Query q } Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); String collection = getMainCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); @@ -1132,7 +1132,7 @@ public OpenCGAResult variantSummary(String studyStr, Q } Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); String collection = getMainCollectionName(study.getFqn()); String auxCollection = getAuxCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { @@ -1238,7 +1238,7 @@ public OpenCGAResult variantSummary(String studyStr, Q public OpenCGAResult aggregationStats(String studyStr, Query query, QueryOptions options, String fields, String token) throws CatalogException, IOException, RgaException { Study study = catalogManager.getStudyManager().get(organizationId, studyStr, QueryOptions.empty(), token).first(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); catalogManager.getAuthorizationManager().checkCanViewStudy(study.getUid(), userId); @@ -1720,7 +1720,7 @@ private Set getAuthorisedSamples(String study, Set sampleIds, Li private Preprocess individualQueryPreprocess(Study study, Query query, QueryOptions options, String token) throws RgaException, CatalogException, IOException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); String collection = getMainCollectionName(study.getFqn()); if (!rgaEngine.isAlive(collection)) { throw new RgaException("Missing RGA indexes for study '" + study.getFqn() + "' or solr server not alive"); diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/SampleTsvAnnotationLoader.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/SampleTsvAnnotationLoader.java index 382eed844d1..bdf1647a67e 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/SampleTsvAnnotationLoader.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/SampleTsvAnnotationLoader.java @@ -36,6 +36,6 @@ public int count(Query query) throws CatalogException { @Override public void addAnnotationSet(String entryId, AnnotationSet annotationSet, QueryOptions options) throws CatalogException { - catalogManager.getSampleManager().addAnnotationSet(study, entryId, annotationSet, options, token); + catalogManager.getSampleManager().addAnnotationSet(organizationId, study, entryId, annotationSet, options, token); } } diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/qc/SampleQcAnalysis.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/qc/SampleQcAnalysis.java index f0cf122b000..1189d39e3df 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/qc/SampleQcAnalysis.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/sample/qc/SampleQcAnalysis.java @@ -81,7 +81,7 @@ protected void check() throws Exception { // Check permissions try { long studyUid = catalogManager.getStudyManager().get(organizationId, getStudy(), QueryOptions.empty(), token).first().getUid(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); catalogManager.getAuthorizationManager().checkStudyPermission(studyUid, userId, WRITE_SAMPLES); } catch (CatalogException e) { throw new ToolException(e); @@ -350,7 +350,7 @@ protected void run() throws ToolException { if (genomePlot != null) { qc.getVariant().setGenomePlot(genomePlot); - catalogManager.getSampleManager().update(getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), + catalogManager.getSampleManager().update(organizationId, getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), QueryOptions.empty(), getToken()); logger.info("Quality control saved for sample {}", sample.getId()); } diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/genomePlot/GenomePlotAnalysis.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/genomePlot/GenomePlotAnalysis.java index caf9f3b9b89..5a57c646cf0 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/genomePlot/GenomePlotAnalysis.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/genomePlot/GenomePlotAnalysis.java @@ -107,7 +107,7 @@ protected void run() throws ToolException { } qc.getVariant().setGenomePlot(genomePlot); - catalogManager.getSampleManager().update(getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), + catalogManager.getSampleManager().update(organizationId, getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), QueryOptions.empty(), getToken()); } } diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/hrdetect/HRDetectAnalysis.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/hrdetect/HRDetectAnalysis.java index 31920d6121c..1ac83baaf00 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/hrdetect/HRDetectAnalysis.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/hrdetect/HRDetectAnalysis.java @@ -239,7 +239,7 @@ protected void run() throws ToolException { qc.getVariant().setHrDetects(new ArrayList<>()); } qc.getVariant().getHrDetects().add(hrDetect); - catalogManager.getSampleManager().update(getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), + catalogManager.getSampleManager().update(organizationId, getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), QueryOptions.empty(), getToken()); }); } diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/julie/JulieTool.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/julie/JulieTool.java index 06aad326c5d..c0668b538f1 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/julie/JulieTool.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/julie/JulieTool.java @@ -39,8 +39,8 @@ protected void check() throws Exception { String project = getParams().getString(ParamConstants.PROJECT_PARAM); if (StringUtils.isEmpty(project)) { - String userId = getCatalogManager().getUserManager().getUserId(getToken()); - User user = catalogManager.getUserManager().get(userId, null, getToken()).first(); + String userId = getCatalogManager().getUserManager().getUserId(organizationId, getToken()); + User user = catalogManager.getUserManager().get(organizationId, userId, null, getToken()).first(); if (CollectionUtils.isEmpty(user.getProjects()) || user.getProjects().size() > 1) { throw new CatalogException("Missing '" + ParamConstants.PROJECT_PARAM + "' parameter"); } else { diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtils.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtils.java index 3b595d567ba..de4a6fdded2 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtils.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtils.java @@ -279,8 +279,8 @@ public Query parseQuery(Query query, QueryOptions queryOptions, CellBaseUtils ce if (isValidParam(query, SAVED_FILTER)) { String savedFilter = query.getString(SAVED_FILTER.key()); - String userId = catalogManager.getUserManager().getUserId(token); - UserFilter userFilter = catalogManager.getUserManager().getFilter(userId, savedFilter, token).first(); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); + UserFilter userFilter = catalogManager.getUserManager().getFilter(organizationId, userId, savedFilter, token).first(); if (!userFilter.getResource().equals(Enums.Resource.VARIANT)) { throw VariantQueryException.malformedParam(SAVED_FILTER, savedFilter, "The selected saved filter is not a filter for '" + Enums.Resource.VARIANT + "'. " @@ -1610,7 +1610,7 @@ protected List getValuesToValidate(List rawValues) { protected List validate(String defaultStudyStr, List values, Integer release, VariantQueryParam param, String sessionId) throws CatalogException { if (release == null) { - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); // DataResult samples = catalogManager.getSampleManager().get(defaultStudyStr, values, // SampleManager.INCLUDE_SAMPLE_IDS, sessionId); long numMatches = catalogManager.getSampleManager() diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManager.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManager.java index 665e64f0d36..6d8d88f0873 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManager.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManager.java @@ -118,7 +118,7 @@ public VariantStorageManager(CatalogManager catalogManager, StorageEngineFactory } public void clearCache(String studyId, String type, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); } @@ -830,7 +830,7 @@ public DataResult getSampleData(String variant, String study, QueryOpti numReadSamples += samplesInResult.size(); StopWatch checkPermissionsStopWatch = StopWatch.createStarted(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); List validSamples = catalogManager.getSampleManager() .search(organizationId, study, new Query(SampleDBAdaptor.QueryParams.ID.key(), samplesInResult) @@ -1209,7 +1209,7 @@ private R secureTool(String toolId, boolean isOperation, ObjectMap params, S // deprecated .append("operationName", toolId); R result = null; - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Exception exception = null; StopWatch totalStopWatch = StopWatch.createStarted(); @@ -1268,7 +1268,7 @@ private R secure(Query query, QueryOptions queryOptions, String token, Enums .append("query", new Query(query)) .append("queryOptions", new QueryOptions(queryOptions)); R result = null; - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Exception exception = null; StopWatch totalStopWatch = StopWatch.createStarted(); StopWatch storageStopWatch = null; @@ -1338,7 +1338,7 @@ Map> checkSamplesPermissions(Query query, QueryOptions quer Enums.Action auditAction, String token) throws CatalogException { final Map> samplesMap = new HashMap<>(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Set returnedFields = VariantField.getIncludeFields(queryOptions); if (auditAction == Enums.Action.FACET) { if (VariantQueryProjectionParser.isIncludeNoSamples(query, VariantField.all())) { diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizer.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizer.java index fa14e0e97df..e098ad666a5 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizer.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizer.java @@ -780,7 +780,7 @@ private boolean synchronizeIndexedFile(StudyMetadata study, File file, Map s.getInternal().getVariant().getAnnotationIndex().getStatus().getId(), null); if (!sampleMetadata.getAnnotationStatus().name().equals(catalogAnnotationIndexStatus)) { catalogManager.getSampleManager() - .updateSampleInternalVariantAnnotationIndex(sample, + .updateSampleInternalVariantAnnotationIndex(organizationId, sample, new SampleInternalVariantAnnotationIndex( new IndexStatus(sampleMetadata.getAnnotationStatus().name())), token); modified = true; @@ -852,7 +852,7 @@ private boolean synchronizeSample(SampleMetadata sampleMetadata, Sample sample, s -> s.getInternal().getVariant().getSecondaryAnnotationIndex().getStatus().getId(), null); if (!sampleMetadata.getSecondaryAnnotationIndexStatus().name().equals(catalogSecondaryAnnotationIndexStatus)) { catalogManager.getSampleManager() - .updateSampleInternalVariantSecondaryAnnotationIndex(sample, + .updateSampleInternalVariantSecondaryAnnotationIndex(organizationId, sample, new SampleInternalVariantSecondaryAnnotationIndex( new IndexStatus(sampleMetadata.getSecondaryAnnotationIndexStatus().name())), token); modified = true; @@ -920,7 +920,7 @@ private boolean synchronizeSample(SampleMetadata sampleMetadata, Sample sample, if (catalogVariantSecondarySampleIndexModified) { catalogManager.getSampleManager() - .updateSampleInternalVariantSecondarySampleIndex(sample, catalogVariantSecondarySampleIndex, token); + .updateSampleInternalVariantSecondarySampleIndex(organizationId, sample, catalogVariantSecondarySampleIndex, token); modified = true; } return modified; diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/mutationalSignature/MutationalSignatureAnalysis.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/mutationalSignature/MutationalSignatureAnalysis.java index 4043a018a00..3301ff51737 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/mutationalSignature/MutationalSignatureAnalysis.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/mutationalSignature/MutationalSignatureAnalysis.java @@ -296,7 +296,7 @@ protected void run() throws ToolException { } // Update sample quality control try { - catalogManager.getSampleManager().update(getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), + catalogManager.getSampleManager().update(organizationId, getStudy(), sample.getId(), new SampleUpdateParams().setQualityControl(qc), QueryOptions.empty(), getToken()); logger.info("Quality control saved for sample {}", sample.getId()); } catch (CatalogException e) { diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataRepairTool.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataRepairTool.java index 385a3a09d5a..243f8fb9c8a 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataRepairTool.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataRepairTool.java @@ -39,7 +39,7 @@ public class VariantStorageMetadataRepairTool extends OperationTool { protected void check() throws Exception { super.check(); - String userId = getCatalogManager().getUserManager().getUserId(getToken()); + String userId = getCatalogManager().getUserManager().getUserId(organizationId, getToken()); if (!userId.equals(ParamConstants.OPENCGA_USER_ID)) { throw new CatalogAuthenticationException("Only user '" + ParamConstants.OPENCGA_USER_ID + "' can run this operation!"); } diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataSynchronizeOperationTool.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataSynchronizeOperationTool.java index 62b69d96d34..534eab1a4a1 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataSynchronizeOperationTool.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/operations/VariantStorageMetadataSynchronizeOperationTool.java @@ -20,7 +20,7 @@ public class VariantStorageMetadataSynchronizeOperationTool extends OperationToo protected void check() throws Exception { super.check(); - String userId = getCatalogManager().getUserManager().getUserId(getToken()); + String userId = getCatalogManager().getUserManager().getUserId(organizationId, getToken()); if (!userId.equals(ParamConstants.OPENCGA_USER_ID)) { throw new CatalogAuthenticationException("Only user '" + ParamConstants.OPENCGA_USER_ID + "' can run this operation!"); } diff --git a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/stats/SampleVariantStatsAnalysis.java b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/stats/SampleVariantStatsAnalysis.java index 214c883210c..35502fecb11 100644 --- a/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/stats/SampleVariantStatsAnalysis.java +++ b/opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/stats/SampleVariantStatsAnalysis.java @@ -87,7 +87,7 @@ protected void check() throws Exception { } } if (toolParams.isIndex()) { - String userId = getCatalogManager().getUserManager().getUserId(getToken()); + String userId = getCatalogManager().getUserManager().getUserId(organizationId, getToken()); Study study = getCatalogManager().getStudyManager().get(organizationId, this.study, new QueryOptions(), getToken()).first(); boolean isOwner = study.getFqn().startsWith(userId + "@"); if (!isOwner) { @@ -322,7 +322,7 @@ protected void run() throws ToolException { } SampleUpdateParams updateParams = new SampleUpdateParams().setQualityControl(qualityControl); getCatalogManager().getSampleManager() - .update(study, sampleVariantStats.getId(), updateParams, new QueryOptions(), getToken()); + .update(organizationId, study, sampleVariantStats.getId(), updateParams, new QueryOptions(), getToken()); progressLogger.increment(1); } diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/alignment/AlignmentAnalysisTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/alignment/AlignmentAnalysisTest.java index 5f6c32377cf..d80f64d0a5e 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/alignment/AlignmentAnalysisTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/alignment/AlignmentAnalysisTest.java @@ -227,9 +227,9 @@ public void setUpCatalogManager() throws CatalogException { token = catalogManager.getUserManager().login("user", PASSWORD).getToken(); - String projectId = catalogManager.getProjectManager().create(PROJECT, "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, PROJECT, "Project about some genomes", "", "Homo sapiens", null, "GRCh38", new QueryOptions(ParamConstants.INCLUDE_RESULT_PARAM, true), token).first().getId(); - catalogManager.getStudyManager().create(projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); + catalogManager.getStudyManager().create(organizationId, projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); // Create 10 samples not indexed // for (int i = 0; i < 10; i++) { diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/family/FamilyAnalysisTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/family/FamilyAnalysisTest.java index 590a80049ea..f7bb9bb5f40 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/family/FamilyAnalysisTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/family/FamilyAnalysisTest.java @@ -77,13 +77,13 @@ public static void setUp() throws IOException, CatalogException { public static void setUpCatalogManager(CatalogManager catalogManager) throws CatalogException { opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); - projectId = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", + projectId = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first().getId(); - studyId = catalogManager.getStudyManager().create(projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, + studyId = catalogManager.getStudyManager().create(organizationId, projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser).first().getId(); try { diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/rga/RgaManagerTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/rga/RgaManagerTest.java index d04fc2ae294..90574d4a843 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/rga/RgaManagerTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/rga/RgaManagerTest.java @@ -100,7 +100,7 @@ public void setUp() throws Throwable { if (i % 2 == 0) { String id = file.getSampleIds().get(i); SampleUpdateParams updateParams = new SampleUpdateParams().setPhenotypes(Collections.singletonList(PHENOTYPE)); - catalogManager.getSampleManager().update(STUDY, id, updateParams, null, ownerToken); + catalogManager.getSampleManager().update(organizationId, STUDY, id, updateParams, null, ownerToken); } } @@ -141,7 +141,7 @@ public void setUp() throws Throwable { catalogManager.getIndividualManager().updateAcl(organizationId, STUDY, Arrays.asList(FATHER, MOTHER, DAUGHTER), USER, new IndividualAclParams().setPermissions(IndividualPermissions.VIEW.name()), ParamUtils.AclAction.SET, false, ownerToken); - catalogManager.getSampleManager().updateAcl(STUDY, Arrays.asList(FATHER, MOTHER, DAUGHTER), USER, + catalogManager.getSampleManager().updateAcl(organizationId, STUDY, Arrays.asList(FATHER, MOTHER, DAUGHTER), USER, new SampleAclParams().setPermissions(SamplePermissions.VIEW_VARIANTS.name()), ParamUtils.AclAction.SET, ownerToken); @@ -183,12 +183,12 @@ public static void afterClass() { } public void setUpCatalogManager() throws CatalogException { - catalogManager.getUserManager().create(OWNER, "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, opencga.getAdminToken()); + catalogManager.getUserManager().create(organizationId, OWNER, "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, opencga.getAdminToken()); ownerToken = catalogManager.getUserManager().login(OWNER, PASSWORD).getToken(); - String projectId = catalogManager.getProjectManager().create(PROJECT, "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, PROJECT, "Project about some genomes", "", "Homo sapiens", null, "GRCh37", new QueryOptions(ParamConstants.INCLUDE_RESULT_PARAM, true), ownerToken).first().getId(); - catalogManager.getStudyManager().create(projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, ownerToken); + catalogManager.getStudyManager().create(organizationId, projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, ownerToken); // Create 10 samples not indexed for (int i = 0; i < 10; i++) { @@ -199,7 +199,7 @@ public void setUpCatalogManager() throws CatalogException { catalogManager.getSampleManager().create(organizationId, STUDY, sample, null, ownerToken); } - catalogManager.getUserManager().create(USER, "Other Name", "mail2@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.GUEST, opencga.getAdminToken()); + catalogManager.getUserManager().create(organizationId, USER, "Other Name", "mail2@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.GUEST, opencga.getAdminToken()); userToken = catalogManager.getUserManager().login(USER, PASSWORD).getToken(); } diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/VariantAnalysisTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/VariantAnalysisTest.java index 0623ebac1d8..4da253988f6 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/VariantAnalysisTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/VariantAnalysisTest.java @@ -178,11 +178,11 @@ public void setUp() throws Throwable { String id = file.getSampleIds().get(i); if (id.equals(son)) { SampleUpdateParams updateParams = new SampleUpdateParams().setSomatic(true); - catalogManager.getSampleManager().update(STUDY, id, updateParams, null, token); + catalogManager.getSampleManager().update(organizationId, STUDY, id, updateParams, null, token); } if (i % 2 == 0) { SampleUpdateParams updateParams = new SampleUpdateParams().setPhenotypes(Collections.singletonList(PHENOTYPE)); - catalogManager.getSampleManager().update(STUDY, id, updateParams, null, token); + catalogManager.getSampleManager().update(organizationId, STUDY, id, updateParams, null, token); } } @@ -235,7 +235,7 @@ public void setUp() throws Throwable { variantStorageManager.index(CANCER_STUDY, file.getId(), opencga.createTmpOutdir("_index"), config, token); SampleUpdateParams updateParams = new SampleUpdateParams().setSomatic(true); - catalogManager.getSampleManager().update(CANCER_STUDY, cancer_sample, updateParams, null, token); + catalogManager.getSampleManager().update(organizationId, CANCER_STUDY, cancer_sample, updateParams, null, token); opencga.getStorageConfiguration().getVariant().setDefaultEngine(storageEngine); VariantStorageEngine engine = opencga.getStorageEngineFactory().getVariantStorageEngine(storageEngine, DB_NAME); @@ -261,12 +261,12 @@ public static void afterClass() { } public void setUpCatalogManager() throws IOException, CatalogException { - catalogManager.getUserManager().create(USER, "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, opencga.getAdminToken()); + catalogManager.getUserManager().create(organizationId, USER, "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, opencga.getAdminToken()); token = catalogManager.getUserManager().login("user", PASSWORD).getToken(); - String projectId = catalogManager.getProjectManager().create(PROJECT, "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, PROJECT, "Project about some genomes", "", "Homo sapiens", null, "GRCh38", new QueryOptions(ParamConstants.INCLUDE_RESULT_PARAM, true), token).first().getId(); - catalogManager.getStudyManager().create(projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); + catalogManager.getStudyManager().create(organizationId, projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); // Create 10 samples not indexed for (int i = 0; i < 10; i++) { @@ -279,7 +279,7 @@ public void setUpCatalogManager() throws IOException, CatalogException { // Cancer List samples = new ArrayList<>(); - catalogManager.getStudyManager().create(projectId, CANCER_STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); + catalogManager.getStudyManager().create(organizationId, projectId, CANCER_STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); Sample sample = new Sample().setId(cancer_sample).setSomatic(true); samples.add(sample); // catalogManager.getSampleManager().create(CANCER_STUDY, sample, null, token); @@ -397,7 +397,7 @@ public void testSampleStatsSampleFilter() throws Exception { SampleQualityControl qualityControl = sample.getQualityControl(); if (qualityControl != null && qualityControl.getVariant() != null && CollectionUtils.isNotEmpty(qualityControl.getVariant().getVariantStats())) { qualityControl.getVariant().setVariantStats(Collections.emptyList()); - catalogManager.getSampleManager().update(STUDY, sample.getId(), new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, STUDY, sample.getId(), new SampleUpdateParams() .setQualityControl(qualityControl), new QueryOptions(), token); } } @@ -760,7 +760,7 @@ public void testMutationalSignatureFittingSNV() throws Exception { SampleQualityControl qc = new SampleQualityControl(); qc.getVariant().setSignatures(Collections.singletonList(signature)); SampleUpdateParams updateParams = new SampleUpdateParams().setQualityControl(qc); - catalogManager.getSampleManager().update(CANCER_STUDY, cancer_sample, updateParams, null, token); + catalogManager.getSampleManager().update(organizationId, CANCER_STUDY, cancer_sample, updateParams, null, token); MutationalSignatureAnalysisParams params = new MutationalSignatureAnalysisParams(); params.setSample(cancer_sample); @@ -878,7 +878,7 @@ public void testMutationalSignatureFittingSV() throws Exception { SampleQualityControl qc = new SampleQualityControl(); qc.getVariant().setSignatures(Collections.singletonList(signature)); SampleUpdateParams updateParams = new SampleUpdateParams().setQualityControl(qc); - catalogManager.getSampleManager().update(CANCER_STUDY, cancer_sample, updateParams, null, token); + catalogManager.getSampleManager().update(organizationId, CANCER_STUDY, cancer_sample, updateParams, null, token); MutationalSignatureAnalysisParams params = new MutationalSignatureAnalysisParams(); params.setSample(cancer_sample); @@ -929,7 +929,7 @@ public void testHRDetect() throws Exception { SampleQualityControl qc = new SampleQualityControl(); qc.getVariant().setSignatures(Arrays.asList(snvSignature, svSignature)); SampleUpdateParams updateParams = new SampleUpdateParams().setQualityControl(qc); - catalogManager.getSampleManager().update(CANCER_STUDY, cancer_sample, updateParams, null, token); + catalogManager.getSampleManager().update(organizationId, CANCER_STUDY, cancer_sample, updateParams, null, token); // SNV fitting MutationalSignatureAnalysisParams params = new MutationalSignatureAnalysisParams(); diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtilsTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtilsTest.java index 9d486efa20b..e8a3c625c31 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtilsTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantCatalogQueryUtilsTest.java @@ -112,14 +112,14 @@ public class VariantCatalogQueryUtilsTest { public static void setUp() throws Exception { catalog = catalogManagerExternalResource.getCatalogManager(); - User user = catalog.getUserManager().create("user", "user", "my@email.org", TestParamConstants.PASSWORD, "ACME", 1000L, Account.AccountType.FULL, catalogManagerExternalResource.getAdminToken()).first(); + User user = catalog.getUserManager().create(organizationId, "user", "user", "my@email.org", TestParamConstants.PASSWORD, "ACME", 1000L, Account.AccountType.FULL, catalogManagerExternalResource.getAdminToken()).first(); sessionId = catalog.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); assembly = "GRCh38"; - catalog.getProjectManager().create("p1", "p1", "", "hsapiens", "Homo Sapiens", assembly, null, sessionId); - catalog.getStudyManager().create("p1", "s1", "s1", "s1", null, null, null, null, null, null, sessionId); - catalog.getStudyManager().create("p1", "s2", "s2", "s2", null, null, null, null, null, null, sessionId); - catalog.getStudyManager().create("p1", "s3", "s3", "s3", null, null, null, null, null, null, sessionId); + catalog.getProjectManager().create(organizationId, "p1", "p1", "", "hsapiens", "Homo Sapiens", assembly, null, sessionId); + catalog.getStudyManager().create(organizationId, "p1", "s1", "s1", "s1", null, null, null, null, null, null, sessionId); + catalog.getStudyManager().create(organizationId, "p1", "s2", "s2", "s2", null, null, null, null, null, null, sessionId); + catalog.getStudyManager().create(organizationId, "p1", "s3", "s3", "s3", null, null, null, null, null, null, sessionId); file1 = createFile("data/file1.vcf"); file2 = createFile("data/file2.vcf"); @@ -156,8 +156,8 @@ public static void setUp() throws Exception { catalog.getCohortManager().create(organizationId, "s2", new Cohort().setId(StudyEntry.DEFAULT_COHORT).setSamples(Collections.emptyList()), null, sessionId); - catalog.getProjectManager().create("p2", "p2", "", "hsapiens", "Homo Sapiens", assembly, null, sessionId); - catalog.getStudyManager().create("p2", "p2s2", "p2s2", "p2s2", null, null, null, null, null, null, sessionId); + catalog.getProjectManager().create(organizationId, "p2", "p2", "", "hsapiens", "Homo Sapiens", assembly, null, sessionId); + catalog.getStudyManager().create(organizationId, "p2", "p2s2", "p2s2", "p2s2", null, null, null, null, null, null, sessionId); myPanel = new Panel("MyPanel", "MyPanel", 1); myPanel.setGenes( @@ -383,8 +383,8 @@ public void parseQuery() throws Exception { @Test public void queryBySavedFilter() throws Exception { - String userId = catalog.getUserManager().getUserId(sessionId); - catalog.getUserManager().addFilter(userId, "myFilter", "", Enums.Resource.VARIANT, + String userId = catalog.getUserManager().getUserId(organizationId, sessionId); + catalog.getUserManager().addFilter(organizationId, userId, "myFilter", "", Enums.Resource.VARIANT, new Query("key1", "value1").append("key2", "value2"), new QueryOptions(), sessionId); Query query = queryUtils.parseQuery(new Query(STUDY.key(), "s1").append(SAVED_FILTER.key(), "myFilter"), null, sessionId); diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantManagerFetchTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantManagerFetchTest.java index 29465ab18de..1d98879b50f 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantManagerFetchTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantManagerFetchTest.java @@ -161,10 +161,10 @@ public void testQueryAnonymousViewSampleVariants() throws Exception { catalogManager.getStudyManager().updateAcl(organizationId, Collections.singletonList(studyFqn), "*", new StudyAclParams(StudyPermissions.Permissions.VIEW_AGGREGATED_VARIANTS.name(), null), ADD, sessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Arrays.asList("NA19600"), "*", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Arrays.asList("NA19600"), "*", new SampleAclParams().setPermissions(SamplePermissions.VIEW.name()), // View is not enough ADD, sessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Arrays.asList("NA19660"), "*", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Arrays.asList("NA19660"), "*", new SampleAclParams().setPermissions(SamplePermissions.VIEW_VARIANTS.name()), // ViewVariants without VIEW should be enough ADD, sessionId); @@ -181,7 +181,7 @@ public void testQueryAnonymousViewSampleVariants() throws Exception { @Test public void testQueryAnonymousViewSampleVariantsWithoutAggregatedVariants() throws Exception { // Only 2 samples - catalogManager.getSampleManager().updateAcl(studyFqn, Arrays.asList("NA19600", "NA19660"), "*", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Arrays.asList("NA19600", "NA19660"), "*", new SampleAclParams() .setPermissions(SamplePermissions.VIEW + "," + SamplePermissions.VIEW_VARIANTS), ADD, sessionId); @@ -208,7 +208,7 @@ public void testQueryAnonymousViewSampleVariantsWithoutAggregatedVariantsFail1() catalogManager.getStudyManager().updateAcl(organizationId, Collections.singletonList(studyFqn), "*", new StudyAclParams(StudyPermissions.Permissions.VIEW_SAMPLES.name(), null), ADD, sessionId); // Only 2 samples - catalogManager.getSampleManager().updateAcl(studyFqn, Arrays.asList("NA19600", "NA19660"), "*", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Arrays.asList("NA19600", "NA19660"), "*", new SampleAclParams() .setPermissions(SamplePermissions.VIEW + "," + SamplePermissions.VIEW_VARIANTS), ADD, sessionId); @@ -228,7 +228,7 @@ public void testQueryAnonymousViewSampleVariantsWithoutAggregatedVariantsFail2() catalogManager.getStudyManager().updateAcl(organizationId, Collections.singletonList(studyFqn), "*", new StudyAclParams(StudyPermissions.Permissions.VIEW_SAMPLES.name(), null), ADD, sessionId); // Only 2 samples - catalogManager.getSampleManager().updateAcl(studyFqn, Arrays.asList("NA19600", "NA19660"), "*", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Arrays.asList("NA19600", "NA19660"), "*", new SampleAclParams() .setPermissions(SamplePermissions.VIEW + "," + SamplePermissions.VIEW_VARIANTS), ADD, sessionId); diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantOperationsTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantOperationsTest.java index 425865e9f5c..87d35dd88d1 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantOperationsTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantOperationsTest.java @@ -213,7 +213,7 @@ private void loadDataset() throws Throwable { if (i % 2 == 0) { String id = file.getSampleIds().get(i); SampleUpdateParams updateParams = new SampleUpdateParams().setPhenotypes(Collections.singletonList(PHENOTYPE)); - catalogManager.getSampleManager().update(STUDY, id, updateParams, null, token); + catalogManager.getSampleManager().update(organizationId, STUDY, id, updateParams, null, token); } } @@ -259,12 +259,12 @@ private void loadDataset() throws Throwable { } public void setUpCatalogManager() throws Exception { - catalogManager.getUserManager().create(USER, "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, opencga.getAdminToken()); + catalogManager.getUserManager().create(organizationId, USER, "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, opencga.getAdminToken()); token = catalogManager.getUserManager().login("user", PASSWORD).getToken(); - String projectId = catalogManager.getProjectManager().create(PROJECT, "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, PROJECT, "Project about some genomes", "", "Homo sapiens", null, "GRCh38", new QueryOptions(ParamConstants.INCLUDE_RESULT_PARAM, true), token).first().getId(); - catalogManager.getStudyManager().create(projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); + catalogManager.getStudyManager().create(organizationId, projectId, STUDY, null, "Phase 1", "Done", null, null, null, null, null, token); // Create 10 samples not indexed for (int i = 0; i < 10; i++) { diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManagerTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManagerTest.java index 32b54176e2f..2944251b262 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManagerTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/VariantStorageManagerTest.java @@ -112,7 +112,7 @@ public void testGetIndexedSamples() throws Exception { indexFile(file, new QueryOptions(), outputId); assertEquals(new HashSet<>(file.getSampleIds()), variantManager.getIndexedSamples(studyId, sessionId)); - Study studyNew = catalogManager.getStudyManager().create(projectId, "sNew", "sNew", "sNew", + Study studyNew = catalogManager.getStudyManager().create(organizationId, projectId, "sNew", "sNew", "sNew", "Study New", null, null, null, null, null, sessionId) .first(); assertEquals(Collections.emptySet(), variantManager.getIndexedSamples(studyNew.getId(), sessionId)); diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/AbstractVariantOperationManagerTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/AbstractVariantOperationManagerTest.java index 9f425d9eb0f..9c5e5b8d34a 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/AbstractVariantOperationManagerTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/AbstractVariantOperationManagerTest.java @@ -142,12 +142,12 @@ public final void setUpAbstract() throws Exception { // Policies policies = new Policies(); // policies.setUserCreation(Policies.UserCreation.ALWAYS); - User user = catalogManager.getUserManager().create(userId, "User", "user@email.org", "userACME1.", "ACME", null, Account.AccountType.FULL, opencga.getAdminToken()).first(); + User user = catalogManager.getUserManager().create(organizationId, userId, "User", "user@email.org", "userACME1.", "ACME", null, Account.AccountType.FULL, opencga.getAdminToken()).first(); sessionId = catalogManager.getUserManager().login(userId, "userACME1.").getToken(); projectId = "p1"; - catalogManager.getProjectManager().create(projectId, projectId, "Project 1", "Homo sapiens", + catalogManager.getProjectManager().create(organizationId, projectId, projectId, "Project 1", "Homo sapiens", null, "GRCh38", new QueryOptions(ParamConstants.INCLUDE_RESULT_PARAM, true), sessionId); - Study study = catalogManager.getStudyManager().create(projectId, "s1", "s1", "s1", + Study study = catalogManager.getStudyManager().create(organizationId, projectId, "s1", "s1", "s1", "Study 1", null, null, null, Collections.singletonMap(VariantStatsAnalysis.STATS_AGGREGATION_CATALOG, getAggregation()), null, sessionId) .first(); studyId = study.getId(); @@ -155,7 +155,7 @@ public final void setUpAbstract() throws Exception { outputId = catalogManager.getFileManager().createFolder(organizationId, studyFqn, Paths.get("data", "index").toString(), true, null, QueryOptions.empty(), sessionId).first().getId(); outputPath = "data/index/"; - studyId2 = catalogManager.getStudyManager().create(projectId, "s2", "s2", "s2", "Study " + "2", null, null, + studyId2 = catalogManager.getStudyManager().create(organizationId, projectId, "s2", "s2", "s2", "Study " + "2", null, null, null, Collections.singletonMap(VariantStatsAnalysis.STATS_AGGREGATION_CATALOG, getAggregation()), null, sessionId).first().getId(); outputId2 = catalogManager.getFileManager().createFolder(organizationId, studyId2, Paths.get("data", "index").toString(), true, null, QueryOptions.empty(), sessionId).first().getId(); @@ -382,14 +382,14 @@ protected List copyResults(Path tmpOutdirPath, String study, String catalo && !ExecutionResultManager.isExecutionResultFile(uri.getPath()) && !uri.getPath().endsWith(OUT_LOG_EXTENSION) && !uri.getPath().endsWith(ERR_LOG_EXTENSION); - files = fileScanner.scan(outDir, tmpOutdirPath.toUri(), FileScanner.FileScannerPolicy.DELETE, false, true, fileStatusFilter, + files = fileScanner.scan(organizationId, outDir, tmpOutdirPath.toUri(), FileScanner.FileScannerPolicy.DELETE, false, true, fileStatusFilter, sessionId); System.out.println("files = " + files); // TODO: Check whether we want to store the logs as well. At this point, we are also storing them. // Do not execute checksum for log files! They may not be closed yet fileStatusFilter = uri -> uri.getPath().endsWith(OUT_LOG_EXTENSION) || uri.getPath().endsWith(ERR_LOG_EXTENSION); - files.addAll(fileScanner.scan(outDir, tmpOutdirPath.toUri(), FileScanner.FileScannerPolicy.DELETE, false, false, + files.addAll(fileScanner.scan(organizationId, outDir, tmpOutdirPath.toUri(), FileScanner.FileScannerPolicy.DELETE, false, false, fileStatusFilter, sessionId)); System.out.println("files2 = " + files); diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/VariantImportTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/VariantImportTest.java index 2cd0a90fd76..c5b67aea31b 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/VariantImportTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/manager/operations/VariantImportTest.java @@ -68,14 +68,14 @@ public void setUp() throws Exception { new Variable("other", "", "", Variable.VariableType.STRING, "unknown", false, false, null, null, 0, null, null, null, null)), Collections.singletonList(VariableSet.AnnotableDataModels.SAMPLE), sessionId); - catalogManager.getSampleManager().update(studyId, "NA19600", new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyId, "NA19600", new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("as1", "vs1", new ObjectMap("name", "NA19600").append("age", 30)))), QueryOptions.empty(), sessionId); - catalogManager.getSampleManager().update(studyId, "NA19660", new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyId, "NA19660", new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("as1", "vs1", new ObjectMap("name", "NA19660").append("age", 35).append("other", "unknown")))), QueryOptions.empty(), sessionId); - catalogManager.getSampleManager().update(studyId, "NA19660", new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyId, "NA19660", new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("as2", "vs1", new ObjectMap("name", "NA19660").append("age", 35).append("other", "asdf")))), QueryOptions.empty(), sessionId); diff --git a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizerTest.java b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizerTest.java index 7aebae94d72..149c067258d 100644 --- a/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizerTest.java +++ b/opencga-analysis/src/test/java/org/opencb/opencga/analysis/variant/metadata/CatalogStorageMetadataSynchronizerTest.java @@ -90,12 +90,12 @@ public static void beforeClass() throws Exception { catalogManager = catalogManagerExternalResource.getCatalogManager(); - catalogManager.getUserManager().create(userId, "User", "user@email.org", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.FULL, catalogManagerExternalResource.getAdminToken()).first(); + catalogManager.getUserManager().create(organizationId, userId, "User", "user@email.org", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.FULL, catalogManagerExternalResource.getAdminToken()).first(); sessionId = catalogManager.getUserManager().login(userId, TestParamConstants.PASSWORD).getToken(); - projectId = catalogManager.getProjectManager().create("p1", "p1", "Project 1", "Homo sapiens", + projectId = catalogManager.getProjectManager().create(organizationId, "p1", "p1", "Project 1", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionId).first().getId(); - Study study = catalogManager.getStudyManager().create(projectId, "s1", null, "s1", "Study " + "1", null, null, + Study study = catalogManager.getStudyManager().create(organizationId, projectId, "s1", null, "s1", "Study " + "1", null, null, null, null, INCLUDE_RESULT, sessionId).first(); studyId = study.getFqn(); catalogManager.getFileManager().createFolder(organizationId, studyId, Paths.get("data", "index").toString(), diff --git a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/CatalogCommandExecutor.java b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/CatalogCommandExecutor.java index 52d6c4351cc..2f8de266008 100644 --- a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/CatalogCommandExecutor.java +++ b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/CatalogCommandExecutor.java @@ -211,7 +211,7 @@ private void index() throws CatalogException { logger.info("\nChecking and installing non-existing indexes in {} in {}\n", catalogManager.getCatalogDatabase(), configuration.getCatalog().getDatabase().getHosts()); - catalogManager.installIndexes(token); + catalogManager.installIndexes(organizationId, token); } private void daemons() throws Exception { diff --git a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MetaCommandExecutor.java b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MetaCommandExecutor.java index 1e9b66a9ac5..29a6f41348c 100644 --- a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MetaCommandExecutor.java +++ b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MetaCommandExecutor.java @@ -63,7 +63,7 @@ private void insertUpdatedAAdmin() throws CatalogException, IOException { params.putIfNotEmpty(MetaDBAdaptor.SECRET_KEY, executor.updateSecretKey); params.putIfNotEmpty(MetaDBAdaptor.ALGORITHM, executor.algorithm); - catalogManager.updateJWTParameters(params, token); + catalogManager.updateJWTParameters(organizationId, params, token); } } diff --git a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MigrationCommandExecutor.java b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MigrationCommandExecutor.java index a360eaa2f1e..bfc32f08e05 100644 --- a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MigrationCommandExecutor.java +++ b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/MigrationCommandExecutor.java @@ -65,8 +65,8 @@ private void summary() throws Exception { try (CatalogManager catalogManager = new CatalogManager(configuration)) { String token = catalogManager.getUserManager().loginAsAdmin(options.commonOptions.adminPassword).getToken(); - catalogManager.getMigrationManager().updateMigrationRuns(token); - MigrationSummary migrationSummary = catalogManager.getMigrationManager().getMigrationSummary(); + catalogManager.getMigrationManager().updateMigrationRuns(organizationId, token); + MigrationSummary migrationSummary = catalogManager.getMigrationManager().getMigrationSummary(organizationId); System.out.println(JacksonUtils.getDefaultObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(migrationSummary)); } @@ -80,7 +80,7 @@ private void search() throws Exception { String token = catalogManager.getUserManager().loginAsAdmin(options.commonOptions.adminPassword).getToken(); List> rows = catalogManager.getMigrationManager() - .getMigrationRuns(options.version, options.domain, options.status, token); + .getMigrationRuns(organizationId, options.version, options.domain, options.status, token); if (options.commonOptions.commonOptions.outputFormat.toLowerCase().contains("json")) { for (Pair pair : rows) { @@ -139,7 +139,7 @@ private void run() throws CatalogException, IOException { String version = parseVersion(options.version); MigrationManager migrationManager = catalogManager.getMigrationManager(); - migrationManager.runMigration(version, options.domain, options.language, options.offline, appHome, token); + migrationManager.runMigration(organizationId, version, options.domain, options.language, options.offline, appHome, token); } } @@ -150,7 +150,7 @@ private void runManual() throws Exception { try (CatalogManager catalogManager = new CatalogManager(configuration)) { String token = catalogManager.getUserManager().loginAsAdmin(options.commonOptions.adminPassword).getToken(); - catalogManager.getMigrationManager().runManualMigration(parseVersion(options.version), options.id, Paths.get(appHome), + catalogManager.getMigrationManager().runManualMigration(organizationId, parseVersion(options.version), options.id, Paths.get(appHome), options.force, options.offline, new ObjectMap(options.commonOptions.commonOptions.params), token); } } diff --git a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/UsersCommandExecutor.java b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/UsersCommandExecutor.java index 1162fdb2dc6..94c9d643769 100644 --- a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/UsersCommandExecutor.java +++ b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/UsersCommandExecutor.java @@ -82,9 +82,9 @@ private void syncGroups() throws CatalogException { String token = catalogManager.getUserManager().loginAsAdmin(executor.commonOptions.adminPassword).getToken(); if (executor.syncAll) { - catalogManager.getUserManager().syncAllUsersOfExternalGroup(executor.study, executor.authOrigin, token); + catalogManager.getUserManager().syncAllUsersOfExternalGroup(organizationId, executor.study, executor.authOrigin, token); } else { - catalogManager.getUserManager().importRemoteGroupOfUsers(executor.authOrigin, executor.from, executor.to, executor.study, + catalogManager.getUserManager().importRemoteGroupOfUsers(organizationId, executor.authOrigin, executor.from, executor.to, executor.study, true, token); } } @@ -113,10 +113,10 @@ private void importUsersAndGroups() throws CatalogException { } if ("user".equalsIgnoreCase(executor.resourceType) || "application".equalsIgnoreCase(executor.resourceType)) { - catalogManager.getUserManager().importRemoteEntities(executor.authOrigin, Arrays.asList(executor.id.split(",")), + catalogManager.getUserManager().importRemoteEntities(organizationId, executor.authOrigin, Arrays.asList(executor.id.split(",")), executor.resourceType.equalsIgnoreCase("application"), executor.studyGroup, executor.study, token); } else if ("group".equalsIgnoreCase(executor.resourceType)) { - catalogManager.getUserManager().importRemoteGroupOfUsers(executor.authOrigin, executor.id, executor.studyGroup, + catalogManager.getUserManager().importRemoteGroupOfUsers(organizationId, executor.authOrigin, executor.id, executor.studyGroup, executor.study, false, token); } else { logger.error("Unknown resource type. Please use one of 'user', 'group' or 'application'"); @@ -154,7 +154,7 @@ private void create() throws CatalogException { User user; try { - user = catalogManager.getUserManager().create(commandOptions.userId, commandOptions.userName, commandOptions.userEmail, + user = catalogManager.getUserManager().create(organizationId, commandOptions.userId, commandOptions.userName, commandOptions.userEmail, commandOptions.userPassword, commandOptions.userOrganization, userQuota, commandOptions.type, token).first(); } catch (CatalogException e) { if (e.getMessage().contains("already exists")) { @@ -179,7 +179,7 @@ private void delete() throws CatalogException, IOException { catalogManager.getUserManager().loginAsAdmin(usersCommandOptions.deleteUserCommandOptions.commonOptions.adminPassword); DataResult deletedUsers = catalogManager.getUserManager() - .delete(usersCommandOptions.deleteUserCommandOptions.userId, new QueryOptions("force", true), null); + .delete(organizationId, usersCommandOptions.deleteUserCommandOptions.userId, new QueryOptions("force", true), null); for (User user : deletedUsers.getResults()) { if (user != null) { System.out.println("The user has been successfully deleted from the database: " + user.toString()); @@ -197,7 +197,7 @@ private void setQuota() throws CatalogException { try (CatalogManager catalogManager = new CatalogManager(configuration)) { catalogManager.getUserManager().loginAsAdmin(usersCommandOptions.quotaUserCommandOptions.commonOptions.adminPassword); - User user = catalogManager.getUserManager().update(usersCommandOptions.quotaUserCommandOptions.userId, new ObjectMap + User user = catalogManager.getUserManager().update(organizationId, usersCommandOptions.quotaUserCommandOptions.userId, new ObjectMap (UserDBAdaptor.QueryParams.QUOTA.key(), usersCommandOptions.quotaUserCommandOptions.quota * 1073741824), null, null).first(); System.out.println("The disk quota has been properly updated: " + user.toString()); diff --git a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/migration/v2_0_0/VariantStorage200MigrationTool.java b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/migration/v2_0_0/VariantStorage200MigrationTool.java index 39319cd310e..96c4bfc8b85 100644 --- a/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/migration/v2_0_0/VariantStorage200MigrationTool.java +++ b/opencga-app/src/main/java/org/opencb/opencga/app/cli/admin/executors/migration/v2_0_0/VariantStorage200MigrationTool.java @@ -26,7 +26,7 @@ public class VariantStorage200MigrationTool extends OpenCgaTool { protected void check() throws Exception { super.check(); - String userId = getCatalogManager().getUserManager().getUserId(getToken()); + String userId = getCatalogManager().getUserManager().getUserId(organizationId, getToken()); if (!userId.equals(ParamConstants.OPENCGA_USER_ID)) { throw new CatalogAuthenticationException("Only user '" + ParamConstants.OPENCGA_USER_ID + "' can run this operation!"); } diff --git a/opencga-app/src/test/java/org/opencb/opencga/app/cli/analysis/InternalMainTest.java b/opencga-app/src/test/java/org/opencb/opencga/app/cli/analysis/InternalMainTest.java index e8d49118995..18302b43ca1 100644 --- a/opencga-app/src/test/java/org/opencb/opencga/app/cli/analysis/InternalMainTest.java +++ b/opencga-app/src/test/java/org/opencb/opencga/app/cli/analysis/InternalMainTest.java @@ -102,10 +102,10 @@ public void setUp() throws Exception { opencga.clearStorageDB(STORAGE_ENGINE, dbNameVariants); opencga.clearStorageDB(STORAGE_ENGINE, dbNameAlignments); - User user = catalogManager.getUserManager().create(userId, "User", "user@email.org", "user", "ACME", null, Account.AccountType.FULL, opencga.getAdminToken()).first(); + User user = catalogManager.getUserManager().create(organizationId, userId, "User", "user@email.org", "user", "ACME", null, Account.AccountType.FULL, opencga.getAdminToken()).first(); sessionId = catalogManager.getUserManager().login(userId, "user").getToken(); - projectId = catalogManager.getProjectManager().create("p1", "p1", "Project 1", "Homo sapiens", + projectId = catalogManager.getProjectManager().create(organizationId, "p1", "p1", "Project 1", "Homo sapiens", null, "GRCh38", new QueryOptions(), sessionId).first().getId(); datastores = new HashMap<>(); @@ -116,7 +116,7 @@ public void setUp() throws Exception { } private void createStudy(Map datastores, String studyName) throws CatalogException { - Study study = catalogManager.getStudyManager().create(projectId, studyName, studyName, studyName, "Study 1", null, + Study study = catalogManager.getStudyManager().create(organizationId, projectId, studyName, studyName, studyName, "Study 1", null, null, null, Collections.singletonMap(VariantStorageOptions.STATS_AGGREGATION.key(), Aggregation.NONE), null, sessionId) .first(); studyId = study.getId(); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/DBAdaptorFactory.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/DBAdaptorFactory.java index 6d57497be2f..29d036bcf0f 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/DBAdaptorFactory.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/DBAdaptorFactory.java @@ -20,6 +20,8 @@ import org.opencb.opencga.catalog.db.api.*; import org.opencb.opencga.catalog.exceptions.CatalogDBException; import org.opencb.opencga.catalog.exceptions.CatalogException; +import org.opencb.opencga.core.api.ParamConstants; +import org.opencb.opencga.core.config.Admin; import org.opencb.opencga.core.config.Configuration; import java.util.List; @@ -43,6 +45,18 @@ public interface DBAdaptorFactory extends AutoCloseable { */ void createAllCollections(Configuration configuration) throws CatalogException; + /** + * Initialise meta collection. + * + * @param admin Admin information. + * @throws CatalogException if there is any problem with the installation. + */ + void initialiseMetaCollection(Admin admin) throws CatalogException; + + default String getAdminCatalogDatabase(String prefix) { + return getCatalogOrganizationDatabase(prefix, ParamConstants.ADMIN_ORGANIZATION); + } + default String getCatalogDatabase(String prefix) { String dbPrefix = StringUtils.isEmpty(prefix) ? "opencga" : prefix; dbPrefix = dbPrefix.endsWith("_") ? dbPrefix : dbPrefix + "_"; @@ -73,12 +87,12 @@ default String getCatalogOrganizationDatabase(String prefix, String organization List getOrganizationIds(); - OrganizationDBAdaptor getCatalogOrganizationDBAdaptor(); - MigrationDBAdaptor getMigrationDBAdaptor(String organization) throws CatalogDBException; MetaDBAdaptor getCatalogMetaDBAdaptor(String organization) throws CatalogDBException; + OrganizationDBAdaptor getCatalogOrganizationDBAdaptor(String organization) throws CatalogDBException; + UserDBAdaptor getCatalogUserDBAdaptor(String organization) throws CatalogDBException; ProjectDBAdaptor getCatalogProjectDbAdaptor(String organization) throws CatalogDBException; diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/MongoDBAdaptorFactory.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/MongoDBAdaptorFactory.java index 076fed562a7..6e2ed0954b1 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/MongoDBAdaptorFactory.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/MongoDBAdaptorFactory.java @@ -16,13 +16,10 @@ package org.opencb.opencga.catalog.db.mongodb; -import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang3.StringUtils; -import org.bson.Document; import org.opencb.commons.datastore.core.DataStoreServerAddress; -import org.opencb.commons.datastore.core.ObjectMap; import org.opencb.commons.datastore.core.Query; -import org.opencb.commons.datastore.mongodb.MongoDBCollection; +import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.datastore.mongodb.MongoDBConfiguration; import org.opencb.commons.datastore.mongodb.MongoDataStore; import org.opencb.commons.datastore.mongodb.MongoDataStoreManager; @@ -30,7 +27,8 @@ import org.opencb.opencga.catalog.db.api.*; import org.opencb.opencga.catalog.exceptions.CatalogDBException; import org.opencb.opencga.catalog.exceptions.CatalogException; -import org.opencb.opencga.catalog.managers.OrganizationManager; +import org.opencb.opencga.core.api.ParamConstants; +import org.opencb.opencga.core.config.Admin; import org.opencb.opencga.core.config.Configuration; import org.opencb.opencga.core.models.organizations.Organization; import org.opencb.opencga.core.response.OpenCGAResult; @@ -39,22 +37,15 @@ import java.util.*; -import static org.opencb.opencga.core.common.JacksonUtils.getDefaultObjectMapper; - /** * Created by pfurio on 08/01/16. */ public class MongoDBAdaptorFactory implements DBAdaptorFactory { - public static final String ORGANIZATION_COLLECTION = "organization"; - private final MongoDataStoreManager mongoManager; - private final MongoDBConfiguration configuration; - private final String database; - private MongoDataStore mongoDataStore; + private final MongoDBConfiguration mongoDbConfiguration; private Map organizationDBAdaptorMap; - private OrganizationMongoDBAdaptor organizationDBAdaptor; private final Logger logger; @@ -79,8 +70,8 @@ public MongoDBAdaptorFactory(Configuration catalogConfiguration) throws CatalogD .build(); this.mongoManager = new MongoDataStoreManager(dataStoreServerAddresses); - this.configuration = mongoDBConfiguration; - this.database = getCatalogDatabase(catalogConfiguration.getDatabasePrefix()); + this.mongoDbConfiguration = mongoDBConfiguration; +// this.database = getAdminCatalogDatabase(catalogConfiguration.getDatabasePrefix()); logger = LoggerFactory.getLogger(this.getClass()); connect(catalogConfiguration); @@ -88,43 +79,46 @@ public MongoDBAdaptorFactory(Configuration catalogConfiguration) throws CatalogD @Override public void createAllCollections(Configuration configuration) throws CatalogException { - // TODO: Check META object does not exist. Use {@link isCatalogDBReady} - // TODO: Check all collections do not exists, or are empty - // TODO: Catch DuplicatedKeyException while inserting META object - - MongoDataStore mongoDataStore = mongoManager.get(database, this.configuration); - if (!mongoDataStore.getCollectionNames().isEmpty()) { - throw new CatalogException("Database " + database + " already exists with the following collections: " - + StringUtils.join(mongoDataStore.getCollectionNames()) + ".\nPlease, remove the database or choose a different one."); + for (OrganizationMongoDBAdaptorFactory orgFactory : organizationDBAdaptorMap.values()) { + MongoDataStore mongoDataStore = orgFactory.getMongoDataStore(); + if (!mongoDataStore.getCollectionNames().isEmpty()) { + throw new CatalogException("Database " + mongoDataStore.getDatabaseName() + " already exists with the following " + + "collections: " + StringUtils.join(mongoDataStore.getCollectionNames()) + ".\nPlease, remove the database or" + + " choose a different one."); + } + OrganizationMongoDBAdaptorFactory.COLLECTIONS_LIST.forEach(mongoDataStore::createCollection); } - OrganizationMongoDBAdaptorFactory.COLLECTIONS_LIST.forEach(mongoDataStore::createCollection); } @Override - public boolean getDatabaseStatus() { - Document dbStatus = mongoManager.get(database, this.configuration).getServerStatus(); - try { - ObjectMap map = new ObjectMap(getDefaultObjectMapper().writeValueAsString(dbStatus)); - return map.getInt("ok", 0) > 0; - } catch (JsonProcessingException e) { - logger.error(e.getMessage(), e); - return false; + public void initialiseMetaCollection(Admin admin) throws CatalogException { + for (OrganizationMongoDBAdaptorFactory dbAdaptorFactory : organizationDBAdaptorMap.values()) { + dbAdaptorFactory.initialiseMetaCollection(admin); } } @Override - public void deleteCatalogDB() throws CatalogDBException { - mongoManager.drop(database); + public boolean getDatabaseStatus() { + return organizationDBAdaptorMap.get(ParamConstants.ADMIN_ORGANIZATION).getDatabaseStatus(); + } + + @Override + public void deleteCatalogDB() { + for (OrganizationMongoDBAdaptorFactory dbAdaptorFactory : organizationDBAdaptorMap.values()) { + dbAdaptorFactory.deleteCatalogDB(); + } } @Override public boolean isCatalogDBReady() { - return !mongoDataStore.getCollectionNames().isEmpty(); + return organizationDBAdaptorMap.get(ParamConstants.ADMIN_ORGANIZATION).isCatalogDBReady(); } @Override public void close() { - mongoManager.close(mongoDataStore.getDatabaseName()); + for (OrganizationMongoDBAdaptorFactory dbAdaptorFactory : organizationDBAdaptorMap.values()) { + dbAdaptorFactory.close(); + } } @Override @@ -138,39 +132,37 @@ public List getOrganizationIds() { return new ArrayList<>(organizationDBAdaptorMap.keySet()); } - public MongoDataStore getMongoDataStore() { - return mongoDataStore; + public MongoDataStore getMongoDataStore(String organization) throws CatalogDBException { + return getOrganizationMongoDBAdaptorFactory(organization).getMongoDataStore(); } private void connect(Configuration catalogConfiguration) throws CatalogDBException { - mongoDataStore = mongoManager.get(database, configuration); - if (mongoDataStore == null) { - throw new CatalogDBException("Unable to connect to MongoDB '" + database + "'"); - } - - MongoDBCollection organizationCollection = mongoDataStore.getCollection(ORGANIZATION_COLLECTION); - MongoDBCollection deletedOrganizationCollection = mongoDataStore - .getCollection(OrganizationMongoDBAdaptorFactory.DELETED_ORGANIZATION_COLLECTION); - organizationDBAdaptor = new OrganizationMongoDBAdaptor(organizationCollection, deletedOrganizationCollection, catalogConfiguration, - this); - - // Fetch all organizations present in the database - OpenCGAResult result = organizationDBAdaptor.get(new Query(), OrganizationManager.INCLUDE_ORGANIZATION_IDS); - - // And create connections to them + // Init map of organization db adaptor factories organizationDBAdaptorMap = new HashMap<>(); - for (Organization organization : result.getResults()) { - String organizationDB = getCatalogOrganizationDatabase(catalogConfiguration.getDatabasePrefix(), organization.getId()); - OrganizationMongoDBAdaptorFactory orgFactory = new OrganizationMongoDBAdaptorFactory(mongoManager, configuration, - organizationDB, catalogConfiguration); - organizationDBAdaptorMap.put(organization.getId(), orgFactory); + // Configure admin organization first + OrganizationMongoDBAdaptorFactory adminFactory = configureOrganizationMongoDBAdaptorFactory(ParamConstants.ADMIN_ORGANIZATION, + catalogConfiguration); + organizationDBAdaptorMap.put(ParamConstants.ADMIN_ORGANIZATION, adminFactory); + + // Read organizations present in the installation + OpenCGAResult result = adminFactory.getCatalogOrganizationDBAdaptor().get(new Query(), QueryOptions.empty()); + if (result.getNumResults() == 1) { + // TODO: Read organizations present in the installation + List organizationIds = Collections.emptyList(); + + for (String organizationId : organizationIds) { + OrganizationMongoDBAdaptorFactory orgFactory = configureOrganizationMongoDBAdaptorFactory(organizationId, + catalogConfiguration); + organizationDBAdaptorMap.put(organizationId, orgFactory); + } } } - @Override - public OrganizationDBAdaptor getCatalogOrganizationDBAdaptor() { - return organizationDBAdaptor; + private OrganizationMongoDBAdaptorFactory configureOrganizationMongoDBAdaptorFactory(String organizationId, Configuration configuration) + throws CatalogDBException { + String organizationDB = getCatalogOrganizationDatabase(configuration.getDatabasePrefix(), organizationId); + return new OrganizationMongoDBAdaptorFactory(mongoManager, mongoDbConfiguration, organizationDB, configuration); } private OrganizationMongoDBAdaptorFactory getOrganizationMongoDBAdaptorFactory(String organization) throws CatalogDBException { @@ -191,6 +183,11 @@ public MetaDBAdaptor getCatalogMetaDBAdaptor(String organization) throws Catalog return getOrganizationMongoDBAdaptorFactory(organization).getCatalogMetaDBAdaptor(); } + @Override + public OrganizationDBAdaptor getCatalogOrganizationDBAdaptor(String organization) throws CatalogDBException { + return getOrganizationMongoDBAdaptorFactory(organization).getCatalogOrganizationDBAdaptor(); + } + @Override public UserDBAdaptor getCatalogUserDBAdaptor(String organization) throws CatalogDBException { return getOrganizationMongoDBAdaptorFactory(organization).getCatalogUserDBAdaptor(); @@ -198,7 +195,7 @@ public UserDBAdaptor getCatalogUserDBAdaptor(String organization) throws Catalog @Override public ProjectDBAdaptor getCatalogProjectDbAdaptor(String organization) throws CatalogDBException { - return getOrganizationMongoDBAdaptorFactory(organization).getCatalogProjectDbAdaptor(); + return getOrganizationMongoDBAdaptorFactory(organization).getCatalogProjectDBAdaptor(); } @Override diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptor.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptor.java index 7001ac7d21e..25c08ccae5f 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptor.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptor.java @@ -36,15 +36,13 @@ public class OrganizationMongoDBAdaptor extends MongoDBAdaptor implements OrganizationDBAdaptor { private final MongoDBCollection organizationCollection; - private final MongoDBCollection deletedOrganizationCollection; - private OrganizationConverter organizationConverter; + private final OrganizationConverter organizationConverter; - public OrganizationMongoDBAdaptor(MongoDBCollection organizationCollection, MongoDBCollection deletedOrganizationCollection, - Configuration configuration, MongoDBAdaptorFactory dbAdaptorFactory) { + public OrganizationMongoDBAdaptor(MongoDBCollection organizationCollection, Configuration configuration, + OrganizationMongoDBAdaptorFactory dbAdaptorFactory) { super(configuration, LoggerFactory.getLogger(OrganizationMongoDBAdaptor.class)); this.dbAdaptorFactory = dbAdaptorFactory; this.organizationCollection = organizationCollection; - this.deletedOrganizationCollection = deletedOrganizationCollection; this.organizationConverter = new OrganizationConverter(); } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptorFactory.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptorFactory.java index 74992a362a3..cc89f3c5ade 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptorFactory.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/OrganizationMongoDBAdaptorFactory.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.mongodb.client.model.Filters; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.StopWatch; import org.bson.Document; import org.opencb.commons.datastore.core.ObjectMap; @@ -27,6 +26,7 @@ public class OrganizationMongoDBAdaptorFactory { + public static final String ORGANIZATION_COLLECTION = "organization"; public static final String USER_COLLECTION = "user"; public static final String STUDY_COLLECTION = "study"; public static final String FILE_COLLECTION = "file"; @@ -45,7 +45,6 @@ public class OrganizationMongoDBAdaptorFactory { public static final String PANEL_ARCHIVE_COLLECTION = "panel_archive"; public static final String INTERPRETATION_ARCHIVE_COLLECTION = "interpretation_archive"; - public static final String DELETED_ORGANIZATION_COLLECTION = "organization_deleted"; public static final String DELETED_USER_COLLECTION = "user_deleted"; public static final String DELETED_STUDY_COLLECTION = "study_deleted"; public static final String DELETED_FILE_COLLECTION = "file_deleted"; @@ -63,7 +62,7 @@ public class OrganizationMongoDBAdaptorFactory { public static final String AUDIT_COLLECTION = "audit"; public static final List COLLECTIONS_LIST = Arrays.asList( - MongoDBAdaptorFactory.ORGANIZATION_COLLECTION, + ORGANIZATION_COLLECTION, USER_COLLECTION, STUDY_COLLECTION, FILE_COLLECTION, @@ -82,7 +81,6 @@ public class OrganizationMongoDBAdaptorFactory { PANEL_ARCHIVE_COLLECTION, INTERPRETATION_ARCHIVE_COLLECTION, - DELETED_ORGANIZATION_COLLECTION, DELETED_USER_COLLECTION, DELETED_STUDY_COLLECTION, DELETED_FILE_COLLECTION, @@ -105,6 +103,7 @@ public class OrganizationMongoDBAdaptorFactory { private final MongoDataStore mongoDataStore; private final String database; + private final OrganizationMongoDBAdaptor organizationDBAdaptor; private final UserMongoDBAdaptor userDBAdaptor; private final StudyMongoDBAdaptor studyDBAdaptor; private final IndividualMongoDBAdaptor individualDBAdaptor; @@ -140,6 +139,7 @@ public OrganizationMongoDBAdaptorFactory(MongoDataStoreManager mongoDataStoreMan metaCollection = mongoDataStore.getCollection(METADATA_COLLECTION); MongoDBCollection migrationCollection = mongoDataStore.getCollection(MIGRATION_COLLECTION); + MongoDBCollection organizationCollection = mongoDataStore.getCollection(ORGANIZATION_COLLECTION); MongoDBCollection userCollection = mongoDataStore.getCollection(USER_COLLECTION); MongoDBCollection studyCollection = mongoDataStore.getCollection(STUDY_COLLECTION); MongoDBCollection fileCollection = mongoDataStore.getCollection(FILE_COLLECTION); @@ -172,6 +172,7 @@ public OrganizationMongoDBAdaptorFactory(MongoDataStoreManager mongoDataStoreMan MongoDBCollection auditCollection = mongoDataStore.getCollection(AUDIT_COLLECTION); + organizationDBAdaptor = new OrganizationMongoDBAdaptor(organizationCollection, configuration, this); fileDBAdaptor = new FileMongoDBAdaptor(fileCollection, deletedFileCollection, configuration, this); familyDBAdaptor = new FamilyMongoDBAdaptor(familyCollection, familyArchivedCollection, deletedFamilyCollection, configuration, this); @@ -197,6 +198,7 @@ public OrganizationMongoDBAdaptorFactory(MongoDataStoreManager mongoDataStoreMan mongoDBCollectionMap.put(METADATA_COLLECTION, metaCollection); mongoDBCollectionMap.put(MIGRATION_COLLECTION, migrationCollection); + mongoDBCollectionMap.put(ORGANIZATION_COLLECTION, organizationCollection); mongoDBCollectionMap.put(USER_COLLECTION, userCollection); mongoDBCollectionMap.put(STUDY_COLLECTION, studyCollection); mongoDBCollectionMap.put(FILE_COLLECTION, fileCollection); @@ -234,17 +236,17 @@ public boolean isCatalogDBReady() { return metaCollection.count(Filters.eq("id", METADATA_OBJECT_ID)).getNumMatches() == 1; } - public void createAllCollections(Configuration configuration) throws CatalogException { - // TODO: Check META object does not exist. Use {@link isCatalogDBReady} - // TODO: Check all collections do not exists, or are empty - // TODO: Catch DuplicatedKeyException while inserting META object - - if (!mongoDataStore.getCollectionNames().isEmpty()) { - throw new CatalogException("Database " + database + " already exists with the following collections: " - + StringUtils.join(mongoDataStore.getCollectionNames()) + ".\nPlease, remove the database or choose a different one."); - } - COLLECTIONS_LIST.forEach(mongoDataStore::createCollection); - } +// public void createAllCollections(Configuration configuration) throws CatalogException { +// // TODO: Check META object does not exist. Use {@link isCatalogDBReady} +// // TODO: Check all collections do not exists, or are empty +// // TODO: Catch DuplicatedKeyException while inserting META object +// +// if (!mongoDataStore.getCollectionNames().isEmpty()) { +// throw new CatalogException("Database " + database + " already exists with the following collections: " +// + StringUtils.join(mongoDataStore.getCollectionNames()) + ".\nPlease, remove the database or choose a different one."); +// } +// COLLECTIONS_LIST.forEach(mongoDataStore::createCollection); +// } public void initialiseMetaCollection(Admin admin) throws CatalogException { metaDBAdaptor.initializeMetaCollection(admin); @@ -287,11 +289,15 @@ public MetaMongoDBAdaptor getCatalogMetaDBAdaptor() { return metaDBAdaptor; } + public OrganizationMongoDBAdaptor getCatalogOrganizationDBAdaptor() { + return organizationDBAdaptor; + } + public UserMongoDBAdaptor getCatalogUserDBAdaptor() { return userDBAdaptor; } - public ProjectMongoDBAdaptor getCatalogProjectDbAdaptor() { + public ProjectMongoDBAdaptor getCatalogProjectDBAdaptor() { return projectDBAdaptor; } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/StudyMongoDBAdaptor.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/StudyMongoDBAdaptor.java index 06e58b3e7ae..23bd2a546fa 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/StudyMongoDBAdaptor.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/StudyMongoDBAdaptor.java @@ -320,7 +320,7 @@ Study insert(ClientSession clientSession, Project project, Study study) @Override public OpenCGAResult getAllStudiesInProject(long projectId, QueryOptions options) throws CatalogDBException { long startTime = startQuery(); - dbAdaptorFactory.getCatalogProjectDbAdaptor().checkId(projectId); + dbAdaptorFactory.getCatalogProjectDBAdaptor().checkId(projectId); Query query = new Query(QueryParams.PROJECT_ID.key(), projectId); return endQuery(startTime, get(query, options)); } @@ -375,7 +375,7 @@ int getCurrentRelease(ClientSession clientSession, long studyUid) throws Catalog .append(ProjectDBAdaptor.QueryParams.USER_ID.key(), userId) .append(ProjectDBAdaptor.QueryParams.ID.key(), projectId); options = new QueryOptions(QueryOptions.INCLUDE, ProjectDBAdaptor.QueryParams.CURRENT_RELEASE.key()); - OpenCGAResult projectResult = dbAdaptorFactory.getCatalogProjectDbAdaptor().get(clientSession, query, options); + OpenCGAResult projectResult = dbAdaptorFactory.getCatalogProjectDBAdaptor().get(clientSession, query, options); if (projectResult.getNumResults() == 0) { throw new CatalogDBException("Project id '" + projectId + "' from user '" + userId + "' not found."); } @@ -1336,7 +1336,7 @@ public long getStudyIdByVariableSetId(long variableSetId) throws CatalogDBExcept public OpenCGAResult getStudiesFromUser(String userId, QueryOptions queryOptions) throws CatalogDBException { OpenCGAResult result = OpenCGAResult.empty(); - OpenCGAResult allProjects = dbAdaptorFactory.getCatalogProjectDbAdaptor().get(userId, new QueryOptions()); + OpenCGAResult allProjects = dbAdaptorFactory.getCatalogProjectDBAdaptor().get(userId, new QueryOptions()); if (allProjects.getNumResults() == 0) { return result; } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/UserMongoDBAdaptor.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/UserMongoDBAdaptor.java index 7ed441e14ea..342def3594d 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/UserMongoDBAdaptor.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/db/mongodb/UserMongoDBAdaptor.java @@ -406,7 +406,7 @@ private void extractSharedProjects(DataResult userDataResult, QueryOptions Map studyMap = new HashMap<>(); Map studyProjectMap = new HashMap<>(); Map> userStudyMap = new HashMap<>(); - OpenCGAResult result = dbAdaptorFactory.getCatalogProjectDbAdaptor().get(new Query(), options); + OpenCGAResult result = dbAdaptorFactory.getCatalogProjectDBAdaptor().get(new Query(), options); for (Project project : result.getResults()) { projectMap.put(project.getFqn(), project); if (project.getStudies() != null) { @@ -480,7 +480,7 @@ public OpenCGAResult nativeGet(Query query, QueryOptions options) throws Catalog for (Document project : projects) { Query query1 = new Query(ProjectDBAdaptor.QueryParams.UID.key(), project.get(ProjectDBAdaptor .QueryParams.UID.key())); - OpenCGAResult queryResult1 = dbAdaptorFactory.getCatalogProjectDbAdaptor().nativeGet(query1, options); + OpenCGAResult queryResult1 = dbAdaptorFactory.getCatalogProjectDBAdaptor().nativeGet(query1, options); projectsTmp.add(queryResult1.first()); } user.remove("projects"); @@ -586,7 +586,7 @@ public OpenCGAResult delete(String id, QueryOptions queryOptions) if (queryOptions.containsKey(FORCE) && queryOptions.getBoolean(FORCE)) { // Delete the active projects (if any) query = new Query(ProjectDBAdaptor.QueryParams.USER_ID.key(), id); - dbAdaptorFactory.getCatalogProjectDbAdaptor().delete(query, queryOptions); + dbAdaptorFactory.getCatalogProjectDBAdaptor().delete(query, queryOptions); } // Change the status of the user to deleted @@ -603,7 +603,7 @@ private void checkCanDelete(String userId) throws CatalogDBException, CatalogPar checkId(userId); Query query = new Query(ProjectDBAdaptor.QueryParams.USER_ID.key(), userId) .append(ProjectDBAdaptor.QueryParams.INTERNAL_STATUS_ID.key(), InternalStatus.READY); - Long count = dbAdaptorFactory.getCatalogProjectDbAdaptor().count(query).getNumMatches(); + Long count = dbAdaptorFactory.getCatalogProjectDBAdaptor().count(query).getNumMatches(); if (count > 0) { throw new CatalogDBException("The user {" + userId + "} cannot be deleted. The user has " + count + " projects in use."); } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AbstractManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AbstractManager.java index c0174123815..7c0c769bbf7 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AbstractManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AbstractManager.java @@ -75,10 +75,6 @@ public abstract class AbstractManager { logger = LoggerFactory.getLogger(this.getClass()); } - protected OrganizationDBAdaptor getOrganizationDBAdaptor() { - return catalogDBAdaptorFactory.getCatalogOrganizationDBAdaptor(); - } - protected MigrationDBAdaptor getMigrationDBAdaptor(String organization) throws CatalogDBException { return catalogDBAdaptorFactory.getMigrationDBAdaptor(organization); } @@ -87,6 +83,10 @@ protected MetaDBAdaptor getCatalogMetaDBAdaptor(String organization) throws Cata return catalogDBAdaptorFactory.getCatalogMetaDBAdaptor(organization); } + protected OrganizationDBAdaptor getOrganizationDBAdaptor(String organization) { + return catalogDBAdaptorFactory.getCatalogOrganizationDBAdaptor(organization); + } + protected UserDBAdaptor getUserDBAdaptor(String organization) throws CatalogDBException { return catalogDBAdaptorFactory.getCatalogUserDBAdaptor(organization); } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AdminManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AdminManager.java index aa8b1fb2881..a29172a6149 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AdminManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AdminManager.java @@ -36,7 +36,7 @@ public class AdminManager extends AbstractManager { this.catalogIOManager = catalogIOManager; } - public OpenCGAResult userSearch(Query query, QueryOptions options, String token) + public OpenCGAResult userSearch(String organizationId, Query query, QueryOptions options, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); @@ -45,7 +45,7 @@ public OpenCGAResult userSearch(Query query, QueryOptions options, String .append("query", query) .append("options", options) .append("token", token); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); try { authorizationManager.checkIsInstallationAdministrator(userId); @@ -67,7 +67,7 @@ public OpenCGAResult userSearch(Query query, QueryOptions options, String query.remove(ParamConstants.USER_CREATION_DATE); } - OpenCGAResult userDataResult = userDBAdaptor.get(query, options); + OpenCGAResult userDataResult = getUserDBAdaptor(organizationId).get(query, options); auditManager.auditSearch(userId, Enums.Resource.USER, "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); return userDataResult; @@ -78,21 +78,22 @@ public OpenCGAResult userSearch(Query query, QueryOptions options, String } } - public OpenCGAResult updateGroups(String userId, List studyIds, List groupIds, + public OpenCGAResult updateGroups(String organizationId, String userId, List studyIds, List groupIds, ParamUtils.AddRemoveAction action, String token) throws CatalogException { ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("studyIds", studyIds) .append("groupIds", groupIds) .append("action", action) .append("token", token); - String authenticatedUser = catalogManager.getUserManager().getUserId(token); + String authenticatedUser = catalogManager.getUserManager().getUserId(organizationId, token); try { authorizationManager.checkIsInstallationAdministrator(authenticatedUser); // Check userId exists Query query = new Query(UserDBAdaptor.QueryParams.ID.key(), userId); - OpenCGAResult count = userDBAdaptor.count(query); + OpenCGAResult count = getUserDBAdaptor(organizationId).count(query); if (count.getNumMatches() == 0) { throw new CatalogException("User '" + userId + "' not found."); } @@ -119,7 +120,7 @@ public OpenCGAResult updateGroups(String userId, List studyIds, L } } - OpenCGAResult result = studyDBAdaptor.updateUserFromGroups(userId, studyUids, groupIds, action); + OpenCGAResult result = getStudyDBAdaptor(organizationId).updateUserFromGroups(userId, studyUids, groupIds, action); auditManager.audit(userId, Enums.Action.UPDATE_USERS_FROM_STUDY_GROUP, Enums.Resource.STUDY, "", "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -135,31 +136,33 @@ public OpenCGAResult updateGroups(String userId, List studyIds, L * Add a user to all the remote groups he/she may belong for a particular authentication origin. * Also remove the user from other groups he/she may have been associated in the past for the same authentication origin. * - * @param userId User id. - * @param remoteGroupIds List of group ids the user must be associated with. + * @param organizationId Organization id. + * @param userId User id. + * @param remoteGroupIds List of group ids the user must be associated with. * @param authenticationOriginId The authentication origin the groups must be associated to. - * @param token Administrator token. + * @param token Administrator token. * @return An empty OpenCGAResult. * @throws CatalogException If the token is invalid or belongs to a user other thant the Administrator and if userId does not exist. */ - public OpenCGAResult syncRemoteGroups(String userId, List remoteGroupIds, - String authenticationOriginId, String token) throws CatalogException { + public OpenCGAResult syncRemoteGroups(String organizationId, String userId, List remoteGroupIds, + String authenticationOriginId, String token) throws CatalogException { ObjectMap auditParams = new ObjectMap() .append("userId", userId) .append("remoteGroupIds", remoteGroupIds) .append("authenticationOriginId", authenticationOriginId) .append("token", token); - String authenticatedUser = catalogManager.getUserManager().getUserId(token); + String authenticatedUser = catalogManager.getUserManager().getUserId(organizationId, token); try { authorizationManager.checkIsInstallationAdministrator(authenticatedUser); // Check userId exists Query query = new Query(UserDBAdaptor.QueryParams.ID.key(), userId); - OpenCGAResult count = userDBAdaptor.count(query); + OpenCGAResult count = getUserDBAdaptor(organizationId).count(query); if (count.getNumMatches() == 0) { throw new CatalogException("User '" + userId + "' not found."); } - OpenCGAResult result = studyDBAdaptor.resyncUserWithSyncedGroups(userId, remoteGroupIds, authenticationOriginId); + OpenCGAResult result = getStudyDBAdaptor(organizationId).resyncUserWithSyncedGroups(userId, remoteGroupIds, + authenticationOriginId); auditManager.audit(userId, Enums.Action.UPDATE_USERS_FROM_STUDY_GROUP, Enums.Resource.STUDY, "", "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AnnotationSetManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AnnotationSetManager.java index 890696e13ca..1e7cd90dd19 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AnnotationSetManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AnnotationSetManager.java @@ -112,9 +112,10 @@ protected void validateNewAnnotationSets(List variableSetList, List } } - public OpenCGAResult loadTsvAnnotations(String studyStr, String variableSetId, String path, TsvAnnotationParams tsvParams, - ObjectMap params, String toolId, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + public OpenCGAResult loadTsvAnnotations(String organizationId, String studyStr, String variableSetId, String path, + TsvAnnotationParams tsvParams, ObjectMap params, String toolId, String token) + throws CatalogException { + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); ParamUtils.checkObj(variableSetId, "VariableSetId"); @@ -144,8 +145,8 @@ public OpenCGAResult loadTsvAnnotations(String studyStr, String variableSet } Query query = new Query(FileDBAdaptor.QueryParams.PATH.key(), path); - OpenCGAResult search = catalogManager.getFileManager().search(organizationId, study.getFqn(), query, FileManager.INCLUDE_FILE_URI_PATH, - token); + OpenCGAResult search = catalogManager.getFileManager().search(organizationId, study.getFqn(), query, + FileManager.INCLUDE_FILE_URI_PATH, token); if (search.getNumResults() == 0) { // File not found under the path. User must have provided a content so we can create the file. if (StringUtils.isEmpty(tsvParams.getContent())) { @@ -172,8 +173,8 @@ public OpenCGAResult loadTsvAnnotations(String studyStr, String variableSet return catalogManager.getJobManager().submit(organizationId, study.getFqn(), toolId, Enums.Priority.MEDIUM, jobParams, token); } - protected void checkUpdateAnnotations(Study study, T entry, ObjectMap parameters, QueryOptions options, - VariableSet.AnnotableDataModels annotableEntity, + protected void checkUpdateAnnotations(String organizationId, Study study, T entry, ObjectMap parameters, + QueryOptions options, VariableSet.AnnotableDataModels annotableEntity, AnnotationSetDBAdaptor dbAdaptor, String user) throws CatalogException { List variableSetList = study.getVariableSets(); @@ -350,7 +351,7 @@ protected void checkUpdateAnnotations(Study study, T entry } // Obtain all the variable sets from the study - OpenCGAResult studyDataResult = studyDBAdaptor.get(study.getUid(), + OpenCGAResult studyDataResult = getStudyDBAdaptor(organizationId).get(study.getUid(), new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); if (studyDataResult.getNumResults() == 0) { diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AuditManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AuditManager.java index b1237cb65ae..c875f2c0725 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AuditManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/AuditManager.java @@ -217,7 +217,7 @@ public OpenCGAResult search(String studyStr, Query query, QueryOpti query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -261,7 +261,7 @@ public OpenCGAResult groupBy(Query query, String fields, QueryOptions options, S } public OpenCGAResult groupBy(Query query, List fields, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); if (authorizationManager.isInstallationAdministrator(userId)) { return auditDBAdaptor.groupBy(query, fields, options); } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CatalogManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CatalogManager.java index 23d72820959..48d1253f4c7 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CatalogManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CatalogManager.java @@ -19,7 +19,6 @@ import org.apache.commons.lang3.StringUtils; import org.opencb.commons.datastore.core.ObjectMap; import org.opencb.commons.datastore.core.QueryOptions; -import org.opencb.opencga.catalog.auth.authentication.JwtManager; import org.opencb.opencga.catalog.auth.authorization.AuthorizationManager; import org.opencb.opencga.catalog.auth.authorization.CatalogAuthorizationManager; import org.opencb.opencga.catalog.db.DBAdaptorFactory; @@ -35,7 +34,6 @@ import org.opencb.opencga.catalog.utils.ParamUtils; import org.opencb.opencga.core.common.PasswordUtils; import org.opencb.opencga.core.common.UriUtils; -import org.opencb.opencga.core.config.Admin; import org.opencb.opencga.core.config.Configuration; import org.opencb.opencga.core.models.organizations.OrganizationCreateParams; import org.opencb.opencga.core.models.organizations.OrganizationUpdateParams; @@ -99,10 +97,7 @@ public String getCatalogDatabase() { } private void configureManagers(Configuration configuration) throws CatalogException { -// catalogClient = new CatalogDBClient(this); - //TODO: Check if catalog is empty - //TODO: Setup catalog if it's empty. - this.initializeAdmin(configuration); + initializeAdmin(configuration); authorizationManager = new CatalogAuthorizationManager(this.catalogDBAdaptorFactory, configuration); auditManager = new AuditManager(authorizationManager, this, this.catalogDBAdaptorFactory, configuration); migrationManager = new MigrationManager(this, catalogDBAdaptorFactory, configuration); @@ -128,31 +123,32 @@ private void configureManagers(Configuration configuration) throws CatalogExcept } private void initializeAdmin(Configuration configuration) throws CatalogDBException { - if (configuration.getAdmin() == null) { - configuration.setAdmin(new Admin()); - } - - String secretKey = ParamUtils.defaultString(configuration.getAdmin().getSecretKey(), - PasswordUtils.getStrongRandomPassword(JwtManager.SECRET_KEY_MIN_LENGTH)); - String algorithm = ParamUtils.defaultString(configuration.getAdmin().getAlgorithm(), "HS256"); - if (existsCatalogDB()) { - secretKey = catalogDBAdaptorFactory.getCatalogMetaDBAdaptor().readSecretKey(); - algorithm = catalogDBAdaptorFactory.getCatalogMetaDBAdaptor().readAlgorithm(); - } - configuration.getAdmin().setAlgorithm(algorithm); - configuration.getAdmin().setSecretKey(secretKey); - } - - public void updateJWTParameters(ObjectMap params, String token) throws CatalogException { - if (!OPENCGA.equals(userManager.getUserId(token))) { + // TODO: Each organization will have different configurations +// if (configuration.getAdmin() == null) { +// configuration.setAdmin(new Admin()); +// } +// +// String secretKey = ParamUtils.defaultString(configuration.getAdmin().getSecretKey(), +// PasswordUtils.getStrongRandomPassword(JwtManager.SECRET_KEY_MIN_LENGTH)); +// String algorithm = ParamUtils.defaultString(configuration.getAdmin().getAlgorithm(), "HS256"); +// if (existsCatalogDB()) { +// secretKey = catalogDBAdaptorFactory.getCatalogMetaDBAdaptor().readSecretKey(); +// algorithm = catalogDBAdaptorFactory.getCatalogMetaDBAdaptor().readAlgorithm(); +// } +// configuration.getAdmin().setAlgorithm(algorithm); +// configuration.getAdmin().setSecretKey(secretKey); + } + + public void updateJWTParameters(String organizationId, ObjectMap params, String token) throws CatalogException { + if (!OPENCGA.equals(userManager.getUserId(organizationId, token))) { throw new CatalogException("Operation only allowed for the OpenCGA admin"); } - if (params == null || params.size() == 0) { + if (params == null || params.isEmpty()) { return; } - catalogDBAdaptorFactory.getCatalogMetaDBAdaptor().updateJWTParameters(params); + catalogDBAdaptorFactory.getCatalogMetaDBAdaptor(organizationId).updateJWTParameters(params); } public boolean getDatabaseStatus() { @@ -191,7 +187,7 @@ public void installCatalogDB(String secretKey, String password, String email, bo // Check admin password ... try { userManager.loginAsAdmin(password); - logger.warn("A database called " + getCatalogDatabase() + " already exists"); + logger.warn("A database called {} already exists", getCatalogDatabase()); return; } catch (CatalogException e) { throw new CatalogException("A database called " + getCatalogDatabase() + " with a different admin" @@ -204,7 +200,7 @@ public void installCatalogDB(String secretKey, String password, String email, bo logger.info("Installing database {} in {}", getCatalogDatabase(), configuration.getCatalog().getDatabase().getHosts()); privateInstall(secretKey, password, email, test); String token = userManager.loginAsAdmin(password).getToken(); - installIndexes(token); + installIndexes(ADMIN_ORGANIZATION, token); } catch (Exception e) { try { clearCatalog(); @@ -238,26 +234,26 @@ private void privateInstall(String secretKey, String password, String email, boo User user = new User(OPENCGA, new Account().setType(Account.AccountType.ADMINISTRATOR).setExpirationDate("")) .setEmail(StringUtils.isEmpty(email) ? "opencga@admin.com" : email) .setOrganization(ADMIN_ORGANIZATION); - userManager.create(user, password, null); - String token = userManager.login(OPENCGA, password).getToken(); + userManager.create(ADMIN_ORGANIZATION, user, password, null); + String token = userManager.login(ADMIN_ORGANIZATION, OPENCGA, password).getToken(); // Add OPENCGA as owner of ADMIN_ORGANIZATION organizationManager.update(ADMIN_ORGANIZATION, new OrganizationUpdateParams().setOwner(OPENCGA), QueryOptions.empty(), token); - projectManager.create(organizationId, new ProjectCreateParams().setId(ADMIN_PROJECT).setDescription("Default project"), null, token); - studyManager.create(organizationId, ADMIN_PROJECT, new Study().setId(ADMIN_STUDY).setDescription("Default study"), QueryOptions.empty(), token); + projectManager.create(ADMIN_ORGANIZATION, new ProjectCreateParams().setId(ADMIN_PROJECT).setDescription("Default project"), null, + token); + studyManager.create(ADMIN_ORGANIZATION, ADMIN_PROJECT, new Study().setId(ADMIN_STUDY).setDescription("Default study"), + QueryOptions.empty(), token); // Skip old available migrations - migrationManager.skipPendingMigrations(token); + migrationManager.skipPendingMigrations(ADMIN_ORGANIZATION, token); } - public void installIndexes(String token) throws CatalogException { - if (!OPENCGA.equals(userManager.getUserId(token))) { + public void installIndexes(String organizationId, String token) throws CatalogException { + if (!OPENCGA.equals(userManager.getUserId(organizationId, token))) { throw new CatalogAuthorizationException("Only the admin can install new indexes"); } - for (String organizationId : catalogDBAdaptorFactory.getOrganizationIds()) { - catalogDBAdaptorFactory.createIndexes(organizationId); - } + catalogDBAdaptorFactory.createIndexes(organizationId); } public void deleteCatalogDB(String password) throws CatalogException { @@ -265,7 +261,8 @@ public void deleteCatalogDB(String password) throws CatalogException { userManager.loginAsAdmin(password); } catch (CatalogException e) { // Validate that the admin user exists. - OpenCGAResult result = catalogDBAdaptorFactory.getCatalogUserDBAdaptor().get(OPENCGA, QueryOptions.empty()); + OpenCGAResult result = catalogDBAdaptorFactory.getCatalogUserDBAdaptor(ADMIN_ORGANIZATION) + .get(OPENCGA, QueryOptions.empty()); if (result.getNumResults() == 1) { // Admin user exists so we have to fail. Password must be incorrect. throw e; diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManager.java index d2ca2bfb606..76de19b65ac 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManager.java @@ -133,7 +133,8 @@ Enums.Resource getEntity() { // } // // QueryOptions queryOptions = options != null ? new QueryOptions(options) : new QueryOptions(); -// OpenCGAResult analysisDataResult = getClinicalAnalysisDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, user); +// OpenCGAResult analysisDataResult = getClinicalAnalysisDBAdaptor(organizationId).get(studyUid, queryCopy, +// queryOptions, user); // if (analysisDataResult.getNumResults() == 0) { // analysisDataResult = getClinicalAnalysisDBAdaptor(organizationId).get(queryCopy, queryOptions); // if (analysisDataResult.getNumResults() == 0) { @@ -183,7 +184,8 @@ InternalGetDataResult internalGet(String organizationId, long // Ensure the field by which we are querying for will be kept in the results queryOptions = keepFieldInQueryOptions(queryOptions, idQueryParam.key()); - OpenCGAResult analysisDataResult = getClinicalAnalysisDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, user); + OpenCGAResult analysisDataResult = getClinicalAnalysisDBAdaptor(organizationId).get(studyUid, queryCopy, + queryOptions, user); if (ignoreException || analysisDataResult.getNumResults() == uniqueList.size()) { return keepOriginalOrder(uniqueList, clinicalStringFunction, analysisDataResult, ignoreException, false); @@ -201,12 +203,12 @@ InternalGetDataResult internalGet(String organizationId, long } @Override - public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) - throws CatalogException { + public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); fixQueryObject(organizationId, study, query, userId, sessionId); @@ -216,15 +218,15 @@ public DBIterator iterator(String organizationId, String study } @Override - public OpenCGAResult create(String organizationId, String studyStr, ClinicalAnalysis clinicalAnalysis, QueryOptions options, String token) - throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, ClinicalAnalysis clinicalAnalysis, + QueryOptions options, String token) throws CatalogException { return create(organizationId, studyStr, clinicalAnalysis, null, options, token); } public OpenCGAResult create(String organizationId, String studyStr, ClinicalAnalysis clinicalAnalysis, Boolean skipCreateDefaultInterpretation, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); ObjectMap auditParams = new ObjectMap() @@ -336,7 +338,8 @@ public OpenCGAResult create(String organizationId, String stud if (member.getSamples() != null && !member.getSamples().isEmpty()) { Query query = new Query(SampleDBAdaptor.QueryParams.UID.key(), member.getSamples().stream().map(Sample::getUid).collect(Collectors.toList())); - OpenCGAResult sampleResult = getSampleDBAdaptor(organizationId).get(study.getUid(), query, new QueryOptions(), userId); + OpenCGAResult sampleResult = getSampleDBAdaptor(organizationId).get(study.getUid(), query, + new QueryOptions(), userId); member.setSamples(sampleResult.getResults()); } } @@ -458,8 +461,9 @@ public OpenCGAResult create(String organizationId, String stud // Validate the proband has a disorder validateDisorder(clinicalAnalysis); } else { - OpenCGAResult individualOpenCGAResult = catalogManager.getIndividualManager().internalGet(organizationId, study.getUid(), - clinicalAnalysis.getProband().getId(), new Query(), new QueryOptions(), userId); + OpenCGAResult individualOpenCGAResult = catalogManager.getIndividualManager() + .internalGet(organizationId, study.getUid(), clinicalAnalysis.getProband().getId(), new Query(), new QueryOptions(), + userId); if (individualOpenCGAResult.getNumResults() == 0) { throw new CatalogException("Proband '" + clinicalAnalysis.getProband().getId() + "' not found."); } @@ -516,7 +520,7 @@ public OpenCGAResult create(String organizationId, String stud clinicalAnalysis.setModificationDate(ParamUtils.checkDateOrGetCurrentDate(clinicalAnalysis.getModificationDate(), ClinicalAnalysisDBAdaptor.QueryParams.MODIFICATION_DATE.key())); clinicalAnalysis.setDescription(ParamUtils.defaultString(clinicalAnalysis.getDescription(), "")); - clinicalAnalysis.setRelease(catalogManager.getStudyManager().getCurrentRelease(study)); + clinicalAnalysis.setRelease(catalogManager.getStudyManager().getCurrentRelease(organizationId, study)); clinicalAnalysis.setAttributes(ParamUtils.defaultObject(clinicalAnalysis.getAttributes(), Collections.emptyMap())); clinicalAnalysis.setSecondaryInterpretations(ParamUtils.defaultObject(clinicalAnalysis.getSecondaryInterpretations(), ArrayList::new)); @@ -557,15 +561,16 @@ public OpenCGAResult create(String organizationId, String stud } if (clinicalAnalysis.getInterpretation() != null) { - catalogManager.getInterpretationManager().validateNewInterpretation(organizationId, study, clinicalAnalysis.getInterpretation(), - clinicalAnalysis, userId); + catalogManager.getInterpretationManager().validateNewInterpretation(organizationId, study, + clinicalAnalysis.getInterpretation(), clinicalAnalysis, userId); clinicalAuditList.add(new ClinicalAudit(userId, ClinicalAudit.Action.CREATE_INTERPRETATION, "Create interpretation '" + clinicalAnalysis.getInterpretation().getId() + "'", TimeUtils.getTime())); } clinicalAuditList.add(new ClinicalAudit(userId, ClinicalAudit.Action.CREATE_CLINICAL_ANALYSIS, "Create ClinicalAnalysis '" + clinicalAnalysis.getId() + "'", TimeUtils.getTime())); - OpenCGAResult insert = getClinicalAnalysisDBAdaptor(organizationId).insert(study.getUid(), clinicalAnalysis, clinicalAuditList, options); + OpenCGAResult insert = getClinicalAnalysisDBAdaptor(organizationId).insert(study.getUid(), clinicalAnalysis, + clinicalAuditList, options); insert.addEvents(events); auditManager.auditCreate(userId, Enums.Resource.CLINICAL_ANALYSIS, clinicalAnalysis.getId(), clinicalAnalysis.getUuid(), @@ -573,8 +578,8 @@ public OpenCGAResult create(String organizationId, String stud if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated clinical analysis - OpenCGAResult queryResult = getClinicalAnalysisDBAdaptor(organizationId).get(study.getUid(), clinicalAnalysis.getId(), - QueryOptions.empty()); + OpenCGAResult queryResult = getClinicalAnalysisDBAdaptor(organizationId).get(study.getUid(), + clinicalAnalysis.getId(), QueryOptions.empty()); insert.setResults(queryResult.getResults()); } @@ -775,12 +780,14 @@ private void obtainFiles(String organizationId, Study study, ClinicalAnalysis cl Query query = new Query() .append(FileDBAdaptor.QueryParams.SAMPLE_IDS.key(), new ArrayList<>(sampleSet)) .append(FileDBAdaptor.QueryParams.BIOFORMAT.key(), Arrays.asList(File.Bioformat.ALIGNMENT, File.Bioformat.VARIANT)); - OpenCGAResult fileResults = getFileDBAdaptor(organizationId).get(study.getUid(), query, FileManager.INCLUDE_FILE_URI_PATH, userId); + OpenCGAResult fileResults = getFileDBAdaptor(organizationId).get(study.getUid(), query, FileManager.INCLUDE_FILE_URI_PATH, + userId); clinicalAnalysis.setFiles(fileResults.getResults()); } } - private void validateFiles(String organizationId, Study study, ClinicalAnalysis clinicalAnalysis, String userId) throws CatalogException { + private void validateFiles(String organizationId, Study study, ClinicalAnalysis clinicalAnalysis, String userId) + throws CatalogException { Map sampleMap = new HashMap<>(); if (clinicalAnalysis.getFamily() != null && clinicalAnalysis.getFamily().getMembers() != null) { for (Individual member : clinicalAnalysis.getFamily().getMembers()) { @@ -860,8 +867,8 @@ private Family getFullValidatedFamily(String organizationId, Family family, Stud // List of members relevant for the clinical analysis List selectedMembers = family.getMembers(); - OpenCGAResult familyDataResult = catalogManager.getFamilyManager().get(organizationId, study.getFqn(), family.getId(), new QueryOptions(), - token); + OpenCGAResult familyDataResult = catalogManager.getFamilyManager().get(organizationId, study.getFqn(), family.getId(), + new QueryOptions(), token); if (familyDataResult.getNumResults() == 0) { throw new CatalogException("Family " + family.getId() + " not found"); } @@ -894,8 +901,8 @@ private Family getFullValidatedFamily(String organizationId, Family family, Stud .append(IndividualDBAdaptor.QueryParams.UID.key(), finalFamily.getMembers().stream() .map(Individual::getUid).collect(Collectors.toList())) .append(IndividualDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - OpenCGAResult individuals = getIndividualDBAdaptor(organizationId).get(study.getUid(), query, QueryOptions.empty(), - catalogManager.getUserManager().getUserId(token)); + OpenCGAResult individuals = getIndividualDBAdaptor(organizationId).get(study.getUid(), query, + QueryOptions.empty(), catalogManager.getUserManager().getUserId(organizationId, token)); finalFamily.setMembers(individuals.getResults()); } } @@ -903,7 +910,8 @@ private Family getFullValidatedFamily(String organizationId, Family family, Stud return finalFamily; } - private Individual getFullValidatedMember(String organizationId, Individual member, Study study, String sessionId) throws CatalogException { + private Individual getFullValidatedMember(String organizationId, Individual member, Study study, String sessionId) + throws CatalogException { if (member == null) { return null; } @@ -918,8 +926,8 @@ private Individual getFullValidatedMember(String organizationId, Individual memb List samples = member.getSamples(); if (member.getUid() <= 0) { - OpenCGAResult individualDataResult = catalogManager.getIndividualManager().get(organizationId, study.getFqn(), member.getId(), - new QueryOptions(), sessionId); + OpenCGAResult individualDataResult = catalogManager.getIndividualManager().get(organizationId, study.getFqn(), + member.getId(), new QueryOptions(), sessionId); if (individualDataResult.getNumResults() == 0) { throw new CatalogException("Member " + member.getId() + " not found"); } @@ -962,15 +970,16 @@ private Individual getFullValidatedMember(String organizationId, Individual memb return finalMember; } - public OpenCGAResult update(String organizationId, String studyStr, Query query, + public OpenCGAResult update(String organizationId, String studyStr, Query query, ClinicalAnalysisUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, query, updateParams, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, Query query, ClinicalAnalysisUpdateParams updateParams, - boolean ignoreException, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, Query query, + ClinicalAnalysisUpdateParams updateParams, boolean ignoreException, QueryOptions options, + String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1007,7 +1016,8 @@ public OpenCGAResult update(String organizationId, String stud while (iterator.hasNext()) { ClinicalAnalysis clinicalAnalysis = iterator.next(); try { - OpenCGAResult queryResult = update(organizationId, study, clinicalAnalysis, updateParams, userId, options); + OpenCGAResult queryResult = update(organizationId, study, clinicalAnalysis, updateParams, userId, + options); result.append(queryResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.CLINICAL_ANALYSIS, clinicalAnalysis.getId(), @@ -1029,10 +1039,10 @@ public OpenCGAResult update(String organizationId, String stud return endResult(result, ignoreException); } - public OpenCGAResult update(String organizationId, String studyStr, String clinicalId, - ClinicalAnalysisUpdateParams updateParams, QueryOptions options, String token) + public OpenCGAResult update(String organizationId, String studyStr, String clinicalId, + ClinicalAnalysisUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1055,7 +1065,8 @@ public OpenCGAResult update(String organizationId, String stud OpenCGAResult result = OpenCGAResult.empty(); String clinicalUuid = ""; try { - OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), clinicalId, QueryOptions.empty(), userId); + OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), clinicalId, QueryOptions.empty(), + userId); if (internalResult.getNumResults() == 0) { throw new CatalogException("Clinical analysis '" + clinicalId + "' not found"); } @@ -1089,7 +1100,7 @@ public OpenCGAResult update(String organizationId, String stud * Update a Clinical Analysis from catalog. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param clinicalIds List of clinical analysis ids. Could be either the id or uuid. * @param updateParams Data model filled only with the parameters to be updated. * @param options QueryOptions object. @@ -1098,8 +1109,8 @@ public OpenCGAResult update(String organizationId, String stud * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String organizationId, String studyStr, List clinicalIds, - ClinicalAnalysisUpdateParams updateParams, QueryOptions options, String token) + public OpenCGAResult update(String organizationId, String studyStr, List clinicalIds, + ClinicalAnalysisUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, clinicalIds, updateParams, false, options, token); } @@ -1107,7 +1118,7 @@ public OpenCGAResult update(String organizationId, String stud public OpenCGAResult update(String organizationId, String studyStr, List clinicalIds, ClinicalAnalysisUpdateParams updateParams, boolean ignoreException, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1135,7 +1146,8 @@ public OpenCGAResult update(String organizationId, String stud String clinicalAnalysisId = id; String clinicalAnalysisUuid = ""; try { - OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), id, QueryOptions.empty(), userId); + OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), id, QueryOptions.empty(), + userId); if (internalResult.getNumResults() == 0) { throw new CatalogException("Clinical analysis '" + id + "' not found"); } @@ -1145,7 +1157,8 @@ public OpenCGAResult update(String organizationId, String stud clinicalAnalysisId = clinicalAnalysis.getId(); clinicalAnalysisUuid = clinicalAnalysis.getUuid(); - OpenCGAResult updateResult = update(organizationId, study, clinicalAnalysis, updateParams, userId, options); + OpenCGAResult updateResult = update(organizationId, study, clinicalAnalysis, updateParams, userId, + options); result.append(updateResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.CLINICAL_ANALYSIS, clinicalAnalysis.getId(), @@ -1501,12 +1514,12 @@ private boolean sortMembersFromFamily(ClinicalAnalysis clinicalAnalysis) { return true; } - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); fixQueryObject(organizationId, study, query, userId, token); @@ -1516,11 +1529,11 @@ public OpenCGAResult search(String organizationId, String stud } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1563,7 +1576,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S PanelDBAdaptor.QueryParams fieldFilter = catalogManager.getPanelManager().getFieldFilter(panelList); Query tmpQuery = new Query(fieldFilter.key(), panelList); - OpenCGAResult result = getPanelDBAdaptor(organizationId).get(study.getUid(), tmpQuery, PanelManager.INCLUDE_PANEL_IDS, user); + OpenCGAResult result = getPanelDBAdaptor(organizationId).get(study.getUid(), tmpQuery, PanelManager.INCLUDE_PANEL_IDS, + user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.PANELS_UID.key(), result.getResults().stream().map(Panel::getUid).collect(Collectors.toList())); @@ -1595,8 +1609,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S IndividualDBAdaptor.QueryParams fieldFilter = catalogManager.getIndividualManager().getFieldFilter(probandList); Query tmpQuery = new Query(fieldFilter.key(), probandList); - OpenCGAResult result = getIndividualDBAdaptor(organizationId).get(study.getUid(), tmpQuery, IndividualManager.INCLUDE_INDIVIDUAL_IDS, - user); + OpenCGAResult result = getIndividualDBAdaptor(organizationId).get(study.getUid(), tmpQuery, + IndividualManager.INCLUDE_INDIVIDUAL_IDS, user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.PROBAND_UID.key(), result.getResults().stream().map(Individual::getUid).collect(Collectors.toList())); @@ -1611,7 +1625,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S SampleDBAdaptor.QueryParams fieldFilter = catalogManager.getSampleManager().getFieldFilter(sampleList); Query tmpQuery = new Query(fieldFilter.key(), sampleList); - OpenCGAResult result = getSampleDBAdaptor(organizationId).get(study.getUid(), tmpQuery, SampleManager.INCLUDE_SAMPLE_IDS, user); + OpenCGAResult result = getSampleDBAdaptor(organizationId).get(study.getUid(), tmpQuery, + SampleManager.INCLUDE_SAMPLE_IDS, user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.PROBAND_SAMPLES_UID.key(), result.getResults().stream().map(Sample::getUid).collect(Collectors.toList())); @@ -1626,7 +1641,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S FamilyDBAdaptor.QueryParams fieldFilter = catalogManager.getFamilyManager().getFieldFilter(familyList); Query tmpQuery = new Query(fieldFilter.key(), familyList); - OpenCGAResult result = getFamilyDBAdaptor(organizationId).get(study.getUid(), tmpQuery, FamilyManager.INCLUDE_FAMILY_IDS, user); + OpenCGAResult result = getFamilyDBAdaptor(organizationId).get(study.getUid(), tmpQuery, + FamilyManager.INCLUDE_FAMILY_IDS, user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.FAMILY_UID.key(), result.getResults().stream().map(Family::getUid).collect(Collectors.toList())); @@ -1641,7 +1657,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S IndividualDBAdaptor.QueryParams fieldFilter = catalogManager.getIndividualManager().getFieldFilter(probandList); Query tmpQuery = new Query(fieldFilter.key(), probandList); - OpenCGAResult result = getIndividualDBAdaptor(organizationId).get(study.getUid(), tmpQuery, IndividualManager.INCLUDE_INDIVIDUAL_IDS, + OpenCGAResult result = getIndividualDBAdaptor(organizationId).get(study.getUid(), tmpQuery, + IndividualManager.INCLUDE_INDIVIDUAL_IDS, user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.FAMILY_MEMBERS_UID.key(), @@ -1657,7 +1674,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S SampleDBAdaptor.QueryParams fieldFilter = catalogManager.getSampleManager().getFieldFilter(sampleList); Query tmpQuery = new Query(fieldFilter.key(), sampleList); - OpenCGAResult result = getSampleDBAdaptor(organizationId).get(study.getUid(), tmpQuery, SampleManager.INCLUDE_SAMPLE_IDS, user); + OpenCGAResult result = getSampleDBAdaptor(organizationId).get(study.getUid(), tmpQuery, + SampleManager.INCLUDE_SAMPLE_IDS, user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.FAMILY_MEMBERS_SAMPLES_UID.key(), result.getResults().stream().map(Sample::getUid).collect(Collectors.toList())); @@ -1674,7 +1692,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S IndividualDBAdaptor.QueryParams fieldFilter = catalogManager.getIndividualManager().getFieldFilter(individualList); Query tmpQuery = new Query(fieldFilter.key(), individualList); - OpenCGAResult result = getIndividualDBAdaptor(organizationId).get(study.getUid(), tmpQuery, IndividualManager.INCLUDE_INDIVIDUAL_IDS, + OpenCGAResult result = getIndividualDBAdaptor(organizationId).get(study.getUid(), tmpQuery, + IndividualManager.INCLUDE_INDIVIDUAL_IDS, user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.INDIVIDUAL.key(), @@ -1690,7 +1709,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S SampleDBAdaptor.QueryParams fieldFilter = catalogManager.getSampleManager().getFieldFilter(sampleList); Query tmpQuery = new Query(fieldFilter.key(), sampleList); - OpenCGAResult result = getSampleDBAdaptor(organizationId).get(study.getUid(), tmpQuery, SampleManager.INCLUDE_SAMPLE_IDS, user); + OpenCGAResult result = getSampleDBAdaptor(organizationId).get(study.getUid(), tmpQuery, + SampleManager.INCLUDE_SAMPLE_IDS, user); if (result.getNumResults() > 0) { query.put(ClinicalAnalysisDBAdaptor.QueryParams.SAMPLE.key(), result.getResults().stream().map(Sample::getUid).collect(Collectors.toList())); @@ -1703,7 +1723,7 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S public OpenCGAResult count(String organizationId, String studyId, Query query, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1730,18 +1750,18 @@ public OpenCGAResult count(String organizationId, String study } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List clinicalAnalysisIds, QueryOptions options, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List clinicalAnalysisIds, QueryOptions options, + String token) throws CatalogException { return delete(organizationId, studyStr, clinicalAnalysisIds, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, List clinicalAnalysisIds, QueryOptions options, + public OpenCGAResult delete(String organizationId, String studyStr, List clinicalAnalysisIds, QueryOptions options, boolean ignoreException, String token) throws CatalogException { if (CollectionUtils.isEmpty(clinicalAnalysisIds)) { throw new CatalogException("Missing list of Clinical Analysis ids"); } - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1799,7 +1819,8 @@ public OpenCGAResult delete(String organizationId, String studyStr, List ClinicalAudit clinicalAudit = new ClinicalAudit(userId, ClinicalAudit.Action.DELETE_CLINICAL_ANALYSIS, "Delete Clinical Analysis '" + clinicalId + "'", TimeUtils.getTime()); - result.append(getClinicalAnalysisDBAdaptor(organizationId).delete(clinicalAnalysis, Collections.singletonList(clinicalAudit))); + result.append(getClinicalAnalysisDBAdaptor(organizationId).delete(clinicalAnalysis, + Collections.singletonList(clinicalAudit))); auditManager.auditDelete(operationId, userId, Enums.Resource.CLINICAL_ANALYSIS, clinicalAnalysis.getId(), clinicalAnalysis.getUuid(), study.getId(), study.getUuid(), auditParams, @@ -1842,18 +1863,19 @@ private void checkClinicalAnalysisCanBeDeleted(ClinicalAnalysis clinicalAnalysis } @Override - public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { return delete(organizationId, studyStr, query, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, boolean ignoreException, + public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, boolean ignoreException, String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); options = ParamUtils.defaultObject(options, QueryOptions::new); OpenCGAResult result = OpenCGAResult.empty(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); String operationUuid = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1875,7 +1897,8 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, fixQueryObject(organizationId, study, finalQuery, userId, token); finalQuery.append(ClinicalAnalysisDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - iterator = getClinicalAnalysisDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_CLINICAL_INTERPRETATION_IDS, userId); + iterator = getClinicalAnalysisDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, + INCLUDE_CLINICAL_INTERPRETATION_IDS, userId); // If the user is the owner or the admin, we won't check if he has permissions for every single entry checkPermissions = !authorizationManager.isOwnerOrAdmin(study.getUid(), userId); @@ -1901,7 +1924,8 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, ClinicalAudit clinicalAudit = new ClinicalAudit(userId, ClinicalAudit.Action.DELETE_CLINICAL_ANALYSIS, "Delete Clinical Analysis '" + clinicalAnalysis.getId() + "'", TimeUtils.getTime()); - result.append(getClinicalAnalysisDBAdaptor(organizationId).delete(clinicalAnalysis, Collections.singletonList(clinicalAudit))); + result.append(getClinicalAnalysisDBAdaptor(organizationId).delete(clinicalAnalysis, + Collections.singletonList(clinicalAudit))); auditManager.auditDelete(operationUuid, userId, Enums.Resource.CLINICAL_ANALYSIS, clinicalAnalysis.getId(), clinicalAnalysis.getUuid(), study.getId(), study.getUuid(), auditParams, @@ -1925,21 +1949,21 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) - throws CatalogException { + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, + String sessionId) throws CatalogException { return null; } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); if (fields == null || fields.size() == 0) { throw new CatalogException("Empty fields parameter."); } - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); fixQueryObject(organizationId, study, query, userId, sessionId); @@ -1953,15 +1977,16 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Q // ************************** ACLs ******************************** // public OpenCGAResult> getAcls( - String organizationId, String studyStr, List clinicalList, String member, boolean ignoreException, String token) + String organizationId, String studyStr, List clinicalList, String member, boolean ignoreException, String token) throws CatalogException { - return getAcls(organizationId, studyStr, clinicalList, StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), - ignoreException, token); + return getAcls(organizationId, studyStr, clinicalList, + StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), ignoreException, token); } - public OpenCGAResult> getAcls(String organizationId, String studyId, List clinicalList, List members, + public OpenCGAResult> getAcls(String organizationId, String studyId, + List clinicalList, List members, boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1977,8 +2002,8 @@ public OpenCGAResult> getAcls(String o Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), clinicalList, INCLUDE_CLINICAL_IDS, user, - ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), clinicalList, + INCLUDE_CLINICAL_IDS, user, ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -2041,9 +2066,9 @@ public OpenCGAResult> getAcls(String o } public OpenCGAResult> updateAcl( - String organizationId, String studyStr, List clinicalList, String memberIds, AclParams clinicalAclParams, + String organizationId, String studyStr, List clinicalList, String memberIds, AclParams clinicalAclParams, ParamUtils.AclAction action, boolean propagate, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, user); ObjectMap auditParams = new ObjectMap() @@ -2074,7 +2099,8 @@ public OpenCGAResult> updateAcl( checkPermissions(permissions, ClinicalAnalysisPermissions::valueOf); } - OpenCGAResult queryResult = internalGet(organizationId, study.getUid(), clinicalList, INCLUDE_CATALOG_DATA, user, false); + OpenCGAResult queryResult = internalGet(organizationId, study.getUid(), clinicalList, INCLUDE_CATALOG_DATA, + user, false); authorizationManager.checkCanAssignOrSeePermissions(study.getUid(), user); @@ -2200,9 +2226,9 @@ public OpenCGAResult> updateAcl( } } - public OpenCGAResult configureStudy(String organizationId, String studyStr, ClinicalAnalysisStudyConfiguration clinicalConfiguration, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult configureStudy(String organizationId, String studyStr, ClinicalAnalysisStudyConfiguration clinicalConfiguration, + String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CohortManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CohortManager.java index 781e264aed6..413d2a3e4a9 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CohortManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/CohortManager.java @@ -154,7 +154,7 @@ public OpenCGAResult create(String organizationId, String studyStr, Coho ParamUtils.checkObj(cohortParams, "CohortCreateParams"); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.WRITE_COHORTS); @@ -254,8 +254,9 @@ public OpenCGAResult create(String organizationId, String studyStr, Coho stopWatch.start(); for (Cohort cohort : cohorts) { try { - validateNewCohort(study, cohort); - OpenCGAResult tmpResult = getCohortDBAdaptor(organizationId).insert(study.getUid(), cohort, study.getVariableSets(), options); + validateNewCohort(organizationId, study, cohort); + OpenCGAResult tmpResult = getCohortDBAdaptor(organizationId).insert(study.getUid(), cohort, study.getVariableSets(), + options); insertResult.append(tmpResult); auditManager.audit(operationId, userId, Enums.Action.CREATE, Enums.Resource.COHORT, cohort.getId(), cohort.getUuid(), study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -288,7 +289,7 @@ public OpenCGAResult create(String organizationId, String studyStr, Coho public OpenCGAResult generate(String organizationId, String studyStr, Query sampleQuery, Cohort cohort, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.WRITE_COHORTS); @@ -303,7 +304,7 @@ public OpenCGAResult generate(String organizationId, String studyStr, Qu options = ParamUtils.defaultObject(options, QueryOptions::new); try { // Fix sample query object and search for samples - catalogManager.getSampleManager().fixQueryObject(study, sampleQuery, userId); + catalogManager.getSampleManager().fixQueryObject(organizationId, study, sampleQuery, userId); AnnotationUtils.fixQueryOptionAnnotation(options); sampleQuery.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); OpenCGAResult result = getSampleDBAdaptor(organizationId).get(study.getUid(), sampleQuery, options, userId); @@ -324,10 +325,11 @@ public OpenCGAResult generate(String organizationId, String studyStr, Qu } @Override - public OpenCGAResult create(String organizationId, String studyStr, Cohort cohort, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, Cohort cohort, QueryOptions options, String token) + throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.WRITE_COHORTS); @@ -358,9 +360,10 @@ public OpenCGAResult create(String organizationId, String studyStr, Coho } } - OpenCGAResult privateCreate(String organizationId, Study study, Cohort cohort, QueryOptions options, String userId) throws CatalogException { + OpenCGAResult privateCreate(String organizationId, Study study, Cohort cohort, QueryOptions options, String userId) + throws CatalogException { authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.WRITE_COHORTS); - validateNewCohort(study, cohort); + validateNewCohort(organizationId, study, cohort); OpenCGAResult insert = getCohortDBAdaptor(organizationId).insert(study.getUid(), cohort, study.getVariableSets(), options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { @@ -371,7 +374,7 @@ OpenCGAResult privateCreate(String organizationId, Study study, Cohort c return insert; } - void validateNewCohort(Study study, Cohort cohort) throws CatalogException { + void validateNewCohort(String organizationId, Study study, Cohort cohort) throws CatalogException { ParamUtils.checkObj(cohort, "Cohort"); ParamUtils.checkParameter(cohort.getId(), "id"); ParamUtils.checkObj(cohort.getSamples(), "Sample list"); @@ -384,7 +387,7 @@ void validateNewCohort(Study study, Cohort cohort) throws CatalogException { cohort.setDescription(ParamUtils.defaultString(cohort.getDescription(), "")); cohort.setAnnotationSets(ParamUtils.defaultObject(cohort.getAnnotationSets(), Collections::emptyList)); cohort.setAttributes(ParamUtils.defaultObject(cohort.getAttributes(), HashMap::new)); - cohort.setRelease(studyManager.getCurrentRelease(study)); + cohort.setRelease(studyManager.getCurrentRelease(organizationId, study)); cohort.setInternal(CohortInternal.init()); cohort.setSamples(ParamUtils.defaultObject(cohort.getSamples(), Collections::emptyList)); cohort.setStatus(ParamUtils.defaultObject(cohort.getStatus(), Status::new)); @@ -414,15 +417,16 @@ public Long getStudyId(String organizationId, long cohortId) throws CatalogExcep /** * Fetch all the samples from a cohort. * - * @param organizationId - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param organizationId Organization id. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param cohortStr Cohort id or name. * @param token Token of the user logged in. * @return a OpenCGAResult containing all the samples belonging to the cohort. * @throws CatalogException if there is any kind of error (permissions or invalid ids). */ - public OpenCGAResult getSamples(String organizationId, String studyStr, String cohortStr, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + public OpenCGAResult getSamples(String organizationId, String studyStr, String cohortStr, String token) + throws CatalogException { + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); OpenCGAResult cohortDataResult = internalGet(organizationId, study.getUid(), cohortStr, new QueryOptions(QueryOptions.INCLUDE, CohortDBAdaptor.QueryParams.SAMPLES.key()), userId); @@ -439,11 +443,12 @@ public OpenCGAResult getSamples(String organizationId, String studyStr, } @Override - public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException { + public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) + throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = studyManager.resolveId(organizationId, studyStr, userId); // Fix query if it contains any annotation @@ -457,11 +462,12 @@ public DBIterator iterator(String organizationId, String studyStr, Query } @Override - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -492,10 +498,11 @@ public OpenCGAResult search(String organizationId, String studyId, Query } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -551,7 +558,7 @@ private void fixQueryObject(String organizationId, Study study, Query query, Str public OpenCGAResult count(String organizationId, String studyId, Query query, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -581,17 +588,18 @@ public OpenCGAResult count(String organizationId, String studyId, Query } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List cohortIds, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List cohortIds, QueryOptions options, String token) + throws CatalogException { return delete(organizationId, studyStr, cohortIds, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, List cohortIds, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List cohortIds, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { if (cohortIds == null || ListUtils.isEmpty(cohortIds)) { throw new CatalogException("Missing list of cohort ids"); } - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -657,16 +665,17 @@ public OpenCGAResult delete(String organizationId, String studyStr, List } @Override - public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { return delete(organizationId, studyStr, query, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); OpenCGAResult result = OpenCGAResult.empty(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -728,8 +737,8 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, return endResult(result, ignoreException); } - public OpenCGAResult updateAnnotationSet(String organizationId, String studyStr, String cohortStr, - List annotationSetList, ParamUtils.BasicUpdateAction action, + public OpenCGAResult updateAnnotationSet(String organizationId, String studyStr, String cohortStr, + List annotationSetList, ParamUtils.BasicUpdateAction action, QueryOptions options, String token) throws CatalogException { CohortUpdateParams updateParams = new CohortUpdateParams().setAnnotationSets(annotationSetList); options = ParamUtils.defaultObject(options, QueryOptions::new); @@ -739,29 +748,32 @@ public OpenCGAResult updateAnnotationSet(String organizationId, String s return update(organizationId, studyStr, cohortStr, updateParams, true, options, token); } - public OpenCGAResult addAnnotationSet(String organizationId, String studyStr, String cohortStr, AnnotationSet annotationSet, QueryOptions options, - String token) throws CatalogException { + public OpenCGAResult addAnnotationSet(String organizationId, String studyStr, String cohortStr, AnnotationSet annotationSet, + QueryOptions options, String token) throws CatalogException { return addAnnotationSets(organizationId, studyStr, cohortStr, Collections.singletonList(annotationSet), options, token); } - public OpenCGAResult addAnnotationSets(String organizationId, String studyStr, String cohortStr, List annotationSetList, - QueryOptions options, String token) throws CatalogException { - return updateAnnotationSet(organizationId, studyStr, cohortStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, token); + public OpenCGAResult addAnnotationSets(String organizationId, String studyStr, String cohortStr, + List annotationSetList, QueryOptions options, String token) + throws CatalogException { + return updateAnnotationSet(organizationId, studyStr, cohortStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, + token); } - public OpenCGAResult removeAnnotationSet(String organizationId, String studyStr, String cohortStr, String annotationSetId, QueryOptions options, - String token) throws CatalogException { + public OpenCGAResult removeAnnotationSet(String organizationId, String studyStr, String cohortStr, String annotationSetId, + QueryOptions options, String token) throws CatalogException { return removeAnnotationSets(organizationId, studyStr, cohortStr, Collections.singletonList(annotationSetId), options, token); } - public OpenCGAResult removeAnnotationSets(String organizationId, String studyStr, String cohortStr, + public OpenCGAResult removeAnnotationSets(String organizationId, String studyStr, String cohortStr, List annotationSetIdList, QueryOptions options, String token) throws CatalogException { List annotationSetList = annotationSetIdList .stream() .map(id -> new AnnotationSet().setId(id)) .collect(Collectors.toList()); - return updateAnnotationSet(organizationId, studyStr, cohortStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, token); + return updateAnnotationSet(organizationId, studyStr, cohortStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, + token); } public OpenCGAResult updateAnnotations(String organizationId, String studyStr, String cohortStr, String annotationSetId, @@ -780,14 +792,14 @@ public OpenCGAResult updateAnnotations(String organizationId, String stu public OpenCGAResult removeAnnotations(String organizationId, String studyStr, String cohortStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, cohortStr, annotationSetId, new ObjectMap("remove", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.REMOVE, options, token); + return updateAnnotations(organizationId, studyStr, cohortStr, annotationSetId, + new ObjectMap("remove", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.REMOVE, options, token); } public OpenCGAResult resetAnnotations(String organizationId, String studyStr, String cohortStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, cohortStr, annotationSetId, new ObjectMap("reset", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.RESET, options, token); + return updateAnnotations(organizationId, studyStr, cohortStr, annotationSetId, + new ObjectMap("reset", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.RESET, options, token); } public OpenCGAResult update(String organizationId, String studyStr, String cohortId, CohortUpdateParams updateParams, @@ -797,7 +809,7 @@ public OpenCGAResult update(String organizationId, String studyStr, Stri public OpenCGAResult update(String organizationId, String studyStr, String cohortId, CohortUpdateParams updateParams, boolean allowModifyCohortAll, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -851,7 +863,7 @@ public OpenCGAResult update(String organizationId, String studyStr, Stri return result; } - public OpenCGAResult update(String organizationId, String studyStr, List cohortIds, CohortUpdateParams updateParams, + public OpenCGAResult update(String organizationId, String studyStr, List cohortIds, CohortUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, cohortIds, updateParams, false, false, options, token); } @@ -874,7 +886,7 @@ public OpenCGAResult update(String organizationId, String studyStr, List public OpenCGAResult update(String organizationId, String studyStr, List cohortIds, CohortUpdateParams updateParams, boolean allowModifyCohortAll, boolean ignoreException, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -913,7 +925,8 @@ public OpenCGAResult update(String organizationId, String studyStr, List cohortId = cohort.getId(); cohortUuid = cohort.getUuid(); - OpenCGAResult updateResult = update(organizationId, study, cohort, updateParams, allowModifyCohortAll, options, userId); + OpenCGAResult updateResult = update(organizationId, study, cohort, updateParams, allowModifyCohortAll, options, + userId); result.append(updateResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.COHORT, cohort.getId(), cohort.getUuid(), study.getId(), @@ -937,7 +950,7 @@ public OpenCGAResult update(String organizationId, String studyStr, List * Update a Cohort from catalog. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object. * @param updateParams Data model filled only with the parameters to be updated. * @param options QueryOptions object. @@ -946,7 +959,7 @@ public OpenCGAResult update(String organizationId, String studyStr, List * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String organizationId, String studyStr, Query query, CohortUpdateParams updateParams, + public OpenCGAResult update(String organizationId, String studyStr, Query query, CohortUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, query, updateParams, false, false, options, token); } @@ -956,7 +969,7 @@ public OpenCGAResult update(String organizationId, String studyStr, Quer throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -995,7 +1008,8 @@ public OpenCGAResult update(String organizationId, String studyStr, Quer while (iterator.hasNext()) { Cohort cohort = iterator.next(); try { - OpenCGAResult queryResult = update(organizationId, study, cohort, updateParams, allowModifyCohortAll, options, userId); + OpenCGAResult queryResult = update(organizationId, study, cohort, updateParams, allowModifyCohortAll, options, + userId); result.append(queryResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.COHORT, cohort.getId(), cohort.getUuid(), @@ -1015,7 +1029,7 @@ public OpenCGAResult update(String organizationId, String studyStr, Quer return endResult(result, ignoreException); } - private OpenCGAResult update(String organizationId, Study study, Cohort cohort, CohortUpdateParams updateParams, + private OpenCGAResult update(String organizationId, Study study, Cohort cohort, CohortUpdateParams updateParams, boolean allowModifyCohortAll, QueryOptions options, String userId) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); @@ -1108,8 +1122,10 @@ private OpenCGAResult update(String organizationId, Study study, Cohort } } - checkUpdateAnnotations(study, cohort, parameters, options, VariableSet.AnnotableDataModels.COHORT, getCohortDBAdaptor(organizationId), userId); - OpenCGAResult update = getCohortDBAdaptor(organizationId).update(cohort.getUid(), parameters, study.getVariableSets(), options); + checkUpdateAnnotations(organizationId, study, cohort, parameters, options, VariableSet.AnnotableDataModels.COHORT, + getCohortDBAdaptor(organizationId), userId); + OpenCGAResult update = getCohortDBAdaptor(organizationId).update(cohort.getUid(), parameters, study.getVariableSets(), + options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated cohort OpenCGAResult result = getCohortDBAdaptor(organizationId).get(study.getUid(), @@ -1120,13 +1136,13 @@ private OpenCGAResult update(String organizationId, Study study, Cohort } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); ParamUtils.checkObj(fields, "fields"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); // Fix query if it contains any annotation @@ -1141,9 +1157,9 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Q return ParamUtils.defaultObject(queryResult, OpenCGAResult::new); } - public void setStatus(String organizationId, String studyStr, String cohortId, String status, String message, String token) + public void setStatus(String organizationId, String studyStr, String cohortId, String status, String message, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); CohortStatus cohortStatus = new CohortStatus(status, message); @@ -1184,12 +1200,12 @@ public void setStatus(String organizationId, String studyStr, String cohortId, S } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) - throws CatalogException { + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); ParamUtils.checkObj(field, "field"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.VIEW_COHORTS); @@ -1212,14 +1228,14 @@ public OpenCGAResult> getAcls(String organizatio String member, boolean ignoreException, String token) throws CatalogException { return getAcls(organizationId, studyId, cohortList, - StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), + StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), ignoreException, token); } - public OpenCGAResult> getAcls(String organizationId, String studyId, List cohortList, - List members, boolean ignoreException, String token) + public OpenCGAResult> getAcls(String organizationId, String studyId, List cohortList, + List members, boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1235,7 +1251,8 @@ public OpenCGAResult> getAcls(String organizatio Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), cohortList, INCLUDE_COHORT_IDS, user, ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), cohortList, INCLUDE_COHORT_IDS, user, + ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -1300,7 +1317,7 @@ public OpenCGAResult> updateAcl(String organizat String memberList, AclParams aclParams, ParamUtils.AclAction action, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, StudyManager.INCLUDE_STUDY_UID); ObjectMap auditParams = new ObjectMap() @@ -1330,7 +1347,8 @@ public OpenCGAResult> updateAcl(String organizat checkPermissions(permissions, CohortPermissions::valueOf); } - List cohortList = internalGet(organizationId, study.getUid(), cohortStrList, INCLUDE_COHORT_IDS, userId, false).getResults(); + List cohortList = internalGet(organizationId, study.getUid(), cohortStrList, INCLUDE_COHORT_IDS, userId, false) + .getResults(); authorizationManager.checkCanAssignOrSeePermissions(study.getUid(), userId); @@ -1398,7 +1416,7 @@ public DataResult facet(String organizationId, String studyId, Query ParamUtils.defaultObject(query, Query::new); ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); // We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key()))); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FamilyManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FamilyManager.java index 72144abff63..10fa75d5005 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FamilyManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FamilyManager.java @@ -132,7 +132,7 @@ Enums.Resource getEntity() { } @Override - InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, + InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, QueryOptions options, String user, boolean ignoreException) throws CatalogException { if (ListUtils.isEmpty(entryList)) { throw new CatalogException("Missing family entries."); @@ -193,7 +193,8 @@ FamilyDBAdaptor.QueryParams getFieldFilter(List idList) throws CatalogEx return idQueryParam; } - private OpenCGAResult getFamily(String organizationId, long studyUid, String familyUuid, QueryOptions options) throws CatalogException { + private OpenCGAResult getFamily(String organizationId, long studyUid, String familyUuid, QueryOptions options) + throws CatalogException { Query query = new Query() .append(FamilyDBAdaptor.QueryParams.STUDY_UID.key(), studyUid) .append(FamilyDBAdaptor.QueryParams.UUID.key(), familyUuid); @@ -201,12 +202,13 @@ private OpenCGAResult getFamily(String organizationId, long studyUid, St } @Override - public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { + public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { ParamUtils.checkObj(token, "token"); query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); Query finalQuery = new Query(query); @@ -220,14 +222,15 @@ public DBIterator iterator(String organizationId, String studyStr, Query } @Override - public OpenCGAResult create(String organizationId, String studyStr, Family family, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, Family family, QueryOptions options, String token) + throws CatalogException { return create(organizationId, studyStr, family, null, options, token); } - public OpenCGAResult create(String organizationId, String studyStr, Family family, List members, QueryOptions options, String token) - throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, Family family, List members, QueryOptions options, + String token) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); ObjectMap auditParams = new ObjectMap() @@ -255,7 +258,7 @@ public OpenCGAResult create(String organizationId, String studyStr, Fami family.setAnnotationSets(ParamUtils.defaultObject(family.getAnnotationSets(), Collections.emptyList())); family.setStatus(ParamUtils.defaultObject(family.getStatus(), Status::new)); family.setQualityControl(ParamUtils.defaultObject(family.getQualityControl(), FamilyQualityControl::new)); - family.setRelease(catalogManager.getStudyManager().getCurrentRelease(study)); + family.setRelease(catalogManager.getStudyManager().getCurrentRelease(organizationId, study)); family.setVersion(1); family.setAttributes(ParamUtils.defaultObject(family.getAttributes(), Collections.emptyMap())); @@ -277,8 +280,8 @@ public OpenCGAResult create(String organizationId, String studyStr, Fami options = ParamUtils.defaultObject(options, QueryOptions::new); family.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.FAMILY)); - OpenCGAResult insert = getFamilyDBAdaptor(organizationId).insert(study.getUid(), family, existingMembers, study.getVariableSets(), - options); + OpenCGAResult insert = getFamilyDBAdaptor(organizationId).insert(study.getUid(), family, existingMembers, + study.getVariableSets(), options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated family OpenCGAResult queryResult = getFamily(organizationId, study.getUid(), family.getUuid(), options); @@ -296,12 +299,13 @@ public OpenCGAResult create(String organizationId, String studyStr, Fami } } - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); Query finalQuery = new Query(query); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -334,10 +338,11 @@ public OpenCGAResult search(String organizationId, String studyId, Query } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -379,7 +384,7 @@ private void fixQueryObject(String organizationId, Study study, Query query, Str // The individuals introduced could be either ids or names. As so, we should use the smart resolutor to do this. // We change the MEMBERS parameters for MEMBER_UID which is what the DBAdaptor understands if (query.containsKey(FamilyDBAdaptor.QueryParams.MEMBERS.key())) { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); List memberList = catalogManager.getIndividualManager().internalGet(organizationId, study.getUid(), query.getAsStringList(FamilyDBAdaptor.QueryParams.MEMBERS.key()), IndividualManager.INCLUDE_INDIVIDUAL_IDS, userId, @@ -423,7 +428,7 @@ public OpenCGAResult count(String organizationId, String studyId, Query query = ParamUtils.defaultObject(query, Query::new); Query finalQuery = new Query(query); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -453,13 +458,14 @@ public OpenCGAResult count(String organizationId, String studyId, Query } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List familyIds, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List familyIds, QueryOptions options, String token) + throws CatalogException { return delete(organizationId, studyStr, familyIds, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, List familyIds, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + public OpenCGAResult delete(String organizationId, String studyStr, List familyIds, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -532,7 +538,8 @@ private void checkCanBeDeleted(String organizationId, Study study, Family family Query query = new Query() .append(ClinicalAnalysisDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()) .append(ClinicalAnalysisDBAdaptor.QueryParams.FAMILY_UID.key(), family.getUid()); - OpenCGAResult result = getClinicalAnalysisDBAdaptor(organizationId).get(query, ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS); + OpenCGAResult result = getClinicalAnalysisDBAdaptor(organizationId).get(query, + ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS); if (result.getNumResults() > 0) { String clinicalIds = result.getResults().stream().map(ClinicalAnalysis::getId).collect(Collectors.joining(", ")); throw new CatalogException("Family {" + family.getId() + "} in use in Clinical Analyses: {" + clinicalIds + "}"); @@ -540,16 +547,17 @@ private void checkCanBeDeleted(String organizationId, Study study, Family family } @Override - public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { return delete(organizationId, studyStr, query, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); OpenCGAResult result = OpenCGAResult.empty(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -619,21 +627,21 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) throws - CatalogException { + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, + String sessionId) throws CatalogException { return null; } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); if (fields == null || fields.size() == 0) { throw new CatalogException("Empty fields parameter."); } - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = studyManager.resolveId(organizationId, studyStr, userId); Query finalQuery = new Query(query); @@ -651,7 +659,7 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Q return ParamUtils.defaultObject(queryResult, OpenCGAResult::new); } - public OpenCGAResult updateAnnotationSet(String organizationId, String studyStr, String familyStr, + public OpenCGAResult updateAnnotationSet(String organizationId, String studyStr, String familyStr, List annotationSetList, ParamUtils.BasicUpdateAction action, QueryOptions options, String token) throws CatalogException { FamilyUpdateParams updateParams = new FamilyUpdateParams().setAnnotationSets(annotationSetList); @@ -666,19 +674,23 @@ public OpenCGAResult addAnnotationSet(String organizationId, String stud return addAnnotationSets(organizationId, studyStr, familyStr, Collections.singletonList(annotationSet), options, token); } - public OpenCGAResult addAnnotationSets(String organizationId, String studyStr, String familyStr, List annotationSetList, - QueryOptions options, String token) throws CatalogException { - return updateAnnotationSet(organizationId, studyStr, familyStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, token); + public OpenCGAResult addAnnotationSets(String organizationId, String studyStr, String familyStr, + List annotationSetList, QueryOptions options, String token) + throws CatalogException { + return updateAnnotationSet(organizationId, studyStr, familyStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, + token); } - public OpenCGAResult setAnnotationSet(String organizationId, String studyStr, String familyStr, AnnotationSet annotationSet, + public OpenCGAResult setAnnotationSet(String organizationId, String studyStr, String familyStr, AnnotationSet annotationSet, QueryOptions options, String token) throws CatalogException { return setAnnotationSets(organizationId, studyStr, familyStr, Collections.singletonList(annotationSet), options, token); } - public OpenCGAResult setAnnotationSets(String organizationId, String studyStr, String familyStr, List annotationSetList, - QueryOptions options, String token) throws CatalogException { - return updateAnnotationSet(organizationId, studyStr, familyStr, annotationSetList, ParamUtils.BasicUpdateAction.SET, options, token); + public OpenCGAResult setAnnotationSets(String organizationId, String studyStr, String familyStr, + List annotationSetList, QueryOptions options, String token) + throws CatalogException { + return updateAnnotationSet(organizationId, studyStr, familyStr, annotationSetList, ParamUtils.BasicUpdateAction.SET, options, + token); } public OpenCGAResult removeAnnotationSet(String organizationId, String studyStr, String familyStr, String annotationSetId, @@ -686,13 +698,15 @@ public OpenCGAResult removeAnnotationSet(String organizationId, String s return removeAnnotationSets(organizationId, studyStr, familyStr, Collections.singletonList(annotationSetId), options, token); } - public OpenCGAResult removeAnnotationSets(String organizationId, String studyStr, String familyStr, List annotationSetIdList, - QueryOptions options, String token) throws CatalogException { + public OpenCGAResult removeAnnotationSets(String organizationId, String studyStr, String familyStr, + List annotationSetIdList, QueryOptions options, String token) + throws CatalogException { List annotationSetList = annotationSetIdList .stream() .map(id -> new AnnotationSet().setId(id)) .collect(Collectors.toList()); - return updateAnnotationSet(organizationId, studyStr, familyStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, token); + return updateAnnotationSet(organizationId, studyStr, familyStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, + token); } public OpenCGAResult updateAnnotations(String organizationId, String studyStr, String familyStr, String annotationSetId, @@ -711,24 +725,24 @@ public OpenCGAResult updateAnnotations(String organizationId, String stu public OpenCGAResult removeAnnotations(String organizationId, String studyStr, String familyStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, familyStr, annotationSetId, new ObjectMap("remove", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.REMOVE, options, token); + return updateAnnotations(organizationId, studyStr, familyStr, annotationSetId, + new ObjectMap("remove", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.REMOVE, options, token); } public OpenCGAResult resetAnnotations(String organizationId, String studyStr, String familyStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, familyStr, annotationSetId, new ObjectMap("reset", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.RESET, options, token); + return updateAnnotations(organizationId, studyStr, familyStr, annotationSetId, + new ObjectMap("reset", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.RESET, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, Query query, FamilyUpdateParams updateParams, QueryOptions options, - String token) throws CatalogException { + public OpenCGAResult update(String organizationId, String studyStr, Query query, FamilyUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, query, updateParams, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, Query query, FamilyUpdateParams updateParams, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, Query query, FamilyUpdateParams updateParams, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -792,9 +806,9 @@ public OpenCGAResult update(String organizationId, String studyStr, Quer return endResult(result, ignoreException); } - public OpenCGAResult update(String organizationId, String studyStr, String familyId, FamilyUpdateParams updateParams, QueryOptions options, - String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, String familyId, FamilyUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -851,7 +865,7 @@ public OpenCGAResult update(String organizationId, String studyStr, Stri * Update families from catalog. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param familyIds List of family ids. Could be either the id or uuid. * @param updateParams Data model filled only with the parameters to be updated. * @param options QueryOptions object. @@ -865,9 +879,9 @@ public OpenCGAResult update(String organizationId, String studyStr, List return update(organizationId, studyStr, familyIds, updateParams, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, List familyIds, FamilyUpdateParams updateParams, + public OpenCGAResult update(String organizationId, String studyStr, List familyIds, FamilyUpdateParams updateParams, boolean ignoreException, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -925,7 +939,7 @@ public OpenCGAResult update(String organizationId, String studyStr, List return endResult(result, ignoreException); } - private OpenCGAResult update(String organizationId, Study study, Family family, FamilyUpdateParams updateParams, + private OpenCGAResult update(String organizationId, Study study, Family family, FamilyUpdateParams updateParams, QueryOptions options, String userId) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); @@ -1027,10 +1041,11 @@ private OpenCGAResult update(String organizationId, Study study, Family } } - checkUpdateAnnotations(study, family, parameters, options, VariableSet.AnnotableDataModels.FAMILY, getFamilyDBAdaptor(organizationId), - userId); + checkUpdateAnnotations(organizationId, study, family, parameters, options, VariableSet.AnnotableDataModels.FAMILY, + getFamilyDBAdaptor(organizationId), userId); - OpenCGAResult update = getFamilyDBAdaptor(organizationId).update(family.getUid(), parameters, study.getVariableSets(), options); + OpenCGAResult update = getFamilyDBAdaptor(organizationId).update(family.getUid(), parameters, study.getVariableSets(), + options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated family OpenCGAResult result = getFamilyDBAdaptor(organizationId).get(study.getUid(), @@ -1040,15 +1055,15 @@ private OpenCGAResult update(String organizationId, Study study, Family return update; } - public Map> calculateFamilyGenotypes(String organizationId, String studyStr, String clinicalAnalysisId, + public Map> calculateFamilyGenotypes(String organizationId, String studyStr, String clinicalAnalysisId, String familyId, ClinicalProperty.ModeOfInheritance moi, String disorderId, Penetrance penetrance, String token) throws CatalogException { Pedigree pedigree; Disorder disorder = null; if (StringUtils.isNotEmpty(clinicalAnalysisId)) { - OpenCGAResult clinicalAnalysisDataResult = catalogManager.getClinicalAnalysisManager().get(organizationId, studyStr, - clinicalAnalysisId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList( + OpenCGAResult clinicalAnalysisDataResult = catalogManager.getClinicalAnalysisManager() + .get(organizationId, studyStr, clinicalAnalysisId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList( ClinicalAnalysisDBAdaptor.QueryParams.PROBAND.key(), ClinicalAnalysisDBAdaptor.QueryParams.FAMILY.key(), ClinicalAnalysisDBAdaptor.QueryParams.DISORDER.key())), token); if (clinicalAnalysisDataResult.getNumResults() == 0) { @@ -1104,18 +1119,18 @@ clinicalAnalysisId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList( } // ************************** ACLs ******************************** // - public OpenCGAResult> getAcls(String organizationId, String studyId, List familyList, - String member, boolean ignoreException, String token) + public OpenCGAResult> getAcls(String organizationId, String studyId, List familyList, + String member, boolean ignoreException, String token) throws CatalogException { return getAcls(organizationId, studyId, familyList, StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), ignoreException, token); } - public OpenCGAResult> getAcls(String organizationId, String studyId, List familyList, - List members, boolean ignoreException, String token) + public OpenCGAResult> getAcls(String organizationId, String studyId, List familyList, + List members, boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1131,7 +1146,8 @@ public OpenCGAResult> getAcls(String organizatio Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), familyList, INCLUDE_FAMILY_IDS, user, ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), familyList, INCLUDE_FAMILY_IDS, user, + ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -1194,9 +1210,9 @@ public OpenCGAResult> getAcls(String organizatio } public OpenCGAResult> updateAcl(String organizationId, String studyId, FamilyAclParams aclParams, - String memberList, ParamUtils.AclAction action, String token) + String memberList, ParamUtils.AclAction action, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); ObjectMap auditParams = new ObjectMap() @@ -1354,7 +1370,7 @@ public DataResult facet(String organizationId, String studyId, Query ParamUtils.defaultObject(query, Query::new); ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); // We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key()))); @@ -1403,8 +1419,8 @@ public DataResult facet(String organizationId, String studyId, Query * @return list of already existing members that will be associated to the family. * @throws CatalogException if there is any kind of error. */ - private List autoCompleteFamilyMembers(String organizationId, Study study, Family family, List members, String userId) - throws CatalogException { + private List autoCompleteFamilyMembers(String organizationId, Study study, Family family, List members, + String userId) throws CatalogException { if (family.getMembers() != null && !family.getMembers().isEmpty()) { List memberList = new ArrayList<>(); // Check the user can create new individuals @@ -1423,8 +1439,8 @@ private List autoCompleteFamilyMembers(String organizationId, Study // We remove any possible duplicate ArrayList deduplicatedMemberIds = new ArrayList<>(new HashSet<>(members)); - InternalGetDataResult individualDataResult = catalogManager.getIndividualManager().internalGet(organizationId, study.getUid(), - deduplicatedMemberIds, IndividualManager.INCLUDE_INDIVIDUAL_DISORDERS_PHENOTYPES, userId, false); + InternalGetDataResult individualDataResult = catalogManager.getIndividualManager().internalGet(organizationId, + study.getUid(), deduplicatedMemberIds, IndividualManager.INCLUDE_INDIVIDUAL_DISORDERS_PHENOTYPES, userId, false); return individualDataResult.getResults(); } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileManager.java index 14904ad6fd8..b179787df09 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileManager.java @@ -144,8 +144,8 @@ Enums.Resource getEntity() { } @Override - OpenCGAResult internalGet(String organizationId, long studyUid, String entry, @Nullable Query query, QueryOptions options, String user) - throws CatalogException { + OpenCGAResult internalGet(String organizationId, long studyUid, String entry, @Nullable Query query, QueryOptions options, + String user) throws CatalogException { // We make this comparison because in File, the absence of a fileName means the user is actually looking for the / directory if (StringUtils.isNotEmpty(entry) || entry == null) { ParamUtils.checkIsSingleID(entry); @@ -154,8 +154,8 @@ OpenCGAResult internalGet(String organizationId, long studyUid, String ent } @Override - InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, QueryOptions options, - String user, boolean ignoreException) throws CatalogException { + InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, + QueryOptions options, String user, boolean ignoreException) throws CatalogException { if (org.apache.commons.collections4.CollectionUtils.isEmpty(entryList)) { throw new CatalogException("Missing file entries."); } @@ -268,7 +268,8 @@ FileDBAdaptor.QueryParams getFieldFilter(List idList) throws CatalogExce return idQueryParam; } - private OpenCGAResult getFile(String organizationId, long studyUid, String fileUuid, QueryOptions options) throws CatalogException { + private OpenCGAResult getFile(String organizationId, long studyUid, String fileUuid, QueryOptions options) + throws CatalogException { Query query = new Query() .append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyUid) .append(FileDBAdaptor.QueryParams.UUID.key(), fileUuid); @@ -296,7 +297,7 @@ public Study getStudy(String organizationId, File file, String token) throws Cat throw new CatalogException("Missing study uid field in file"); } - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Query query = new Query(StudyDBAdaptor.QueryParams.UID.key(), file.getStudyUid()); OpenCGAResult studyDataResult = getStudyDBAdaptor(organizationId).get(query, QueryOptions.empty(), user); @@ -310,7 +311,7 @@ public Study getStudy(String organizationId, File file, String token) throws Cat public void matchUpVariantFiles(String organizationId, String studyStr, List transformedFiles, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); for (File transformedFile : transformedFiles) { @@ -445,7 +446,8 @@ public OpenCGAResult updateFileInternalVariantIndex(String organizationId, Fi public OpenCGAResult updateFileInternalVariantAnnotationIndex(String organizationId, File file, FileInternalVariantAnnotationIndex index, String token) throws CatalogException { - return updateFileInternalField(organizationId, file, index, FileDBAdaptor.QueryParams.INTERNAL_VARIANT_ANNOTATION_INDEX.key(), token); + return updateFileInternalField(organizationId, file, index, FileDBAdaptor.QueryParams.INTERNAL_VARIANT_ANNOTATION_INDEX.key(), + token); } public OpenCGAResult updateFileInternalVariantSecondaryAnnotationIndex(String organizationId, File file, @@ -469,7 +471,7 @@ private OpenCGAResult updateFileInternalField(String organizationId, File fil private OpenCGAResult updateFileInternalField(String organizationId, File file, Object value, List fieldKeys, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = getStudyDBAdaptor(organizationId).get(file.getStudyUid(), StudyManager.INCLUDE_STUDY_IDS).first(); ObjectMap auditParams = new ObjectMap() @@ -508,7 +510,7 @@ public OpenCGAResult getParents(String organizationId, long fileId, QueryO return fileDataResult; } - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); authorizationManager.checkFilePermission(fileDataResult.first().getStudyUid(), fileId, userId, FilePermissions.VIEW); return getParents(organizationId, fileDataResult.first().getStudyUid(), fileDataResult.first().getPath(), true, options); @@ -524,7 +526,7 @@ public OpenCGAResult createFolder(String organizationId, String studyStr, ParamUtils.checkPath(path, "folderPath"); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); if (path.startsWith("/")) { @@ -560,13 +562,14 @@ public OpenCGAResult createFolder(String organizationId, String studyStr, } @Override - public OpenCGAResult create(String organizationId, String studyStr, File entry, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, File entry, QueryOptions options, String token) + throws CatalogException { throw new NotImplementedException("Call to create passing parents and content variables"); } public OpenCGAResult create(String organizationId, String studyStr, FileCreateParams createParams, boolean parents, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -639,8 +642,8 @@ public OpenCGAResult create(String organizationId, String studyStr, FileCr if (createParams.getType().equals(File.Type.FILE)) { if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(createParams.getSampleIds())) { // Check samples - InternalGetDataResult sampleResult = catalogManager.getSampleManager().internalGet(organizationId, study.getUid(), - createParams.getSampleIds(), SampleManager.INCLUDE_SAMPLE_IDS, userId, true); + InternalGetDataResult sampleResult = catalogManager.getSampleManager().internalGet(organizationId, + study.getUid(), createParams.getSampleIds(), SampleManager.INCLUDE_SAMPLE_IDS, userId, true); if (!sampleResult.getMissing().isEmpty()) { throw new CatalogException("Could not find samples: '" + sampleResult.getMissing() .stream().map(InternalGetDataResult.Missing::getId).collect(Collectors.joining("', '")) + "'"); @@ -688,7 +691,8 @@ public OpenCGAResult create(String organizationId, String studyStr, FileCr } } // Register file in Catalog - OpenCGAResult result = register(organizationId, study, file, existingSamples, nonExistingSamples, parents, QueryOptions.empty(), token); + OpenCGAResult result = register(organizationId, study, file, existingSamples, nonExistingSamples, parents, + QueryOptions.empty(), token); result.setEvents(eventList); auditManager.auditCreate(userId, Enums.Resource.FILE, file.getId(), file.getUuid(), study.getId(), study.getUuid(), @@ -805,7 +809,7 @@ List validateNewFile(String organizationId, Study study, File file, boole boolean external = isExternal(study, file.getPath(), uri); file.setExternal(external); - file.setRelease(studyManager.getCurrentRelease(study)); + file.setRelease(studyManager.getCurrentRelease(organizationId, study)); validateNewAnnotationSets(study.getVariableSets(), file.getAnnotationSets()); @@ -818,7 +822,7 @@ List validateNewFile(String organizationId, Study study, File file, boole OpenCGAResult register(String organizationId, Study study, File file, List existingSamples, List nonExistingSamples, boolean parents, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); long studyId = study.getUid(); //Find parent. If parents == true, create folders. @@ -832,8 +836,8 @@ OpenCGAResult register(String organizationId, Study study, File file, List File parentFile = new File(File.Type.DIRECTORY, File.Format.NONE, File.Bioformat.NONE, parentPath, "", FileInternal.init(), 0, Collections.emptyList(), null, "", new FileQualityControl(), Collections.emptyMap(), Collections.emptyMap()); validateNewFile(organizationId, study, parentFile, false); - parentFileId = register(organizationId, study, parentFile, Collections.emptyList(), Collections.emptyList(), parents, options, token) - .first().getUid(); + parentFileId = register(organizationId, study, parentFile, Collections.emptyList(), Collections.emptyList(), parents, + options, token).first().getUid(); } else { throw new CatalogDBException("Directory not found " + parentPath); } @@ -871,15 +875,15 @@ private void validateNewSamples(String organizationId, Study study, File file, L return; } - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); - InternalGetDataResult sampleResult = catalogManager.getSampleManager().internalGet(organizationId, study.getUid(), file.getSampleIds(), - SampleManager.INCLUDE_SAMPLE_IDS, userId, true); + InternalGetDataResult sampleResult = catalogManager.getSampleManager().internalGet(organizationId, study.getUid(), + file.getSampleIds(), SampleManager.INCLUDE_SAMPLE_IDS, userId, true); existingSamples.addAll(sampleResult.getResults()); for (InternalGetDataResult.Missing missing : sampleResult.getMissing()) { Sample sample = new Sample().setId(missing.getId()); - catalogManager.getSampleManager().validateNewSample(study, sample, userId); + catalogManager.getSampleManager().validateNewSample(organizationId, study, sample, userId); nonExistingSamples.add(sample); } } @@ -919,15 +923,15 @@ public OpenCGAResult upload(String organizationId, String studyStr, InputS * @return a OpenCGAResult with the file uploaded. * @throws CatalogException if the user does not have permissions or any other unexpected issue happens. */ - public OpenCGAResult upload(String organizationId, String studyStr, InputStream fileInputStream, File file, boolean overwrite, boolean parents, - boolean calculateChecksum, String expectedChecksum, Long expectedSize, String token) + public OpenCGAResult upload(String organizationId, String studyStr, InputStream fileInputStream, File file, boolean overwrite, + boolean parents, boolean calculateChecksum, String expectedChecksum, Long expectedSize, String token) throws CatalogException { // Check basic parameters ParamUtils.checkObj(fileInputStream, "fileInputStream"); if (StringUtils.isNotEmpty(expectedChecksum)) { calculateChecksum = true; } - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); ObjectMap auditParams = new ObjectMap() @@ -1145,7 +1149,7 @@ public OpenCGAResult upload(String organizationId, String studyStr, InputS */ public OpenCGAResult moveAndRegister(String organizationId, String studyStr, Path fileSource, @Nullable Path folderDestiny, @Nullable String path, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -1241,7 +1245,8 @@ public OpenCGAResult moveAndRegister(String organizationId, String studySt OpenCGAResult result; if (external) { - result = link(organizationId, study.getFqn(), folderDestiny.resolve(fileName).toUri(), path, new ObjectMap("parents", true), token); + result = link(organizationId, study.getFqn(), folderDestiny.resolve(fileName).toUri(), path, new ObjectMap("parents", true), + token); } else { CheckPath checkPath = checkPathExists(organizationId, study.getUid(), filePath); if (checkPath != CheckPath.FREE_PATH) { @@ -1285,7 +1290,7 @@ public OpenCGAResult getTree(String organizationId, @Nullable String s options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1368,7 +1373,7 @@ public OpenCGAResult getTree(String organizationId, @Nullable String s public OpenCGAResult getFilesFromFolder(String organizationId, String studyStr, String folderStr, QueryOptions options, String token) throws CatalogException { ParamUtils.checkObj(folderStr, "folder"); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); File file = internalGet(organizationId, study.getUid(), folderStr, new QueryOptions(QueryOptions.INCLUDE, @@ -1384,10 +1389,11 @@ public OpenCGAResult getFilesFromFolder(String organizationId, String stud } @Override - public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException { + public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = studyManager.resolveId(organizationId, studyStr, userId); Query finalQuery = new Query(query); @@ -1401,12 +1407,13 @@ public DBIterator iterator(String organizationId, String studyStr, Query q } @Override - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); Query finalQuery = new Query(query); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -1436,10 +1443,11 @@ public OpenCGAResult search(String organizationId, String studyId, Query q } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -1518,7 +1526,7 @@ private void validateQueryPath(Query query, String key) { public OpenCGAResult count(String organizationId, String studyId, Query query, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -1549,13 +1557,14 @@ public OpenCGAResult count(String organizationId, String studyId, Query qu } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List fileIds, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List fileIds, QueryOptions options, String token) + throws CatalogException { return delete(organizationId, studyStr, fileIds, options, false, token); } public OpenCGAResult delete(String organizationId, String studyStr, List fileIds, ObjectMap params, boolean ignoreException, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -1625,14 +1634,14 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, return delete(organizationId, studyStr, query, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); params = ParamUtils.defaultObject(params, ObjectMap::new); OpenCGAResult dataResult = OpenCGAResult.empty(); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -1746,18 +1755,19 @@ private OpenCGAResult delete(String organizationId, Study study, File file, bool * @throws CatalogException If there is any of the following errors: Study not found, folderId does not exist or user does not have * permissions. */ - public OpenCGAResult syncUntrackedFiles(String organizationId, String studyId, String folderId, String token) throws CatalogException { + public OpenCGAResult syncUntrackedFiles(String organizationId, String studyId, String folderId, String token) + throws CatalogException { return syncUntrackedFiles(organizationId, studyId, folderId, uri -> true, "", token); } - public OpenCGAResult syncUntrackedFiles(String organizationId, String studyId, String folderId, Predicate filter, String token) - throws CatalogException { + public OpenCGAResult syncUntrackedFiles(String organizationId, String studyId, String folderId, Predicate filter, + String token) throws CatalogException { return syncUntrackedFiles(organizationId, studyId, folderId, filter, "", token); } - public OpenCGAResult syncUntrackedFiles(String organizationId, String studyId, String folderId, Predicate filter, String jobId, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult syncUntrackedFiles(String organizationId, String studyId, String folderId, Predicate filter, + String jobId, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); File folder = internalGet(organizationId, study.getUid(), folderId, INCLUDE_FILE_URI_PATH, userId).first(); @@ -1803,7 +1813,8 @@ public OpenCGAResult syncUntrackedFiles(String organizationId, String stud } try { - File registeredFile = internalGet(organizationId, study.getUid(), finalCatalogPath, INCLUDE_FILE_URI_PATH, userId).first(); + File registeredFile = internalGet(organizationId, study.getUid(), finalCatalogPath, INCLUDE_FILE_URI_PATH, userId) + .first(); if (!registeredFile.getUri().equals(fileUri)) { eventList.add(new Event(Event.Type.WARNING, registeredFile.getPath(), "The uri registered in Catalog '" + registeredFile.getUri().getPath() + "' for the path does not match the uri that would have been synced '" @@ -1826,8 +1837,9 @@ public OpenCGAResult syncUntrackedFiles(String organizationId, String stud return result; } - public OpenCGAResult unlink(String organizationId, @Nullable String studyId, String fileId, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult unlink(String organizationId, @Nullable String studyId, String fileId, String token) + throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1969,14 +1981,14 @@ public OpenCGAResult updateAnnotations(String organizationId, String study public OpenCGAResult removeAnnotations(String organizationId, String studyStr, String fileStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, fileStr, annotationSetId, new ObjectMap("remove", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.REMOVE, options, token); + return updateAnnotations(organizationId, studyStr, fileStr, annotationSetId, + new ObjectMap("remove", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.REMOVE, options, token); } public OpenCGAResult resetAnnotations(String organizationId, String studyStr, String fileStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, fileStr, annotationSetId, new ObjectMap("reset", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.RESET, options, token); + return updateAnnotations(organizationId, studyStr, fileStr, annotationSetId, + new ObjectMap("reset", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.RESET, options, token); } public OpenCGAResult update(String organizationId, String studyStr, Query query, FileUpdateParams updateParams, @@ -1984,9 +1996,9 @@ public OpenCGAResult update(String organizationId, String studyStr, Query return update(organizationId, studyStr, query, updateParams, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, Query query, FileUpdateParams updateParams, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, Query query, FileUpdateParams updateParams, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -2047,9 +2059,9 @@ public OpenCGAResult update(String organizationId, String studyStr, Query return endResult(result, ignoreException); } - public OpenCGAResult update(String organizationId, String studyStr, String fileId, FileUpdateParams updateParams, QueryOptions options, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, String fileId, FileUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -2104,7 +2116,7 @@ public OpenCGAResult update(String organizationId, String studyStr, String * Update a File from catalog. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param fileIds List of file ids. Could be either the id, path or uuid. * @param updateParams Data model filled only with the parameters to be updated. * @param options QueryOptions object. @@ -2113,14 +2125,14 @@ public OpenCGAResult update(String organizationId, String studyStr, String * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String organizationId, String studyStr, List fileIds, FileUpdateParams updateParams, QueryOptions options, - String token) throws CatalogException { + public OpenCGAResult update(String organizationId, String studyStr, List fileIds, FileUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, fileIds, updateParams, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, List fileIds, FileUpdateParams updateParams, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, List fileIds, FileUpdateParams updateParams, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -2216,7 +2228,8 @@ private OpenCGAResult update(String organizationId, Study study, File file if (StringUtils.isEmpty(relatedFile.getFile()) || relatedFile.getRelation() == null) { throw new CatalogException("Missing file or relation in relatedFiles list"); } - File relatedFileFile = internalGet(organizationId, study.getUid(), relatedFile.getFile(), null, INCLUDE_FILE_URI_PATH, userId).first(); + File relatedFileFile = internalGet(organizationId, study.getUid(), relatedFile.getFile(), null, INCLUDE_FILE_URI_PATH, + userId).first(); relatedFileList.add(new FileRelatedFile(relatedFileFile, relatedFile.getRelation())); } parameters.put(FileDBAdaptor.QueryParams.RELATED_FILES.key(), relatedFileList); @@ -2247,8 +2260,8 @@ private OpenCGAResult update(String organizationId, Study study, File file // We make a query to check both if the samples exists and if the user has permissions to see them if (updateParams != null && ListUtils.isNotEmpty(updateParams.getSampleIds())) { - catalogManager.getSampleManager().internalGet(organizationId, study.getUid(), updateParams.getSampleIds(), SampleManager.INCLUDE_SAMPLE_IDS, - userId, false); + catalogManager.getSampleManager().internalGet(organizationId, study.getUid(), updateParams.getSampleIds(), + SampleManager.INCLUDE_SAMPLE_IDS, userId, false); } //Name must be changed with "rename". @@ -2258,13 +2271,14 @@ private OpenCGAResult update(String organizationId, Study study, File file parameters.remove(FileDBAdaptor.QueryParams.NAME.key()); } - checkUpdateAnnotations(study, file, parameters, options, VariableSet.AnnotableDataModels.FILE, getFileDBAdaptor(organizationId), userId); + checkUpdateAnnotations(organizationId, study, file, parameters, options, VariableSet.AnnotableDataModels.FILE, + getFileDBAdaptor(organizationId), userId); OpenCGAResult update = getFileDBAdaptor(organizationId).update(file.getUid(), parameters, study.getVariableSets(), options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated file - OpenCGAResult result = getFileDBAdaptor(organizationId).get(study.getUid(), new Query(FileDBAdaptor.QueryParams.UID.key(), file.getUid()), - options, userId); + OpenCGAResult result = getFileDBAdaptor(organizationId).get(study.getUid(), new Query(FileDBAdaptor.QueryParams.UID.key(), + file.getUid()), options, userId); update.setResults(result.getResults()); } return update; @@ -2276,7 +2290,7 @@ public OpenCGAResult update(String organizationId, String studyStr, String ParamUtils.checkObj(parameters, "Parameters"); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); File file = internalGet(organizationId, study.getUid(), entryStr, QueryOptions.empty(), userId).first(); @@ -2311,7 +2325,8 @@ public OpenCGAResult update(String organizationId, String studyStr, String if (parameters.get(FileDBAdaptor.QueryParams.SAMPLE_IDS.key()) != null && ListUtils.isNotEmpty(parameters.getAsStringList(FileDBAdaptor.QueryParams.SAMPLE_IDS.key()))) { List sampleIds = parameters.getAsStringList(FileDBAdaptor.QueryParams.SAMPLE_IDS.key()); - catalogManager.getSampleManager().internalGet(organizationId, study.getUid(), sampleIds, SampleManager.INCLUDE_SAMPLE_IDS, userId, false); + catalogManager.getSampleManager().internalGet(organizationId, study.getUid(), sampleIds, SampleManager.INCLUDE_SAMPLE_IDS, + userId, false); } //Name must be changed with "rename". @@ -2343,7 +2358,8 @@ OpenCGAResult unsafeUpdate(String organizationId, Study study, File file, throw new CatalogException("Could not update: " + e.getMessage(), e); } - checkUpdateAnnotations(study, file, parameters, options, VariableSet.AnnotableDataModels.FILE, getFileDBAdaptor(organizationId), userId); + checkUpdateAnnotations(organizationId, study, file, parameters, options, VariableSet.AnnotableDataModels.FILE, + getFileDBAdaptor(organizationId), userId); getFileDBAdaptor(organizationId).update(file.getUid(), parameters, study.getVariableSets(), options); return getFileDBAdaptor(organizationId).get(file.getUid(), options); @@ -2353,7 +2369,7 @@ public OpenCGAResult link(String organizationId, String studyStr, FileLink throws CatalogException { // We make two attempts to link to ensure the behaviour remains even if it is being called at the same time link from different // threads - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -2398,13 +2414,14 @@ public OpenCGAResult link(String organizationId, String studyStr, URI uriO } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); ParamUtils.checkObj(field, "field"); ParamUtils.checkObj(sessionId, "sessionId"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = studyManager.resolveId(organizationId, studyStr, userId); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.VIEW_FILES); @@ -2422,7 +2439,8 @@ public OpenCGAResult rank(String organizationId, String studyStr, Query query, S } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); @@ -2430,7 +2448,7 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Q throw new CatalogException("Empty fields parameter."); } - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = studyManager.resolveId(organizationId, studyStr, userId); fixQueryObject(study, query, userId); @@ -2444,10 +2462,11 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Q return ParamUtils.defaultObject(queryResult, OpenCGAResult::new); } - OpenCGAResult rename(String organizationId, String studyStr, String fileStr, String newName, String sessionId) throws CatalogException { + OpenCGAResult rename(String organizationId, String studyStr, String fileStr, String newName, String sessionId) + throws CatalogException { ParamUtils.checkFileName(newName, "name"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = studyManager.resolveId(organizationId, studyStr, userId); File file = internalGet(organizationId, study.getUid(), fileStr, EXCLUDE_FILE_ATTRIBUTES, userId).first(); @@ -2510,7 +2529,7 @@ public OpenCGAResult grep(String organizationId, String studyId, St int numLines, String token) throws CatalogException { long startTime = System.currentTimeMillis(); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -2546,7 +2565,7 @@ public OpenCGAResult grep(String organizationId, String studyId, St } public OpenCGAResult image(String organizationId, String studyStr, String fileId, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); long startTime = System.currentTimeMillis(); @@ -2587,7 +2606,7 @@ public OpenCGAResult image(String organizationId, String studyStr, public OpenCGAResult head(String organizationId, String studyStr, String fileId, long offset, int lines, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); long startTime = System.currentTimeMillis(); @@ -2624,7 +2643,7 @@ public OpenCGAResult head(String organizationId, String studyStr, S public OpenCGAResult tail(String organizationId, String studyStr, String fileId, int lines, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); long startTime = System.currentTimeMillis(); @@ -2664,7 +2683,7 @@ public DataInputStream download(String organizationId, String studyStr, String f public DataInputStream download(String organizationId, String studyStr, String fileId, int start, int limit, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -2699,13 +2718,14 @@ public DataInputStream download(String organizationId, String studyStr, String f // ************************** ACLs ******************************** // public OpenCGAResult> getAcls(String organizationId, String studyId, List fileList, String member, boolean ignoreException, String token) throws CatalogException { - return getAcls(organizationId, studyId, fileList, StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), - ignoreException, token); + return getAcls(organizationId, studyId, fileList, + StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), ignoreException, token); } public OpenCGAResult> getAcls(String organizationId, String studyId, List fileList, - List members, boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + List members, boolean ignoreException, String token) + throws CatalogException { + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -2721,7 +2741,8 @@ public OpenCGAResult> getAcls(String organizationI Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), fileList, INCLUDE_FILE_IDS, user, ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), fileList, INCLUDE_FILE_IDS, user, + ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -2784,7 +2805,7 @@ public OpenCGAResult> getAcls(String organizationI public OpenCGAResult> updateAcl(String organizationId, String studyId, List fileStrList, String memberList, FileAclParams aclParams, ParamUtils.AclAction action, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); ObjectMap auditParams = new ObjectMap() @@ -2828,9 +2849,11 @@ public OpenCGAResult> updateAcl(String organizatio Query query = new Query(FileDBAdaptor.QueryParams.SAMPLE_IDS.key(), sampleDataResult.getResults().stream().map(Sample::getId).collect(Collectors.toList())); - extendedFileList = catalogManager.getFileManager().search(organizationId, studyId, query, EXCLUDE_FILE_ATTRIBUTES, token).getResults(); + extendedFileList = catalogManager.getFileManager().search(organizationId, studyId, query, EXCLUDE_FILE_ATTRIBUTES, token) + .getResults(); } else { - extendedFileList = internalGet(organizationId, study.getUid(), fileStrList, EXCLUDE_FILE_ATTRIBUTES, user, false).getResults(); + extendedFileList = internalGet(organizationId, study.getUid(), fileStrList, EXCLUDE_FILE_ATTRIBUTES, user, false) + .getResults(); } authorizationManager.checkCanAssignOrSeePermissions(study.getUid(), user); @@ -2899,7 +2922,7 @@ public OpenCGAResult> updateAcl(String organizatio public OpenCGAResult getParents(String organizationId, String studyStr, String path, boolean rootFirst, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); List paths = calculateAllPossiblePaths(path); @@ -3028,7 +3051,8 @@ private String getParentPath(String path) { * @return URI where the file should be placed * @throws CatalogException CatalogException */ - private URI getFileUri(String organizationId, long studyId, String path, boolean directory) throws CatalogException, URISyntaxException { + private URI getFileUri(String organizationId, long studyId, String path, boolean directory) + throws CatalogException, URISyntaxException { // Get the closest existing parent. If parents == true, may happen that the parent is not registered in catalog yet. File existingParent = getParents(organizationId, studyId, path, false, null).first(); @@ -3064,13 +3088,14 @@ private boolean isExternal(Study study, String catalogFilePath, URI fileUri) thr * @param organizationId Organization id. * @param studyStr Study. * @param fileId File or folder id. - * @param unlink Boolean indicating whether the operation only expects to remove the entry from the database or also remove the file - * from disk. + * @param unlink Boolean indicating whether the operation only expects to remove the entry from the database or also remove the + * file from disk. * @param token Token of the user for which DELETE permissions will be checked. * @throws CatalogException if any of the files cannot be deleted. */ - public void checkCanDeleteFile(String organizationId, String studyStr, String fileId, boolean unlink, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public void checkCanDeleteFile(String organizationId, String studyStr, String fileId, boolean unlink, String token) + throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); checkCanDeleteFile(organizationId, study, fileId, unlink, Arrays.asList(FileStatus.READY, FileStatus.TRASHED), userId); } @@ -3089,8 +3114,8 @@ public void checkCanDeleteFile(String organizationId, String studyStr, String fi * @param userId user for which DELETE permissions will be checked. * @throws CatalogException if any of the files cannot be deleted. */ - private void checkCanDeleteFile(String organizationId, Study study, String fileId, boolean unlink, List acceptedStatus, String userId) - throws CatalogException { + private void checkCanDeleteFile(String organizationId, Study study, String fileId, boolean unlink, List acceptedStatus, + String userId) throws CatalogException { QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(FileDBAdaptor.QueryParams.UID.key(), FileDBAdaptor.QueryParams.NAME.key(), FileDBAdaptor.QueryParams.TYPE.key(), FileDBAdaptor.QueryParams.RELATED_FILES.key(), @@ -3190,8 +3215,8 @@ private void checkCanDeleteFile(String organizationId, Study study, String fileI // Check the original files are not being indexed at the moment if (!indexFiles.isEmpty()) { Query query = new Query(FileDBAdaptor.QueryParams.UID.key(), new ArrayList<>(indexFiles)); - try (DBIterator iterator = getFileDBAdaptor(organizationId).iterator(query, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList( - FileDBAdaptor.QueryParams.INTERNAL.key(), FileDBAdaptor.QueryParams.UID.key())))) { + try (DBIterator iterator = getFileDBAdaptor(organizationId).iterator(query, new QueryOptions(QueryOptions.INCLUDE, + Arrays.asList(FileDBAdaptor.QueryParams.INTERNAL.key(), FileDBAdaptor.QueryParams.UID.key())))) { while (iterator.hasNext()) { File next = iterator.next(); String status = FileInternal.getVariantIndexStatusId(next.getInternal()); @@ -3243,12 +3268,12 @@ void checkValidStatusForDeletion(File file, List expectedStatus) throws throw new CatalogException("Cannot delete file: " + file.getName() + ". The status is " + file.getInternal().getStatus().getId()); } - public DataResult facet(String organizationId, String studyId, Query query, QueryOptions options, boolean defaultStats, + public DataResult facet(String organizationId, String studyId, Query query, QueryOptions options, boolean defaultStats, String token) throws CatalogException, IOException { ParamUtils.defaultObject(query, Query::new); ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); // We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key()))); @@ -3346,12 +3371,12 @@ private void createParents(String organizationId, Study study, String userId, UR // Create the folder in catalog File folder = new File(path.getFileName().toString(), File.Type.DIRECTORY, File.Format.PLAIN, File.Bioformat.NONE, completeURI, stringPath, null, TimeUtils.getTime(), TimeUtils.getTime(), "", false, 0, null, new FileExperiment(), - Collections.emptyList(), Collections.emptyList(), "", studyManager.getCurrentRelease(study), Collections.emptyList(), - Collections.emptyList(), new FileQualityControl(), null, new Status(), FileInternal.init(), null); + Collections.emptyList(), Collections.emptyList(), "", studyManager.getCurrentRelease(organizationId, study), + Collections.emptyList(), Collections.emptyList(), new FileQualityControl(), null, new Status(), FileInternal.init(), null); folder.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.FILE)); checkHooks(folder, study.getFqn(), HookConfiguration.Stage.CREATE); - getFileDBAdaptor(organizationId).insert(study.getUid(), folder, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), - new QueryOptions()); + getFileDBAdaptor(organizationId).insert(study.getUid(), folder, Collections.emptyList(), Collections.emptyList(), + Collections.emptyList(), new QueryOptions()); OpenCGAResult queryResult = getFile(organizationId, study.getUid(), folder.getUuid(), QueryOptions.empty()); // Propagate ACLs if (allFileAcls != null && allFileAcls.getNumResults() > 0) { @@ -3360,7 +3385,7 @@ private void createParents(String organizationId, Study study, String userId, UR } } - private OpenCGAResult privateLink(String organizationId, Study study, FileLinkParams params, boolean parents, String token) + private OpenCGAResult privateLink(String organizationId, Study study, FileLinkParams params, boolean parents, String token) throws CatalogException { ParamUtils.checkObj(params, "FileLinkParams"); ParamUtils.checkParameter(params.getUri(), "uri"); @@ -3388,7 +3413,7 @@ private OpenCGAResult privateLink(String organizationId, Study study, File throw new CatalogException(e); } - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.WRITE_FILES); params.setPath(ParamUtils.defaultString(params.getPath(), "")); @@ -3467,7 +3492,8 @@ private OpenCGAResult privateLink(String organizationId, Study study, File if (relatedFilesParams != null) { relatedFiles = new ArrayList<>(relatedFilesParams.size()); for (SmallRelatedFileParams relatedFileParams : relatedFilesParams) { - File tmpFile = internalGet(organizationId, study.getUid(), relatedFileParams.getFile(), INCLUDE_FILE_URI_PATH, userId).first(); + File tmpFile = internalGet(organizationId, study.getUid(), relatedFileParams.getFile(), INCLUDE_FILE_URI_PATH, userId) + .first(); relatedFiles.add(new FileRelatedFile(tmpFile, relatedFileParams.getRelation())); } } else { @@ -3553,8 +3579,8 @@ public FileVisitResult preVisitDirectory(URI dir, BasicFileAttributes attrs) thr File folder = new File(Paths.get(dir).getFileName().toString(), File.Type.DIRECTORY, File.Format.PLAIN, File.Bioformat.NONE, dir, destinyPath, null, creationDate, modificationDate, params.getDescription(), true, 0, new Software(), new FileExperiment(), - Collections.emptyList(), relatedFiles, "", studyManager.getCurrentRelease(study), Collections.emptyList(), - Collections.emptyList(), new FileQualityControl(), Collections.emptyMap(), + Collections.emptyList(), relatedFiles, "", studyManager.getCurrentRelease(organizationId, study), + Collections.emptyList(), Collections.emptyList(), new FileQualityControl(), Collections.emptyMap(), params.getStatus() != null ? params.getStatus().toStatus() : new Status(), FileInternal.init(), Collections.emptyMap()); folder.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.FILE)); @@ -3612,8 +3638,8 @@ public FileVisitResult visitFile(URI fileUri, BasicFileAttributes attrs) throws File subfile = new File(Paths.get(fileUri).getFileName().toString(), File.Type.FILE, File.Format.UNKNOWN, File.Bioformat.NONE, fileUri, destinyPath, null, creationDate, modificationDate, params.getDescription(), true, size, new Software(), new FileExperiment(), - Collections.emptyList(), relatedFiles, "", studyManager.getCurrentRelease(study), Collections.emptyList(), - Collections.emptyList(), new FileQualityControl(), Collections.emptyMap(), + Collections.emptyList(), relatedFiles, "", studyManager.getCurrentRelease(organizationId, study), + Collections.emptyList(), Collections.emptyList(), new FileQualityControl(), Collections.emptyMap(), params.getStatus() != null ? params.getStatus().toStatus() : new Status(), internal, new HashMap<>()); subfile.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.FILE)); @@ -3643,7 +3669,8 @@ public FileVisitResult visitFile(URI fileUri, BasicFileAttributes attrs) throws FileDBAdaptor.QueryParams.TYPE.key(), FileDBAdaptor.QueryParams.SAMPLE_IDS.key(), FileDBAdaptor.QueryParams.INTERNAL_MISSING_SAMPLES.key())); - OpenCGAResult vFileResult = getFileDBAdaptor(organizationId).get(study.getUid(), tmpQuery, tmpOptions, userId); + OpenCGAResult vFileResult = getFileDBAdaptor(organizationId).get(study.getUid(), tmpQuery, tmpOptions, + userId); if (vFileResult.getNumResults() == 1) { if (!vFileResult.first().getType().equals(File.Type.VIRTUAL)) { @@ -3675,11 +3702,11 @@ public FileVisitResult visitFile(URI fileUri, BasicFileAttributes attrs) throws } subfile.setSampleIds(null); - getFileDBAdaptor(organizationId).insertWithVirtualFile(study.getUid(), subfile, virtualFile, existingSamples, nonExistingSamples, - Collections.emptyList(), new QueryOptions()); + getFileDBAdaptor(organizationId).insertWithVirtualFile(study.getUid(), subfile, virtualFile, existingSamples, + nonExistingSamples, Collections.emptyList(), new QueryOptions()); } else { - getFileDBAdaptor(organizationId).insert(study.getUid(), subfile, existingSamples, nonExistingSamples, Collections.emptyList(), - new QueryOptions()); + getFileDBAdaptor(organizationId).insert(study.getUid(), subfile, existingSamples, nonExistingSamples, + Collections.emptyList(), new QueryOptions()); } subfile = getFile(organizationId, study.getUid(), subfile.getUuid(), QueryOptions.empty()).first(); @@ -3737,9 +3764,9 @@ public FileVisitResult postVisitDirectory(URI dir, IOException exc) throws IOExc return getFileDBAdaptor(organizationId).get(query, queryOptions); } - OpenCGAResult registerFile(String organizationId, Study study, String filePath, URI fileUri, String jobId, String token) + OpenCGAResult registerFile(String organizationId, Study study, String filePath, URI fileUri, String jobId, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); IOManager ioManager; try { ioManager = ioManagerFactory.get(fileUri); @@ -3761,8 +3788,9 @@ OpenCGAResult registerFile(String organizationId, Study study, String file File subfile = new File(Paths.get(filePath).getFileName().toString(), type, File.Format.UNKNOWN, File.Bioformat.NONE, fileUri, filePath, "", TimeUtils.getTime(), TimeUtils.getTime(), "", isExternal(study, filePath, fileUri), size, new Software(), new FileExperiment(), Collections.emptyList(), - Collections.emptyList(), jobId, studyManager.getCurrentRelease(study), Collections.emptyList(), Collections.emptyList(), - new FileQualityControl(), Collections.emptyMap(), new Status(), FileInternal.init(), Collections.emptyMap()); + Collections.emptyList(), jobId, studyManager.getCurrentRelease(organizationId, study), Collections.emptyList(), + Collections.emptyList(), new FileQualityControl(), Collections.emptyMap(), new Status(), FileInternal.init(), + Collections.emptyMap()); subfile.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.FILE)); checkHooks(subfile, study.getFqn(), HookConfiguration.Stage.CREATE); @@ -3772,7 +3800,8 @@ OpenCGAResult registerFile(String organizationId, Study study, String file List nonExistingSamples = new LinkedList<>(); validateNewSamples(organizationId, study, subfile, existingSamples, nonExistingSamples, token); - getFileDBAdaptor(organizationId).insert(study.getUid(), subfile, existingSamples, nonExistingSamples, Collections.emptyList(), new QueryOptions()); + getFileDBAdaptor(organizationId).insert(study.getUid(), subfile, existingSamples, nonExistingSamples, Collections.emptyList(), + new QueryOptions()); OpenCGAResult result = getFile(organizationId, study.getUid(), subfile.getUuid(), QueryOptions.empty()); subfile = result.first(); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileUtils.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileUtils.java index 1cea9e668a5..30fc6472f42 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileUtils.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/FileUtils.java @@ -67,6 +67,7 @@ public FileUtils(CatalogManager catalogManager) { * For READY files with a non existing file, set status to MISSING. "Lost file" * For MISSING files who recover the file, set status to READY. "Found file" * + * @param organizationId Organization id. * @param studyStr Study corresponding to the file to be checked. * @param file File to check * @param calculateChecksum Calculate checksum for "found files" @@ -74,7 +75,8 @@ public FileUtils(CatalogManager catalogManager) { * @return If there is any change, returns the modified file. Else, return the same file. * @throws CatalogException CatalogException */ - public File checkFile(String studyStr, File file, boolean calculateChecksum, String sessionId) throws CatalogException { + public File checkFile(String organizationId, String studyStr, File file, boolean calculateChecksum, String sessionId) + throws CatalogException { if (!file.getType().equals(File.Type.FILE)) { return file; } @@ -98,15 +100,17 @@ public File checkFile(String studyStr, File file, boolean calculateChecksum, Str ObjectMap params = new ObjectMap(FileDBAdaptor.UpdateParams.INTERNAL_STATUS.key(), new FileStatus(FileStatus.MISSING)); catalogManager.getFileManager().update(organizationId, studyStr, file.getPath(), params, null, sessionId); - modifiedFile = catalogManager.getFileManager().get(organizationId, studyStr, file.getPath(), null, sessionId).first(); + modifiedFile = catalogManager.getFileManager().get(organizationId, studyStr, file.getPath(), null, sessionId) + .first(); } } else if (file.getInternal().getStatus().getId().equals(FileStatus.MISSING)) { logger.info("File { path:\"" + file.getPath() + "\" } recover tracking from file " + fileUri); logger.info("Set status to " + FileStatus.READY); - ObjectMap params = getModifiedFileAttributes(file, fileUri, calculateChecksum); + ObjectMap params = getModifiedFileAttributes(organizationId, file, fileUri, calculateChecksum); params.put(FileDBAdaptor.UpdateParams.INTERNAL_STATUS.key(), new FileStatus(FileStatus.READY)); - catalogManager.getFileManager().update(organizationId, studyStr, file.getPath(), params, QueryOptions.empty(), sessionId); + catalogManager.getFileManager().update(organizationId, studyStr, file.getPath(), params, QueryOptions.empty(), + sessionId); modifiedFile = catalogManager.getFileManager().get(organizationId, studyStr, file.getPath(), null, sessionId).first(); } break; @@ -134,15 +138,17 @@ public File checkFile(String studyStr, File file, boolean calculateChecksum, Str * checksum * uri * + * @param organizationId Organization id. * @param file file * @param fileUri If null, calls to getFileUri() *

- * TODO: Lazy checksum: Only calculate checksum if the size has changed. + * TODO: Lazy checksum: Only calculate checksum if the size has changed. * @param calculateChecksum Calculate checksum to check if have changed * @return ObjectMap ObjectMap * @throws CatalogException CatalogException */ - public ObjectMap getModifiedFileAttributes(File file, URI fileUri, boolean calculateChecksum) throws CatalogException { + public ObjectMap getModifiedFileAttributes(String organizationId, File file, URI fileUri, boolean calculateChecksum) + throws CatalogException { if (fileUri == null) { fileUri = catalogManager.getFileManager().getUri(organizationId, file); } @@ -154,7 +160,7 @@ public ObjectMap getModifiedFileAttributes(File file, URI fileUri, boolean calcu throw CatalogIOException.ioManagerException(fileUri, e); } } - return getModifiedFileAttributes(file, checksum, fileUri, null); + return getModifiedFileAttributes(organizationId, file, checksum, fileUri, null); } /** @@ -165,7 +171,8 @@ public ObjectMap getModifiedFileAttributes(File file, URI fileUri, boolean calcu * * @throws CatalogException CatalogException */ - private ObjectMap getModifiedFileAttributes(File file, String checksum, URI fileUri, ObjectMap parameters) throws CatalogException { + private ObjectMap getModifiedFileAttributes(String organizationId, File file, String checksum, URI fileUri, ObjectMap parameters) + throws CatalogException { parameters = ParamUtils.defaultObject(parameters, ObjectMap::new); if (fileUri == null) { fileUri = catalogManager.getFileManager().getUri(organizationId, file); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/IndividualManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/IndividualManager.java index 17c266a6a9c..ab086b871c3 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/IndividualManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/IndividualManager.java @@ -127,7 +127,8 @@ Enums.Resource getEntity() { // queryCopy.put(IndividualDBAdaptor.QueryParams.ID.key(), entry); // } // QueryOptions queryOptions = options != null ? new QueryOptions(options) : new QueryOptions(); -// OpenCGAResult individualDataResult = getIndividualDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, user); +// OpenCGAResult individualDataResult = getIndividualDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, +// user); // if (individualDataResult.getNumResults() == 0) { // individualDataResult = getIndividualDBAdaptor(organizationId).get(queryCopy, queryOptions); // if (individualDataResult.getNumResults() == 0) { @@ -143,8 +144,8 @@ Enums.Resource getEntity() { // } @Override - InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, QueryOptions options, - String user, boolean ignoreException) throws CatalogException { + InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, + QueryOptions options, String user, boolean ignoreException) throws CatalogException { if (ListUtils.isEmpty(entryList)) { throw new CatalogException("Missing individual entries."); } @@ -166,7 +167,8 @@ InternalGetDataResult internalGet(String organizationId, long studyU // Ensure the field by which we are querying for will be kept in the results queryOptions = keepFieldInQueryOptions(queryOptions, idQueryParam.key()); - OpenCGAResult individualDataResult = getIndividualDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, user); + OpenCGAResult individualDataResult = getIndividualDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, + user); Function individualStringFunction = Individual::getId; if (idQueryParam.equals(IndividualDBAdaptor.QueryParams.UUID)) { @@ -236,7 +238,7 @@ void validateNewIndividual(String organizationId, Study study, Individual indivi individual.setModificationDate(ParamUtils.checkDateOrGetCurrentDate(individual.getModificationDate(), IndividualDBAdaptor.QueryParams.MODIFICATION_DATE.key())); individual.setModificationDate(TimeUtils.getTime()); - individual.setRelease(studyManager.getCurrentRelease(study)); + individual.setRelease(studyManager.getCurrentRelease(organizationId, study)); individual.setVersion(1); individual.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.INDIVIDUAL)); @@ -259,13 +261,13 @@ void validateNewIndividual(String organizationId, Study study, Individual indivi if (linkParents) { if (individual.getFather() != null && StringUtils.isNotEmpty(individual.getFather().getId())) { - OpenCGAResult fatherResult = internalGet(organizationId, study.getUid(), individual.getFather().getId(), INCLUDE_INDIVIDUAL_IDS, - userId); + OpenCGAResult fatherResult = internalGet(organizationId, study.getUid(), individual.getFather().getId(), + INCLUDE_INDIVIDUAL_IDS, userId); individual.setFather(fatherResult.first()); } if (individual.getMother() != null && StringUtils.isNotEmpty(individual.getMother().getId())) { - OpenCGAResult motherResult = internalGet(organizationId, study.getUid(), individual.getMother().getId(), INCLUDE_INDIVIDUAL_IDS, - userId); + OpenCGAResult motherResult = internalGet(organizationId, study.getUid(), individual.getMother().getId(), + INCLUDE_INDIVIDUAL_IDS, userId); individual.setMother(motherResult.first()); } } @@ -281,7 +283,7 @@ private void validateSamples(String organizationId, Study study, Individual indi // Validate the samples can be created and are valid for (Sample sample : individual.getSamples()) { - catalogManager.getSampleManager().validateNewSample(study, sample, userId); + catalogManager.getSampleManager().validateNewSample(organizationId, study, sample, userId); sampleList.add(sample); } } @@ -305,8 +307,8 @@ private void validateSamples(String organizationId, Study study, Individual indi } @Override - public OpenCGAResult create(String organizationId, String studyStr, Individual individual, QueryOptions options, String token) - throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, Individual individual, QueryOptions options, + String token) throws CatalogException { return create(organizationId, studyStr, individual, null, options, token); } @@ -314,7 +316,7 @@ public OpenCGAResult create(String organizationId, String studyStr, QueryOptions options, String token) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); ObjectMap auditParams = new ObjectMap() @@ -329,7 +331,8 @@ public OpenCGAResult create(String organizationId, String studyStr, validateNewIndividual(organizationId, study, individual, sampleIds, userId, true); // Create the individual - OpenCGAResult insert = getIndividualDBAdaptor(organizationId).insert(study.getUid(), individual, study.getVariableSets(), options); + OpenCGAResult insert = getIndividualDBAdaptor(organizationId).insert(study.getUid(), individual, + study.getVariableSets(), options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch created individual OpenCGAResult queryResult = getIndividual(organizationId, study.getUid(), individual.getUuid(), options); @@ -379,12 +382,13 @@ private void checkSamplesNotInUseInOtherIndividual(String organizationId, Set iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException { + public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) + throws CatalogException { ParamUtils.checkObj(sessionId, "sessionId"); query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); Query finalQuery = new Query(query); @@ -398,12 +402,13 @@ public DBIterator iterator(String organizationId, String studyStr, Q } @Override - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); Query finalQuery = new Query(query); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -436,10 +441,11 @@ public OpenCGAResult search(String organizationId, String studyId, Q } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -473,7 +479,7 @@ public OpenCGAResult count(String organizationId, String studyId, Qu query = ParamUtils.defaultObject(query, Query::new); Query finalQuery = new Query(query); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -504,7 +510,7 @@ public OpenCGAResult count(String organizationId, String studyId, Qu public OpenCGAResult relatives(String organizationId, String studyId, String individualId, int degree, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -555,13 +561,14 @@ public OpenCGAResult relatives(String organizationId, String studyId } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List individualIds, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List individualIds, QueryOptions options, String token) + throws CatalogException { return delete(organizationId, studyStr, individualIds, options, false, token); } public OpenCGAResult delete(String organizationId, String studyStr, List individualIds, ObjectMap params, boolean ignoreException, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); @@ -632,12 +639,12 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, return delete(organizationId, studyStr, query, options, false, token); } - public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); OpenCGAResult result = OpenCGAResult.empty(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationUuid = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -751,22 +758,26 @@ public OpenCGAResult addAnnotationSet(String organizationId, String public OpenCGAResult addAnnotationSets(String organizationId, String studyStr, String individualStr, List annotationSetList, QueryOptions options, String token) throws CatalogException { - return updateAnnotationSet(organizationId, studyStr, individualStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, token); + return updateAnnotationSet(organizationId, studyStr, individualStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, + token); } public OpenCGAResult setAnnotationSet(String organizationId, String studyStr, String individualStr, - AnnotationSet annotationSet, QueryOptions options, String token) throws CatalogException { + AnnotationSet annotationSet, QueryOptions options, String token) + throws CatalogException { return setAnnotationSets(organizationId, studyStr, individualStr, Collections.singletonList(annotationSet), options, token); } public OpenCGAResult setAnnotationSets(String organizationId, String studyStr, String individualStr, List annotationSetList, QueryOptions options, String token) throws CatalogException { - return updateAnnotationSet(organizationId, studyStr, individualStr, annotationSetList, ParamUtils.BasicUpdateAction.SET, options, token); + return updateAnnotationSet(organizationId, studyStr, individualStr, annotationSetList, ParamUtils.BasicUpdateAction.SET, options, + token); } - public OpenCGAResult removeAnnotationSet(String organizationId, String studyStr, String individualStr, String annotationSetId, - QueryOptions options, String token) throws CatalogException { + public OpenCGAResult removeAnnotationSet(String organizationId, String studyStr, String individualStr, + String annotationSetId, QueryOptions options, String token) + throws CatalogException { return removeAnnotationSets(organizationId, studyStr, individualStr, Collections.singletonList(annotationSetId), options, token); } @@ -777,7 +788,8 @@ public OpenCGAResult removeAnnotationSets(String organizationId, Str .stream() .map(id -> new AnnotationSet().setId(id)) .collect(Collectors.toList()); - return updateAnnotationSet(organizationId, studyStr, individualStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, token); + return updateAnnotationSet(organizationId, studyStr, individualStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, + token); } public OpenCGAResult updateAnnotations(String organizationId, String studyStr, String individualStr, String annotationSetId, @@ -797,15 +809,15 @@ public OpenCGAResult updateAnnotations(String organizationId, String public OpenCGAResult removeAnnotations(String organizationId, String studyStr, String individualStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, individualStr, annotationSetId, new ObjectMap("remove", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.REMOVE, options, token); + return updateAnnotations(organizationId, studyStr, individualStr, annotationSetId, + new ObjectMap("remove", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.REMOVE, options, token); } public OpenCGAResult resetAnnotations(String organizationId, String studyStr, String individualStr, String annotationSetId, List annotations, QueryOptions options, String token) throws CatalogException { - return updateAnnotations(organizationId, studyStr, individualStr, annotationSetId, new ObjectMap("reset", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.RESET, options, token); + return updateAnnotations(organizationId, studyStr, individualStr, annotationSetId, + new ObjectMap("reset", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.RESET, options, token); } public OpenCGAResult update(String organizationId, String studyStr, Query query, IndividualUpdateParams updateParams, @@ -815,7 +827,7 @@ public OpenCGAResult update(String organizationId, String studyStr, public OpenCGAResult update(String organizationId, String studyStr, Query query, IndividualUpdateParams updateParams, boolean ignoreException, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -879,10 +891,10 @@ public OpenCGAResult update(String organizationId, String studyStr, return endResult(result, ignoreException); } - public OpenCGAResult update(String organizationId, String studyStr, String individualId, + public OpenCGAResult update(String organizationId, String studyStr, String individualId, IndividualUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -906,7 +918,8 @@ public OpenCGAResult update(String organizationId, String studyStr, String individualUuid = ""; try { - OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), individualId, QueryOptions.empty(), userId); + OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), individualId, QueryOptions.empty(), + userId); if (internalResult.getNumResults() == 0) { throw new CatalogException("Individual '" + individualId + "' not found"); } @@ -939,7 +952,7 @@ public OpenCGAResult update(String organizationId, String studyStr, * Update an Individual from catalog. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param individualIds List of individual ids. Could be either the id or uuid. * @param updateParams Data model filled only with the parameters to be updated. * @param options QueryOptions object. @@ -948,16 +961,16 @@ public OpenCGAResult update(String organizationId, String studyStr, * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String organizationId, String studyStr, List individualIds, + public OpenCGAResult update(String organizationId, String studyStr, List individualIds, IndividualUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, individualIds, updateParams, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, List individualIds, - IndividualUpdateParams updateParams, boolean ignoreException, QueryOptions options, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, List individualIds, + IndividualUpdateParams updateParams, boolean ignoreException, QueryOptions options, + String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1096,12 +1109,12 @@ private OpenCGAResult update(String organizationId, Study study, Individual indi throw new CatalogException("Missing id or uuid in 'samples'"); } } - List sampleList = catalogManager.getSampleManager().internalGet(organizationId, studyUid, idList, SampleManager.INCLUDE_SAMPLE_IDS, - userId, false).getResults(); + List sampleList = catalogManager.getSampleManager().internalGet(organizationId, studyUid, idList, + SampleManager.INCLUDE_SAMPLE_IDS, userId, false).getResults(); // Check those samples are not in use by other individuals - checkSamplesNotInUseInOtherIndividual(organizationId, sampleList.stream().map(Sample::getUid).collect(Collectors.toSet()), studyUid, - individualUid); + checkSamplesNotInUseInOtherIndividual(organizationId, sampleList.stream().map(Sample::getUid).collect(Collectors.toSet()), + studyUid, individualUid); // Pass the DBAdaptor the corresponding list of Sample objects parameters.put(IndividualDBAdaptor.QueryParams.SAMPLES.key(), sampleList); @@ -1130,10 +1143,11 @@ private OpenCGAResult update(String organizationId, Study study, Individual indi parameters.remove(IndividualDBAdaptor.QueryParams.MOTHER.key()); } - checkUpdateAnnotations(study, individual, parameters, options, VariableSet.AnnotableDataModels.INDIVIDUAL, getIndividualDBAdaptor(organizationId), - userId); + checkUpdateAnnotations(organizationId, study, individual, parameters, options, VariableSet.AnnotableDataModels.INDIVIDUAL, + getIndividualDBAdaptor(organizationId), userId); - OpenCGAResult update = getIndividualDBAdaptor(organizationId).update(individual.getUid(), parameters, study.getVariableSets(), options); + OpenCGAResult update = getIndividualDBAdaptor(organizationId).update(individual.getUid(), parameters, + study.getVariableSets(), options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated individual OpenCGAResult result = getIndividualDBAdaptor(organizationId).get(study.getUid(), @@ -1144,13 +1158,13 @@ private OpenCGAResult update(String organizationId, Study study, Individual indi } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); ParamUtils.checkObj(field, "field"); - ParamUtils.checkObj(sessionId, "sessionId"); + ParamUtils.checkObj(token, "sessionId"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.VIEW_INDIVIDUALS); @@ -1171,13 +1185,13 @@ public OpenCGAResult rank(String organizationId, String studyStr, Query query, S } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); ParamUtils.checkObj(fields, "fields"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); Query finalQuery = new Query(query); @@ -1214,7 +1228,7 @@ public OpenCGAResult> getAcls(String organiz public OpenCGAResult> getAcls(String organizationId, String studyId, List individualList, List members, boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1230,8 +1244,8 @@ public OpenCGAResult> getAcls(String organiz Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), individualList, INCLUDE_INDIVIDUAL_IDS, user, - ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), individualList, + INCLUDE_INDIVIDUAL_IDS, user, ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -1293,11 +1307,11 @@ public OpenCGAResult> getAcls(String organiz return individualAcls; } - public OpenCGAResult> updateAcl(String organizationId, String studyId, + public OpenCGAResult> updateAcl(String organizationId, String studyId, List individualStrList, String memberList, IndividualAclParams aclParams, ParamUtils.AclAction action, boolean propagate, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, StudyManager.INCLUDE_STUDY_UID); ObjectMap auditParams = new ObjectMap() @@ -1337,14 +1351,15 @@ public OpenCGAResult> updateAcl(String organ if (StringUtils.isNotEmpty(aclParams.getSample())) { Query query = new Query(IndividualDBAdaptor.QueryParams.SAMPLES.key(), aclParams.getSample()); QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, IndividualDBAdaptor.QueryParams.ID.key()); - OpenCGAResult indDataResult = catalogManager.getIndividualManager().search(organizationId, studyId, query, options, token); + OpenCGAResult indDataResult = catalogManager.getIndividualManager().search(organizationId, studyId, query, + options, token); individualStrList = indDataResult.getResults().stream().map(Individual::getId).collect(Collectors.toList()); } // Obtain the resource ids - List individualList = internalGet(organizationId, study.getUid(), individualStrList, INCLUDE_INDIVIDUAL_IDS, userId, false) - .getResults(); + List individualList = internalGet(organizationId, study.getUid(), individualStrList, INCLUDE_INDIVIDUAL_IDS, userId, + false).getResults(); authorizationManager.checkCanAssignOrSeePermissions(study.getUid(), userId); @@ -1418,7 +1433,7 @@ public DataResult facet(String organizationId, String studyId, Query ParamUtils.defaultObject(query, Query::new); ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); // We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key()))); @@ -1455,7 +1470,8 @@ public DataResult facet(String organizationId, String studyId, Query // ************************** Private methods ******************************** // - private List getSampleUidsFromIndividuals(String organizationId, long studyUid, List individualUidList) throws CatalogException { + private List getSampleUidsFromIndividuals(String organizationId, long studyUid, List individualUidList) + throws CatalogException { // Look for all the samples belonging to the individual Query query = new Query() .append(IndividualDBAdaptor.QueryParams.STUDY_UID.key(), studyUid) diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/InterpretationManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/InterpretationManager.java index f8c9763eeeb..6c197bd97b2 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/InterpretationManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/InterpretationManager.java @@ -98,8 +98,8 @@ Enums.Resource getEntity() { } @Override - InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, QueryOptions options, - String user, boolean ignoreException) throws CatalogException { + InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, + QueryOptions options, String user, boolean ignoreException) throws CatalogException { if (ListUtils.isEmpty(entryList)) { throw new CatalogException("Missing interpretation entries."); } @@ -135,7 +135,8 @@ InternalGetDataResult internalGet(String organizationId, long st // Ensure the field by which we are querying for will be kept in the results queryOptions = keepFieldInQueryOptions(queryOptions, idQueryParam.key()); - OpenCGAResult interpretationDataResult = getInterpretationDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, user); + OpenCGAResult interpretationDataResult = getInterpretationDBAdaptor(organizationId).get(studyUid, queryCopy, + queryOptions, user); if (!versioned && interpretationDataResult.getNumResults() != uniqueList.size() && !ignoreException) { throw CatalogException.notFound("interpretations", @@ -190,16 +191,16 @@ InternalGetDataResult internalGet(String organizationId, long st } @Override - public OpenCGAResult create(String organizationId, String studyStr, Interpretation entry, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, Interpretation entry, QueryOptions options, + String token) throws CatalogException { throw new CatalogException("Non-supported. Use other create method"); } public OpenCGAResult create(String organizationId, String studyStr, String clinicalAnalysisStr, - Interpretation interpretation, ParamUtils.SaveInterpretationAs saveInterpretationAs, + Interpretation interpretation, ParamUtils.SaveInterpretationAs saveInterpretationAs, QueryOptions options, String token) throws CatalogException { // We check if the user can create interpretations in the clinical analysis - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); ObjectMap auditParams = new ObjectMap() @@ -218,8 +219,8 @@ public OpenCGAResult create(String organizationId, String studyS ClinicalAnalysisDBAdaptor.QueryParams.AUDIT.key(), ClinicalAnalysisDBAdaptor.QueryParams.INTERPRETATION_ID.key(), ClinicalAnalysisDBAdaptor.QueryParams.SECONDARY_INTERPRETATIONS_ID.key())); - ClinicalAnalysis clinicalAnalysis = catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), clinicalAnalysisStr, - clinicalOptions, userId).first(); + ClinicalAnalysis clinicalAnalysis = catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), + clinicalAnalysisStr, clinicalOptions, userId).first(); authorizationManager.checkClinicalAnalysisPermission(study.getUid(), clinicalAnalysis.getUid(), userId, ClinicalAnalysisPermissions.WRITE); @@ -228,12 +229,12 @@ public OpenCGAResult create(String organizationId, String studyS ClinicalAudit clinicalAudit = new ClinicalAudit(userId, ClinicalAudit.Action.CREATE_INTERPRETATION, "Create interpretation '" + interpretation.getId() + "'", TimeUtils.getTime()); - OpenCGAResult result = getInterpretationDBAdaptor(organizationId).insert(study.getUid(), interpretation, saveInterpretationAs, - Collections.singletonList(clinicalAudit)); + OpenCGAResult result = getInterpretationDBAdaptor(organizationId).insert(study.getUid(), interpretation, + saveInterpretationAs, Collections.singletonList(clinicalAudit)); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch created Interpretation - OpenCGAResult queryResult = getInterpretationDBAdaptor(organizationId).get(study.getUid(), interpretation.getId(), - QueryOptions.empty()); + OpenCGAResult queryResult = getInterpretationDBAdaptor(organizationId).get(study.getUid(), + interpretation.getId(), QueryOptions.empty()); result.setResults(queryResult.getResults()); } @@ -247,8 +248,8 @@ public OpenCGAResult create(String organizationId, String studyS } } - void validateNewInterpretation(String organizationId, Study study, Interpretation interpretation, ClinicalAnalysis clinicalAnalysis, String userId) - throws CatalogException { + void validateNewInterpretation(String organizationId, Study study, Interpretation interpretation, ClinicalAnalysis clinicalAnalysis, + String userId) throws CatalogException { if (study.getInternal() == null || study.getInternal().getConfiguration() == null || study.getInternal().getConfiguration().getClinical() == null || study.getInternal().getConfiguration().getClinical().getInterpretation() == null) { @@ -286,7 +287,7 @@ void validateNewInterpretation(String organizationId, Study study, Interpretatio interpretation.setSecondaryFindings(ParamUtils.defaultObject(interpretation.getSecondaryFindings(), Collections.emptyList())); interpretation.setComments(ParamUtils.defaultObject(interpretation.getComments(), Collections.emptyList())); interpretation.setStatus(ParamUtils.defaultObject(interpretation.getStatus(), Status::new)); - interpretation.setRelease(studyManager.getCurrentRelease(study)); + interpretation.setRelease(studyManager.getCurrentRelease(organizationId, study)); interpretation.setVersion(1); interpretation.setAttributes(ParamUtils.defaultObject(interpretation.getAttributes(), Collections.emptyMap())); interpretation.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.INTERPRETATION)); @@ -392,9 +393,9 @@ void validateNewInterpretation(String organizationId, Study study, Interpretatio interpretation.setAnalyst(new ClinicalAnalyst(user.getId(), user.getName(), user.getEmail(), userId, TimeUtils.getTime())); } - public OpenCGAResult clear(String organizationId, String studyStr, String clinicalAnalysisId, + public OpenCGAResult clear(String organizationId, String studyStr, String clinicalAnalysisId, List interpretationList, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); ObjectMap auditParams = new ObjectMap() @@ -413,8 +414,8 @@ public OpenCGAResult clear(String organizationId, String studySt try { QueryOptions clinicalOptions = keepFieldInQueryOptions(INCLUDE_CLINICAL_ANALYSIS, ClinicalAnalysisDBAdaptor.QueryParams.PANELS.key()); - OpenCGAResult clinicalResult = catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), - clinicalAnalysisId, clinicalOptions, userId); + OpenCGAResult clinicalResult = catalogManager.getClinicalAnalysisManager().internalGet(organizationId, + study.getUid(), clinicalAnalysisId, clinicalOptions, userId); if (clinicalResult.getNumResults() == 0) { throw new CatalogException("ClinicalAnalysis '" + clinicalAnalysisId + "' not found"); } @@ -424,8 +425,8 @@ public OpenCGAResult clear(String organizationId, String studySt + "made to the Interpretation."); } - OpenCGAResult tmpResult = internalGet(organizationId, study.getUid(), interpretationStr, INCLUDE_INTERPRETATION_IDS, - userId); + OpenCGAResult tmpResult = internalGet(organizationId, study.getUid(), interpretationStr, + INCLUDE_INTERPRETATION_IDS, userId); if (tmpResult.getNumResults() == 0) { throw new CatalogException("Interpretation '" + interpretationStr + "' not found."); } @@ -460,8 +461,8 @@ public OpenCGAResult clear(String organizationId, String studySt ClinicalAudit clinicalAudit = new ClinicalAudit(userId, ClinicalAudit.Action.CLEAR_INTERPRETATION, "Clear interpretation '" + interpretationId + "'", TimeUtils.getTime()); - OpenCGAResult writeResult = update(organizationId, study, interpretation, params, Collections.singletonList(clinicalAudit), null, options, - userId); + OpenCGAResult writeResult = update(organizationId, study, interpretation, params, Collections.singletonList(clinicalAudit), + null, options, userId); result.append(writeResult); auditManager.audit(operationId, userId, Enums.Action.CLEAR, Enums.Resource.INTERPRETATION, interpretationId, @@ -543,7 +544,8 @@ public OpenCGAResult clear(String organizationId, String studySt // ClinicalAudit clinicalAudit = new ClinicalAudit(userId, ClinicalAudit.Action.MERGE_INTERPRETATION, // "Merge interpretation '" + interpretation2.getId() + "' in interpretation '" + interpretation.getId() + "'", // TimeUtils.getTime()); -// OpenCGAResult mergeResult = getInterpretationDBAdaptor(organizationId).merge(interpretation.getUid(), interpretation2, +// OpenCGAResult mergeResult = getInterpretationDBAdaptor(organizationId).merge(interpretation.getUid(), +// interpretation2, // Collections.singletonList(clinicalAudit), clinicalVariantList); // auditManager.audit(userId, Enums.Action.MERGE, Enums.Resource.INTERPRETATION, interpretationId, interpretationUuid, // study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -607,7 +609,8 @@ public OpenCGAResult clear(String organizationId, String studySt // ClinicalAudit clinicalAudit = new ClinicalAudit(userId, ClinicalAudit.Action.MERGE_INTERPRETATION, // "Merge external interpretation in interpretation '" + interpretation.getId() + "'", // TimeUtils.getTime()); -// OpenCGAResult mergeResult = getInterpretationDBAdaptor(organizationId).merge(interpretation.getUid(), interpretation2, +// OpenCGAResult mergeResult = getInterpretationDBAdaptor(organizationId).merge(interpretation.getUid(), +// interpretation2, // Collections.singletonList(clinicalAudit), clinicalVariantList); // auditManager.audit(userId, Enums.Action.MERGE, Enums.Resource.INTERPRETATION, interpretationId, interpretationUuid, // study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -621,17 +624,17 @@ public OpenCGAResult clear(String organizationId, String studySt // } public OpenCGAResult update(String organizationId, String studyStr, Query query, - InterpretationUpdateParams updateParams, ParamUtils.SaveInterpretationAs as, + InterpretationUpdateParams updateParams, ParamUtils.SaveInterpretationAs as, QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, query, updateParams, as, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, Query query, InterpretationUpdateParams updateParams, - ParamUtils.SaveInterpretationAs as, boolean ignoreException, QueryOptions options, - String token) throws CatalogException { + public OpenCGAResult update(String organizationId, String studyStr, Query query, + InterpretationUpdateParams updateParams, ParamUtils.SaveInterpretationAs as, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -659,7 +662,8 @@ public OpenCGAResult update(String organizationId, String studyS DBIterator iterator; try { finalQuery.append(InterpretationDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - iterator = getInterpretationDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_INTERPRETATION_FINDING_IDS, userId); + iterator = getInterpretationDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_INTERPRETATION_FINDING_IDS, + userId); } catch (CatalogException e) { auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, "", "", study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError())); @@ -678,7 +682,8 @@ public OpenCGAResult update(String organizationId, String studyS clinicalAuditList.add(new ClinicalAudit(userId, ClinicalAudit.Action.SWAP_INTERPRETATION, "Swap interpretation '" + interpretation.getId() + "' to " + as, TimeUtils.getTime())); } - OpenCGAResult writeResult = update(organizationId, study, interpretation, updateParams, clinicalAuditList, as, options, userId); + OpenCGAResult writeResult = update(organizationId, study, interpretation, updateParams, clinicalAuditList, as, options, + userId); auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretation.getId(), interpretation.getUuid(), study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -705,7 +710,7 @@ public OpenCGAResult update(String organizationId, String studyS QueryOptions options, String token) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -794,20 +799,20 @@ public OpenCGAResult update(String organizationId, String studyS * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String organizationId, String studyStr, String clinicalAnalysisId, - List interpretationIds, InterpretationUpdateParams updateParams, + public OpenCGAResult update(String organizationId, String studyStr, String clinicalAnalysisId, + List interpretationIds, InterpretationUpdateParams updateParams, ParamUtils.SaveInterpretationAs as, QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, clinicalAnalysisId, interpretationIds, updateParams, as, false, options, token); } - public OpenCGAResult update(String organizationId, String studyStr, String clinicalAnalysisId, - List interpretationIds, InterpretationUpdateParams updateParams, + public OpenCGAResult update(String organizationId, String studyStr, String clinicalAnalysisId, + List interpretationIds, InterpretationUpdateParams updateParams, ParamUtils.SaveInterpretationAs as, boolean ignoreException, QueryOptions options, String token) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -837,8 +842,8 @@ public OpenCGAResult update(String organizationId, String studyS String interpretationUuid = ""; try { - OpenCGAResult tmpResult = internalGet(organizationId, study.getUid(), interpretationId, INCLUDE_INTERPRETATION_FINDING_IDS, - userId); + OpenCGAResult tmpResult = internalGet(organizationId, study.getUid(), interpretationId, + INCLUDE_INTERPRETATION_FINDING_IDS, userId); if (tmpResult.getNumResults() == 0) { throw new CatalogException("Interpretation '" + interpretationId + "' not found."); } @@ -860,7 +865,8 @@ public OpenCGAResult update(String organizationId, String studyS clinicalAuditList.add(new ClinicalAudit(userId, ClinicalAudit.Action.SWAP_INTERPRETATION, "Swap interpretation '" + interpretation.getId() + "' to " + as, TimeUtils.getTime())); } - OpenCGAResult writeResult = update(organizationId, study, interpretation, updateParams, clinicalAuditList, as, options, userId); + OpenCGAResult writeResult = update(organizationId, study, interpretation, updateParams, clinicalAuditList, as, options, + userId); result.append(writeResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.INTERPRETATION, interpretation.getId(), @@ -1069,12 +1075,13 @@ private OpenCGAResult update(String organizationId, Study study, Interpretation } } - OpenCGAResult update = getInterpretationDBAdaptor(organizationId).update(interpretation.getUid(), parameters, clinicalAuditList, as, - options); + OpenCGAResult update = getInterpretationDBAdaptor(organizationId).update(interpretation.getUid(), parameters, + clinicalAuditList, as, options); update.addEvents(events); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated interpretation - OpenCGAResult result = getInterpretationDBAdaptor(organizationId).get(study.getUid(), interpretation.getId(), options); + OpenCGAResult result = getInterpretationDBAdaptor(organizationId).get(study.getUid(), interpretation.getId(), + options); update.setResults(result.getResults()); } return update; @@ -1082,7 +1089,7 @@ private OpenCGAResult update(String organizationId, Study study, Interpretation public OpenCGAResult revert(String organizationId, String studyStr, String clinicalAnalysisId, String interpretationId, int version, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_CONFIGURATION); ObjectMap auditParams = new ObjectMap() @@ -1095,8 +1102,8 @@ public OpenCGAResult revert(String organizationId, String studyS String interpretationUuid = ""; try { - OpenCGAResult clinicalResult = catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), - clinicalAnalysisId, INCLUDE_CLINICAL_ANALYSIS, userId); + OpenCGAResult clinicalResult = catalogManager.getClinicalAnalysisManager().internalGet(organizationId, + study.getUid(), clinicalAnalysisId, INCLUDE_CLINICAL_ANALYSIS, userId); if (clinicalResult.getNumResults() == 0) { throw new CatalogException("Could not find ClinicalAnalysis '" + clinicalAnalysisId + "'"); } @@ -1112,7 +1119,8 @@ public OpenCGAResult revert(String organizationId, String studyS + " can be made to the Interpretation."); } - OpenCGAResult result = internalGet(organizationId, study.getUid(), interpretationId, INCLUDE_INTERPRETATION_IDS, userId); + OpenCGAResult result = internalGet(organizationId, study.getUid(), interpretationId, INCLUDE_INTERPRETATION_IDS, + userId); if (result.getNumResults() == 0) { throw new CatalogException("Could not find interpretation '" + interpretationId + "'"); } @@ -1141,7 +1149,8 @@ public OpenCGAResult revert(String organizationId, String studyS List clinicalAuditList = new ArrayList<>(); clinicalAuditList.add(new ClinicalAudit(userId, ClinicalAudit.Action.REVERT_INTERPRETATION, "Revert interpretation '" + interpretation.getId() + "' to version '" + version + "'", TimeUtils.getTime())); - OpenCGAResult revert = getInterpretationDBAdaptor(organizationId).revert(interpretation.getUid(), version, clinicalAuditList); + OpenCGAResult revert = getInterpretationDBAdaptor(organizationId).revert(interpretation.getUid(), version, + clinicalAuditList); auditManager.audit(userId, Enums.Action.REVERT, Enums.Resource.INTERPRETATION, interpretation.getId(), interpretation.getUuid(), study.getId(), study.getUuid(), auditParams, @@ -1177,7 +1186,7 @@ public OpenCGAResult search(String organizationId, String studyI query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); fixQueryObject(organizationId, study, query, userId); @@ -1189,16 +1198,17 @@ public OpenCGAResult search(String organizationId, String studyI for (Interpretation interpretation : queryResult.getResults()) { if (StringUtils.isNotEmpty(interpretation.getClinicalAnalysisId())) { try { - catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), interpretation.getClinicalAnalysisId(), - ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, userId); + catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), + interpretation.getClinicalAnalysisId(), ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, userId); results.add(interpretation); } catch (CatalogException e) { // Maybe the clinical analysis was deleted Query clinicalQuery = new Query(ClinicalAnalysisDBAdaptor.QueryParams.DELETED.key(), true); try { - catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), interpretation.getClinicalAnalysisId(), - clinicalQuery, ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, userId); + catalogManager.getClinicalAnalysisManager().internalGet(organizationId, study.getUid(), + interpretation.getClinicalAnalysisId(), clinicalQuery, ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS, + userId); results.add(interpretation); } catch (CatalogException e1) { logger.debug("Removing interpretation " + interpretation.getUuid() + " from results. User " + userId @@ -1215,10 +1225,11 @@ public OpenCGAResult search(String organizationId, String studyI } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1250,11 +1261,12 @@ public OpenCGAResult count(String organizationId, String studyId } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List ids, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List ids, QueryOptions options, String token) + throws CatalogException { throw new NotImplementedException("Use other implemented delete method"); } - public OpenCGAResult delete(String organizationId, String studyStr, String clinicalAnalysisId, List interpretationIds, + public OpenCGAResult delete(String organizationId, String studyStr, String clinicalAnalysisId, List interpretationIds, String token) throws CatalogException { return delete(organizationId, studyStr, clinicalAnalysisId, interpretationIds, false, token); } @@ -1265,7 +1277,7 @@ public OpenCGAResult delete(String organizationId, String studyStr, String clini throw new CatalogException("Missing list of interpretation ids"); } - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1312,7 +1324,8 @@ public OpenCGAResult delete(String organizationId, String studyStr, String clini String interpretationId = id; String interpretationUuid = ""; try { - OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), id, INCLUDE_INTERPRETATION_IDS, userId); + OpenCGAResult internalResult = internalGet(organizationId, study.getUid(), id, INCLUDE_INTERPRETATION_IDS, + userId); if (internalResult.getNumResults() == 0) { throw new CatalogException("Interpretation '" + id + "' not found"); } @@ -1359,7 +1372,8 @@ public OpenCGAResult delete(String organizationId, String studyStr, String clini } @Override - public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { throw new NotImplementedException("Use other delete implementation"); } // @@ -1391,7 +1405,8 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, // fixQueryObject(finalQuery); // finalQuery.append(InterpretationDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); // -// iterator = getInterpretationDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_INTERPRETATION_IDS, userId); +// iterator = getInterpretationDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_INTERPRETATION_IDS, +// userId); // // // If the user is the owner or the admin, we won't check if he has permissions for every single entry // checkPermissions = !authorizationManager.isOwnerOrAdmin(study.getUid(), userId); @@ -1440,14 +1455,15 @@ public OpenCGAResult delete(String organizationId, String studyStr, Query query, // } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, + String token) throws CatalogException { return null; } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String token) throws CatalogException { return null; } @@ -1469,7 +1485,8 @@ protected void fixQueryObject(String organizationId, Study study, Query query, S PanelDBAdaptor.QueryParams fieldFilter = catalogManager.getPanelManager().getFieldFilter(panelList); Query tmpQuery = new Query(fieldFilter.key(), panelList); - OpenCGAResult result = getPanelDBAdaptor(organizationId).get(study.getUid(), tmpQuery, PanelManager.INCLUDE_PANEL_IDS, user); + OpenCGAResult result = getPanelDBAdaptor(organizationId).get(study.getUid(), tmpQuery, PanelManager.INCLUDE_PANEL_IDS, + user); if (result.getNumResults() > 0) { query.put(InterpretationDBAdaptor.QueryParams.PANELS_UID.key(), result.getResults().stream().map(Panel::getUid).collect(Collectors.toList())); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/JobManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/JobManager.java index da5691d0bcd..b229dc718af 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/JobManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/JobManager.java @@ -201,7 +201,7 @@ public Study getStudy(String organizationId, Job job, String token) throws Catal throw new CatalogException("Missing study uid field in job"); } - String user = catalogManager.getUserManager().getUserId(token); + String user = catalogManager.getUserManager().getUserId(organizationId, token); Query query = new Query(StudyDBAdaptor.QueryParams.UID.key(), job.getStudyUid()); OpenCGAResult studyDataResult = getStudyDBAdaptor(organizationId).get(query, QueryOptions.empty(), user); @@ -214,7 +214,7 @@ public Study getStudy(String organizationId, Job job, String token) throws Catal } public OpenCGAResult visit(String organizationId, String studyId, String jobId, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -239,8 +239,9 @@ public OpenCGAResult visit(String organizationId, String studyId, String jo } @Override - public OpenCGAResult create(String organizationId, String studyStr, Job job, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult create(String organizationId, String studyStr, Job job, QueryOptions options, String token) + throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -274,7 +275,7 @@ public OpenCGAResult create(String organizationId, String studyStr, Job job job.setParams(ParamUtils.defaultObject(job.getParams(), HashMap::new)); job.setAttributes(ParamUtils.defaultObject(job.getAttributes(), HashMap::new)); job.setUserId(userId); - job.setRelease(catalogManager.getStudyManager().getCurrentRelease(study)); + job.setRelease(catalogManager.getStudyManager().getCurrentRelease(organizationId, study)); job.setOutDir(job.getOutDir() != null && StringUtils.isNotEmpty(job.getOutDir().getPath()) ? job.getOutDir() : null); job.setStudy(new JobStudyParam(study.getFqn())); @@ -340,7 +341,7 @@ private void autoCompleteNewJob(String organizationId, Study study, Job job, Str job.setCreationDate(ParamUtils.checkDateOrGetCurrentDate(job.getCreationDate(), JobDBAdaptor.QueryParams.CREATION_DATE.key())); job.setModificationDate(ParamUtils.checkDateOrGetCurrentDate(job.getModificationDate(), JobDBAdaptor.QueryParams.MODIFICATION_DATE.key())); - job.setRelease(catalogManager.getStudyManager().getCurrentRelease(study)); + job.setRelease(catalogManager.getStudyManager().getCurrentRelease(organizationId, study)); // Set default internal job.setInternal(JobInternal.init()); @@ -353,10 +354,12 @@ private void autoCompleteNewJob(String organizationId, Study study, Job job, Str // If uuid is provided, we will remove the study uid from the query so it can be searched across any study InternalGetDataResult dependsOnResult; if (uuidProvided) { - dependsOnResult = internalGet(organizationId, 0, job.getDependsOn().stream().map(Job::getId).collect(Collectors.toList()), null, - INCLUDE_JOB_IDS, job.getUserId(), false); + dependsOnResult = internalGet(organizationId, 0, + job.getDependsOn().stream().map(Job::getId).collect(Collectors.toList()), + null, INCLUDE_JOB_IDS, job.getUserId(), false); } else { - dependsOnResult = internalGet(organizationId, study.getUid(), job.getDependsOn().stream().map(Job::getId).collect(Collectors.toList()), + dependsOnResult = internalGet(organizationId, study.getUid(), + job.getDependsOn().stream().map(Job::getId).collect(Collectors.toList()), null, INCLUDE_JOB_IDS, job.getUserId(), false); } job.setDependsOn(dependsOnResult.getResults()); @@ -473,7 +476,7 @@ public OpenCGAResult submit(String organizationId, String studyStr, String public OpenCGAResult submit(String organizationId, String studyStr, String toolId, Enums.Priority priority, Map params, String jobId, String jobDescription, List jobDependsOn, List jobTags, Map attributes, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -626,14 +629,14 @@ private boolean jobEligibleToReuse(String inputJobId, Job job) { } public OpenCGAResult count(String organizationId, Query query, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); authorizationManager.isInstallationAdministrator(userId); return getJobDBAdaptor(organizationId).count(query); } public DBIterator iterator(String organizationId, Query query, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); authorizationManager.isInstallationAdministrator(userId); return getJobDBAdaptor(organizationId).iterator(query, options); @@ -680,11 +683,12 @@ private void fixQueryObject(String organizationId, Study study, Query query, Str } @Override - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -710,10 +714,11 @@ public OpenCGAResult search(String organizationId, String studyId, Query qu } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -740,11 +745,12 @@ public OpenCGAResult distinct(String organizationId, String studyId, List iterator(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public DBIterator iterator(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); fixQueryObject(organizationId, study, query, userId); @@ -757,7 +763,7 @@ public DBIterator iterator(String organizationId, String studyId, Query que public OpenCGAResult count(String organizationId, String studyId, Query query, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -792,7 +798,7 @@ public OpenCGAResult delete(String organizationId, String studyStr, List public OpenCGAResult delete(String organizationId, String studyStr, List jobIds, ObjectMap params, boolean ignoreException, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationUuid = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -869,7 +875,7 @@ public OpenCGAResult delete(String organizationId, String studyId, Query query, Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); OpenCGAResult result = OpenCGAResult.empty(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); String operationUuid = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -952,7 +958,7 @@ public OpenCGAResult log(String organizationId, String studyId, Str boolean tail, String token) throws CatalogException { long startTime = System.currentTimeMillis(); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1039,7 +1045,7 @@ public OpenCGAResult update(String organizationId, String studyStr, Query q boolean ignoreException, QueryOptions options, String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1101,7 +1107,7 @@ public OpenCGAResult update(String organizationId, String studyStr, Query q * Update Job from catalog. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param jobIds List of Job ids. Could be either the id or uuid. * @param updateParams Data model filled only with the parameters to be updated. * @param options QueryOptions object. @@ -1110,14 +1116,14 @@ public OpenCGAResult update(String organizationId, String studyStr, Query q * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String organizationId, String studyStr, List jobIds, JobUpdateParams updateParams, QueryOptions options, - String token) throws CatalogException { + public OpenCGAResult update(String organizationId, String studyStr, List jobIds, JobUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { return update(organizationId, studyStr, jobIds, updateParams, false, options, token); } public OpenCGAResult update(String organizationId, String studyStr, List jobIds, JobUpdateParams updateParams, boolean ignoreException, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1177,7 +1183,7 @@ public OpenCGAResult update(String organizationId, String studyStr, List update(String organizationId, String studyStr, String jobId, JobUpdateParams updateParams, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1291,8 +1297,8 @@ private OpenCGAResult update(String organizationId, Study study, Job job, J OpenCGAResult update = getJobDBAdaptor(organizationId).update(job.getUid(), updateMap, options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated job - OpenCGAResult result = getJobDBAdaptor(organizationId).get(study.getUid(), new Query(JobDBAdaptor.QueryParams.UID.key(), job.getUid()), - options, userId); + OpenCGAResult result = getJobDBAdaptor(organizationId).get(study.getUid(), new Query(JobDBAdaptor.QueryParams.UID.key(), + job.getUid()), options, userId); update.setResults(result.getResults()); } return update; @@ -1303,22 +1309,22 @@ private File getFile(String organizationId, long studyUid, String path, String u throw new CatalogException("Missing file path"); } - OpenCGAResult fileResult = catalogManager.getFileManager().internalGet(organizationId, studyUid, path, FileManager.INCLUDE_FILE_URI_PATH, - userId); + OpenCGAResult fileResult = catalogManager.getFileManager().internalGet(organizationId, studyUid, path, + FileManager.INCLUDE_FILE_URI_PATH, userId); if (fileResult.getNumResults() == 0) { throw new CatalogException("File/Folder '" + path + "' not found"); } return fileResult.first(); } - public OpenCGAResult update(String organizationId, String studyId, Query query, ObjectMap parameters, QueryOptions options, String token) - throws CatalogException { + public OpenCGAResult update(String organizationId, String studyId, Query query, ObjectMap parameters, QueryOptions options, + String token) throws CatalogException { return update(organizationId, studyId, query, parameters, false, options, token); } - public OpenCGAResult update(String organizationId, String studyId, Query query, ObjectMap parameters, boolean ignoreException, QueryOptions options, - String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyId, Query query, ObjectMap parameters, boolean ignoreException, + QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1375,9 +1381,9 @@ public OpenCGAResult update(String organizationId, String studyId, Query qu return endResult(result, ignoreException); } - public OpenCGAResult update(String organizationId, String studyId, String jobId, ObjectMap parameters, QueryOptions options, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyId, String jobId, ObjectMap parameters, QueryOptions options, + String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1433,9 +1439,9 @@ public OpenCGAResult update(String organizationId, String studyId, List update(String organizationId, String studyId, List jobIds, ObjectMap parameters, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyId, List jobIds, ObjectMap parameters, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1491,7 +1497,7 @@ public OpenCGAResult update(String organizationId, String studyId, List top(String organizationId, Query baseQuery, int limit, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); List studies = studyManager.search(organizationId, new Query(StudyDBAdaptor.QueryParams.OWNER.key(), userId), new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.UUID.key()), token).getResults() .stream() @@ -1500,7 +1506,8 @@ public OpenCGAResult top(String organizationId, Query baseQuery, int lim return top(organizationId, studies, baseQuery, limit, token); } - public OpenCGAResult top(String organizationId, String studyStr, Query baseQuery, int limit, String token) throws CatalogException { + public OpenCGAResult top(String organizationId, String studyStr, Query baseQuery, int limit, String token) + throws CatalogException { if (StringUtils.isEmpty(studyStr)) { return top(organizationId, baseQuery, limit, token); } else { @@ -1508,8 +1515,9 @@ public OpenCGAResult top(String organizationId, String studyStr, Query b } } - public OpenCGAResult top(String organizationId, List studiesStr, Query baseQuery, int limit, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult top(String organizationId, List studiesStr, Query baseQuery, int limit, String token) + throws CatalogException { + String userId = userManager.getUserId(organizationId, token); fixQueryObject(organizationId, null, baseQuery, userId); List studies = new ArrayList<>(studiesStr.size()); for (String studyStr : studiesStr) { @@ -1676,7 +1684,7 @@ public OpenCGAResult rank(String organizationId, String studyId, Query query, St ParamUtils.checkObj(field, "field"); ParamUtils.checkObj(token, "token"); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.VIEW_JOBS); @@ -1693,8 +1701,8 @@ public OpenCGAResult rank(String organizationId, String studyId, Query query, St } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyId, Query query, List fields, QueryOptions options, String token) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyId, Query query, List fields, QueryOptions options, + String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); ParamUtils.checkObj(fields, "fields"); @@ -1702,7 +1710,7 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyId, Qu throw new CatalogException("Empty fields parameter."); } - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); // Add study id to the query @@ -1714,15 +1722,17 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyId, Qu } // ************************** ACLs ******************************** // - public OpenCGAResult> getAcls(String organizationId, String studyId, List jobList, String member, boolean ignoreException, - String token) throws CatalogException { - return getAcls(organizationId, studyId, jobList, StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), + public OpenCGAResult> getAcls(String organizationId, String studyId, List jobList, String member, + boolean ignoreException, String token) throws CatalogException { + return getAcls(organizationId, studyId, jobList, + StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), ignoreException, token); } - public OpenCGAResult> getAcls(String organizationId, String studyId, List jobList, List members, - boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + public OpenCGAResult> getAcls(String organizationId, String studyId, List jobList, + List members, boolean ignoreException, String token) + throws CatalogException { + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1738,7 +1748,8 @@ public OpenCGAResult> getAcls(String organizationId Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), jobList, INCLUDE_JOB_IDS, user, ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), jobList, INCLUDE_JOB_IDS, user, + ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -1799,10 +1810,10 @@ public OpenCGAResult> getAcls(String organizationId return jobAcls; } - public OpenCGAResult> updateAcl(String organizationId, String studyId, List jobStrList, String memberList, - AclParams aclParams, ParamUtils.AclAction action, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult> updateAcl(String organizationId, String studyId, List jobStrList, + String memberList, AclParams aclParams, ParamUtils.AclAction action, + String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1892,9 +1903,9 @@ public OpenCGAResult> updateAcl(String organization } } - public DataResult facet(String organizationId, String studyId, Query query, QueryOptions options, boolean defaultStats, String token) - throws CatalogException, IOException { - String userId = userManager.getUserId(token); + public DataResult facet(String organizationId, String studyId, Query query, QueryOptions options, boolean defaultStats, + String token) throws CatalogException, IOException { + String userId = userManager.getUserId(organizationId, token); // We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key()))); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/OrganizationManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/OrganizationManager.java index 1ddad567156..f3187879f57 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/OrganizationManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/OrganizationManager.java @@ -75,7 +75,7 @@ OpenCGAResult internalGet(List organizationList, @Nullable // Ensure the field by which we are querying for will be kept in the results queryOptions = keepFieldInQueryOptions(queryOptions, idQueryParam.key()); - OpenCGAResult organizationDataResult = organizationDBAdaptor.get(queryCopy, queryOptions); + OpenCGAResult organizationDataResult = getOrganizationDBAdaptor(organization).get(queryCopy, queryOptions); Function organizationStringFunction = Organization::getId; if (idQueryParam.equals(OrganizationDBAdaptor.QueryParams.UUID)) { @@ -115,7 +115,7 @@ OrganizationDBAdaptor.QueryParams getFieldFilter(List idList) throws Cat public OpenCGAResult create(OrganizationCreateParams organizationCreateParams, QueryOptions options, String token) throws CatalogException { - String userId = this.catalogManager.getUserManager().getUserId(token); + String userId = this.catalogManager.getUserManager().getUserId(ParamConstants.ADMIN_ORGANIZATION, token); ObjectMap auditParams = new ObjectMap() .append("organizationCreateParams", organizationCreateParams) @@ -137,9 +137,9 @@ public OpenCGAResult create(OrganizationCreateParams organizationC organization = organizationCreateParams.toOrganization(); validateOrganizationForCreation(organization); - queryResult = organizationDBAdaptor.insert(organization, options); + queryResult = getOrganizationDBAdaptor(organization).insert(organization, options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { - OpenCGAResult result = organizationDBAdaptor.get(organization.getUid(), options); + OpenCGAResult result = getOrganizationDBAdaptor(organization).get(organization.getUid(), options); organization = result.first(); // Fetch created organization queryResult.setResults(result.getResults()); @@ -156,7 +156,7 @@ public OpenCGAResult create(OrganizationCreateParams organizationC auditManager.auditCreate(userId, Enums.Resource.ORGANIZATION, organization.getId(), "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError())); try { - organizationDBAdaptor.delete(organization); + getOrganizationDBAdaptor(organization).delete(organization); } catch (Exception e1) { logger.error("Error deleting organization from catalog after failing creating the folder in the filesystem", e1); throw e; @@ -200,7 +200,7 @@ public OpenCGAResult update(String organizationId, OrganizationUpd organizationId = organization.getId(); organizationUuid = organization.getUuid(); - OpenCGAResult updateResult = organizationDBAdaptor.update(organization.getUid(), updateMap, options); + OpenCGAResult updateResult = getOrganizationDBAdaptor(organization).update(organization.getUid(), updateMap, options); result.append(updateResult); auditManager.auditUpdate(payload.getUserId(), Enums.Resource.ORGANIZATION, organization.getId(), organization.getUuid(), "", "", diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/PanelManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/PanelManager.java index b2bd9344849..7804162e271 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/PanelManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/PanelManager.java @@ -92,8 +92,8 @@ Enums.Resource getEntity() { } @Override - InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, QueryOptions options, - String user, boolean ignoreException) throws CatalogException { + InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, + QueryOptions options, String user, boolean ignoreException) throws CatalogException { if (ListUtils.isEmpty(entryList)) { throw new CatalogException("Missing panel entries."); } @@ -115,7 +115,7 @@ InternalGetDataResult internalGet(String organizationId, long studyUid, L // Ensure the field by which we are querying for will be kept in the results queryOptions = keepFieldInQueryOptions(queryOptions, idQueryParam.key()); - OpenCGAResult panelDataResult = panelDBAdaptor.get(studyUid, queryCopy, queryOptions, user); + OpenCGAResult panelDataResult = getPanelDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, user); Function panelStringFunction = Panel::getId; if (idQueryParam.equals(PanelDBAdaptor.QueryParams.UUID)) { @@ -126,7 +126,7 @@ InternalGetDataResult internalGet(String organizationId, long studyUid, L return keepOriginalOrder(uniqueList, panelStringFunction, panelDataResult, ignoreException, versioned); } // Query without adding the user check - OpenCGAResult resultsNoCheck = panelDBAdaptor.get(queryCopy, queryOptions); + OpenCGAResult resultsNoCheck = getPanelDBAdaptor(organizationId).get(queryCopy, queryOptions); if (resultsNoCheck.getNumResults() == panelDataResult.getNumResults()) { throw CatalogException.notFound("panels", getMissingFields(uniqueList, panelDataResult.getResults(), panelStringFunction)); @@ -152,19 +152,22 @@ PanelDBAdaptor.QueryParams getFieldFilter(List idList) throws CatalogExc return idQueryParam; } - private OpenCGAResult getPanel(long studyUid, String panelUuid, QueryOptions options) throws CatalogException { + private OpenCGAResult getPanel(String organizationId, long studyUid, String panelUuid, QueryOptions options) + throws CatalogException { Query query = new Query() .append(PanelDBAdaptor.QueryParams.STUDY_UID.key(), studyUid) .append(PanelDBAdaptor.QueryParams.UUID.key(), panelUuid); - return panelDBAdaptor.get(query, options); + return getPanelDBAdaptor(organizationId).get(query, options); } @Override - public OpenCGAResult create(String organizationId, String studyStr, Panel panel, QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult create(String organizationId, String studyStr, Panel panel, QueryOptions options, String token) + throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("panel", panel) .append("options", options) @@ -173,13 +176,13 @@ public OpenCGAResult create(String organizationId, String studyStr, Panel // 1. We check everything can be done authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.WRITE_PANELS); - autoCompletePanel(study, panel); + autoCompletePanel(organizationId, study, panel); options = ParamUtils.defaultObject(options, QueryOptions::new); - OpenCGAResult insert = panelDBAdaptor.insert(study.getUid(), panel, options); + OpenCGAResult insert = getPanelDBAdaptor(organizationId).insert(study.getUid(), panel, options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch created panel - OpenCGAResult result = getPanel(study.getUid(), panel.getUuid(), options); + OpenCGAResult result = getPanel(organizationId, study.getUid(), panel.getUuid(), options); insert.setResults(result.getResults()); } auditManager.auditCreate(userId, Enums.Resource.DISEASE_PANEL, panel.getId(), panel.getUuid(), study.getId(), study.getUuid(), @@ -193,11 +196,13 @@ public OpenCGAResult create(String organizationId, String studyStr, Panel } } - public OpenCGAResult importFromSource(String studyId, String source, String panelIds, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult importFromSource(String organizationId, String studyId, String source, String panelIds, String token) + throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("source", source) .append("panelIds", panelIds) @@ -280,13 +285,13 @@ public OpenCGAResult importFromSource(String studyId, String source, Stri logger.info("Downloading panel '{}' from '{}'", panelId, url); try (InputStream inputStream = url.openStream()) { Panel panel = JacksonUtils.getDefaultObjectMapper().readValue(inputStream, Panel.class); - autoCompletePanel(study, panel); + autoCompletePanel(organizationId, study, panel); panelList.add(panel); } } logger.info("Inserting panels in database"); - result.append(panelDBAdaptor.insert(study.getUid(), panelList)); + result.append(getPanelDBAdaptor(organizationId).insert(study.getUid(), panelList)); } result.setResults(importedPanels); auditManager.initAuditBatch(operationId); @@ -313,11 +318,11 @@ public OpenCGAResult importFromSource(String studyId, String source, Stri } } - private void autoCompletePanel(Study study, Panel panel) throws CatalogException { + private void autoCompletePanel(String organizationId, Study study, Panel panel) throws CatalogException { // Check all the panel fields ParamUtils.checkIdentifier(panel.getId(), "id"); panel.setName(ParamUtils.defaultString(panel.getName(), panel.getId())); - panel.setRelease(studyManager.getCurrentRelease(study)); + panel.setRelease(studyManager.getCurrentRelease(organizationId, study)); panel.setVersion(1); panel.setAuthor(ParamUtils.defaultString(panel.getAuthor(), "")); panel.setCreationDate(TimeUtils.getTime()); @@ -335,16 +340,16 @@ private void autoCompletePanel(Study study, Panel panel) throws CatalogException panel.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.PANEL)); } - public OpenCGAResult update(String studyId, Query query, PanelUpdateParams updateParams, QueryOptions options, String token) - throws CatalogException { - return update(studyId, query, updateParams, false, options, token); + public OpenCGAResult update(String organizationId, String studyId, Query query, PanelUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + return update(organizationId, studyId, query, updateParams, false, options, token); } - public OpenCGAResult update(String studyId, Query query, PanelUpdateParams updateParams, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { + public OpenCGAResult update(String organizationId, String studyId, Query query, PanelUpdateParams updateParams, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -357,6 +362,7 @@ public OpenCGAResult update(String studyId, Query query, PanelUpdateParam } ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyId) .append("query", query) .append("updateParams", updateMap) @@ -368,7 +374,7 @@ public OpenCGAResult update(String studyId, Query query, PanelUpdateParam DBIterator iterator; try { finalQuery.append(PanelDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - iterator = panelDBAdaptor.iterator(study.getUid(), finalQuery, INCLUDE_PANEL_IDS, userId); + iterator = getPanelDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_PANEL_IDS, userId); } catch (CatalogException e) { auditManager.auditUpdate(operationId, userId, Enums.Resource.DISEASE_PANEL, "", "", study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError())); @@ -380,7 +386,7 @@ public OpenCGAResult update(String studyId, Query query, PanelUpdateParam while (iterator.hasNext()) { Panel panel = iterator.next(); try { - OpenCGAResult updateResult = update(study, panel, updateParams, options, userId); + OpenCGAResult updateResult = update(organizationId, study, panel, updateParams, options, userId); result.append(updateResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.DISEASE_PANEL, panel.getId(), panel.getUuid(), study.getId(), @@ -400,9 +406,9 @@ public OpenCGAResult update(String studyId, Query query, PanelUpdateParam return endResult(result, ignoreException); } - public OpenCGAResult update(String studyStr, String panelId, PanelUpdateParams updateParams, QueryOptions options, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, String panelId, PanelUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -415,6 +421,7 @@ public OpenCGAResult update(String studyStr, String panelId, PanelUpdateP } ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("panelId", panelId) .append("updateParams", updateMap) @@ -434,7 +441,7 @@ public OpenCGAResult update(String studyStr, String panelId, PanelUpdateP panelId = panel.getId(); panelUuid = panel.getUuid(); - OpenCGAResult updateResult = update(study, panel, updateParams, options, userId); + OpenCGAResult updateResult = update(organizationId, study, panel, updateParams, options, userId); result.append(updateResult); auditManager.auditUpdate(userId, Enums.Resource.DISEASE_PANEL, panel.getId(), panel.getUuid(), study.getId(), study.getUuid(), @@ -456,23 +463,24 @@ public OpenCGAResult update(String studyStr, String panelId, PanelUpdateP /** * Update Panel from catalog. * - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. - * @param panelIds List of Panel ids. Could be either the id or uuid. - * @param updateParams Data model filled only with the parameters to be updated. - * @param options QueryOptions object. - * @param token Session id of the user logged in. + * @param organizationId Organization id. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] + * @param panelIds List of Panel ids. Could be either the id or uuid. + * @param updateParams Data model filled only with the parameters to be updated. + * @param options QueryOptions object. + * @param token Session id of the user logged in. * @return A OpenCGAResult. * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String studyStr, List panelIds, PanelUpdateParams updateParams, QueryOptions options, - String token) throws CatalogException { - return update(studyStr, panelIds, updateParams, false, options, token); + public OpenCGAResult update(String organizationId, String studyStr, List panelIds, PanelUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + return update(organizationId, studyStr, panelIds, updateParams, false, options, token); } - public OpenCGAResult update(String studyStr, List panelIds, PanelUpdateParams updateParams, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, List panelIds, PanelUpdateParams updateParams, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -485,6 +493,7 @@ public OpenCGAResult update(String studyStr, List panelIds, Panel } ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("panelIds", panelIds) .append("updateParams", updateMap) @@ -509,7 +518,7 @@ public OpenCGAResult update(String studyStr, List panelIds, Panel panelId = panel.getId(); panelUuid = panel.getUuid(); - OpenCGAResult updateResult = update(study, panel, updateParams, options, userId); + OpenCGAResult updateResult = update(organizationId, study, panel, updateParams, options, userId); result.append(updateResult); auditManager.auditUpdate(userId, Enums.Resource.DISEASE_PANEL, panel.getId(), panel.getUuid(), study.getId(), @@ -529,8 +538,8 @@ public OpenCGAResult update(String studyStr, List panelIds, Panel return endResult(result, ignoreException); } - private OpenCGAResult update(Study study, Panel panel, PanelUpdateParams updateParams, QueryOptions options, String userId) - throws CatalogException { + private OpenCGAResult update(String organizationId, Study study, Panel panel, PanelUpdateParams updateParams, QueryOptions options, + String userId) throws CatalogException { ObjectMap parameters = new ObjectMap(); if (updateParams != null) { try { @@ -552,10 +561,10 @@ private OpenCGAResult update(Study study, Panel panel, PanelUpdateParams updateP PanelDBAdaptor.QueryParams.ID.key()); } - OpenCGAResult update = panelDBAdaptor.update(panel.getUid(), parameters, options); + OpenCGAResult update = getPanelDBAdaptor(organizationId).update(panel.getUid(), parameters, options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated panel - OpenCGAResult result = panelDBAdaptor.get(study.getUid(), + OpenCGAResult result = getPanelDBAdaptor(organizationId).get(study.getUid(), new Query(PanelDBAdaptor.QueryParams.UID.key(), panel.getUid()), options, userId); update.setResults(result.getResults()); } @@ -563,28 +572,31 @@ private OpenCGAResult update(Study study, Panel panel, PanelUpdateParams updateP } @Override - public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException { + public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); fixQueryObject(query); query.append(PanelDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - return panelDBAdaptor.iterator(study.getUid(), query, options, userId); + return getPanelDBAdaptor(organizationId).iterator(study.getUid(), query, options, userId); } @Override - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("query", new Query(query)) .append("options", options) @@ -593,7 +605,7 @@ public OpenCGAResult search(String organizationId, String studyId, Query try { fixQueryObject(query); query.append(PanelDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - OpenCGAResult result = panelDBAdaptor.get(study.getUid(), query, options, userId); + OpenCGAResult result = getPanelDBAdaptor(organizationId).get(study.getUid(), query, options, userId); auditManager.auditSearch(userId, Enums.Resource.DISEASE_PANEL, study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -606,13 +618,15 @@ public OpenCGAResult search(String organizationId, String studyId, Query } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("fields", fields) .append("query", new Query(query)) @@ -622,7 +636,7 @@ public OpenCGAResult distinct(String organizationId, String studyId, List result = panelDBAdaptor.distinct(study.getUid(), fields, query, userId); + OpenCGAResult result = getPanelDBAdaptor(organizationId).distinct(study.getUid(), fields, query, userId); auditManager.auditDistinct(userId, Enums.Resource.DISEASE_PANEL, study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -639,11 +653,12 @@ public OpenCGAResult distinct(String organizationId, String studyId, List count(String organizationId, String studyId, Query query, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("query", new Query(query)) .append("token", token); @@ -652,7 +667,7 @@ public OpenCGAResult count(String organizationId, String studyId, Query q query.append(PanelDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); // Here view permissions will be checked - OpenCGAResult queryResultAux = panelDBAdaptor.count(query, userId); + OpenCGAResult queryResultAux = getPanelDBAdaptor(organizationId).count(query, userId); auditManager.auditCount(userId, Enums.Resource.DISEASE_PANEL, study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -667,22 +682,24 @@ public OpenCGAResult count(String organizationId, String studyId, Query q } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List panelIds, QueryOptions options, String token) throws CatalogException { - return delete(studyStr, panelIds, options, false, token); + public OpenCGAResult delete(String organizationId, String studyStr, List panelIds, QueryOptions options, String token) + throws CatalogException { + return delete(organizationId, studyStr, panelIds, options, false, token); } - public OpenCGAResult delete(String studyStr, List panelIds, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List panelIds, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { if (panelIds == null || ListUtils.isEmpty(panelIds)) { throw new CatalogException("Missing list of panel ids"); } - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("panelIds", panelIds) .append("params", params) @@ -725,7 +742,7 @@ public OpenCGAResult delete(String studyStr, List panelIds, ObjectMap pa // TODO: Check if the panel is used in an interpretation. At this point, it can be deleted no matter what. // Delete the panel - result.append(panelDBAdaptor.delete(panel)); + result.append(getPanelDBAdaptor(organizationId).delete(panel)); auditManager.auditDelete(operationId, userId, Enums.Resource.DISEASE_PANEL, panel.getId(), panel.getUuid(), study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -745,21 +762,23 @@ public OpenCGAResult delete(String studyStr, List panelIds, ObjectMap pa } @Override - public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { - return delete(studyStr, query, options, false, token); + public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { + return delete(organizationId, studyStr, query, options, false, token); } - public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); OpenCGAResult result = OpenCGAResult.empty(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("query", new Query(query)) .append("params", params) @@ -775,7 +794,7 @@ public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, bool try { finalQuery.append(FamilyDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - iterator = panelDBAdaptor.iterator(study.getUid(), finalQuery, INCLUDE_PANEL_IDS, userId); + iterator = getPanelDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_PANEL_IDS, userId); // If the user is the owner or the admin, we won't check if he has permissions for every single entry checkPermissions = !authorizationManager.isOwnerOrAdmin(study.getUid(), userId); @@ -799,7 +818,7 @@ public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, bool // TODO: Check if the panel is used in an interpretation. At this point, it can be deleted no matter what. // Delete the panel - result.append(panelDBAdaptor.delete(panel)); + result.append(getPanelDBAdaptor(organizationId).delete(panel)); auditManager.auditDelete(operationId, userId, Enums.Resource.DISEASE_PANEL, panel.getId(), panel.getUuid(), study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -821,13 +840,13 @@ public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, bool } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); ParamUtils.checkObj(field, "field"); - ParamUtils.checkObj(sessionId, "sessionId"); + ParamUtils.checkObj(token, "token"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.VIEW_PANELS); @@ -840,46 +859,49 @@ public OpenCGAResult rank(String organizationId, String studyStr, Query query, S OpenCGAResult queryResult = null; if (count) { // We do not need to check for permissions when we show the count of files - queryResult = panelDBAdaptor.rank(query, field, numResults, asc); + queryResult = getPanelDBAdaptor(organizationId).rank(query, field, numResults, asc); } return ParamUtils.defaultObject(queryResult, OpenCGAResult::new); } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String sessionId) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); fixQueryObject(query); options = ParamUtils.defaultObject(options, QueryOptions::new); - if (fields == null || fields.size() == 0) { + if (CollectionUtils.isEmpty(fields)) { throw new CatalogException("Empty fields parameter."); } - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); // Add study id to the query query.put(PanelDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - OpenCGAResult queryResult = sampleDBAdaptor.groupBy(query, fields, options, userId); + OpenCGAResult queryResult = getSampleDBAdaptor(organizationId).groupBy(query, fields, options, userId); return ParamUtils.defaultObject(queryResult, OpenCGAResult::new); } // ************************** ACLs ******************************** // - public OpenCGAResult> getAcls(String studyId, List panelList, String member, - boolean ignoreException, String token) throws CatalogException { - return getAcls(studyId, panelList, StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), - ignoreException, token); + public OpenCGAResult> getAcls(String organizationId, String studyId, List panelList, + String member, boolean ignoreException, String token) + throws CatalogException { + return getAcls(organizationId, studyId, panelList, + StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), ignoreException, token); } - public OpenCGAResult> getAcls(String studyId, List panelList, List members, - boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + public OpenCGAResult> getAcls(String organizationId, String studyId, List panelList, + List members, boolean ignoreException, String token) + throws CatalogException { + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("panelList", panelList) .append("members", members) @@ -890,7 +912,8 @@ public OpenCGAResult> getAcls(String studyId, Lis Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), panelList, INCLUDE_PANEL_IDS, user, ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), panelList, INCLUDE_PANEL_IDS, user, + ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -952,14 +975,15 @@ public OpenCGAResult> getAcls(String studyId, Lis return panelAcls; } - public OpenCGAResult> updateAcl(String studyId, List panelStrList, + public OpenCGAResult> updateAcl(String organizationId, String studyId, List panelStrList, String memberList, AclParams aclParams, ParamUtils.AclAction action, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("panelStrList", panelStrList) .append("memberList", memberList) @@ -985,7 +1009,8 @@ public OpenCGAResult> updateAcl(String studyId, L checkPermissions(permissions, PanelPermissions::valueOf); } - OpenCGAResult panelDataResult = internalGet(organizationId, study.getUid(), panelStrList, INCLUDE_PANEL_IDS, user, false); + OpenCGAResult panelDataResult = internalGet(organizationId, study.getUid(), panelStrList, INCLUDE_PANEL_IDS, user, + false); authorizationManager.checkCanAssignOrSeePermissions(study.getUid(), user); // Validate that the members are actually valid members @@ -996,7 +1021,7 @@ public OpenCGAResult> updateAcl(String studyId, L members = Collections.emptyList(); } authorizationManager.checkNotAssigningPermissionsToAdminsGroup(members); - checkMembers(study.getUid(), members); + checkMembers(organizationId, study.getUid(), members); List panelUids = panelDataResult.getResults().stream().map(Panel::getUid).collect(Collectors.toList()); AuthorizationManager.CatalogAclParams catalogAclParams = new AuthorizationManager.CatalogAclParams(panelUids, permissions, diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ProjectManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ProjectManager.java index 868d21c0a6c..42046591f49 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ProjectManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ProjectManager.java @@ -92,7 +92,7 @@ public String getOwner(String organizationId, long projectId) throws CatalogExce /** * Fetch the project qualifying the projectStr structure as long as userId has permissions to see it. * - * @param organizationId + * @param organizationId Organization id. * @param projectStr string that can contain the full qualified name (owner@projectId) or just the projectId. * @param userId user asking for the project information. * @return a OpenCGAResult containing the project. @@ -197,16 +197,17 @@ private OpenCGAResult getProject(String organizationId, String userId, /** * Obtain the list of projects and studies that are shared with the user. * - * @param organizationId + * @param organizationId Organization id. * @param userId user whose projects and studies are being shared with. * @param queryOptions QueryOptions object. * @param sessionId Session id which should correspond to userId. * @return A OpenCGAResult object containing the list of projects and studies that are shared with the user. * @throws CatalogException CatalogException */ - public OpenCGAResult getSharedProjects(String organizationId, String userId, QueryOptions queryOptions, String sessionId) throws CatalogException { - OpenCGAResult result = search(organizationId, new Query(ProjectDBAdaptor.QueryParams.USER_ID.key(), "!=" + userId), queryOptions, - sessionId); + public OpenCGAResult getSharedProjects(String organizationId, String userId, QueryOptions queryOptions, String sessionId) + throws CatalogException { + OpenCGAResult result = search(organizationId, new Query(ProjectDBAdaptor.QueryParams.USER_ID.key(), "!=" + userId), + queryOptions, sessionId); for (Event event : result.getEvents()) { if (event.getType() == Event.Type.ERROR) { throw new CatalogAuthorizationException(event.getMessage()); @@ -216,8 +217,9 @@ public OpenCGAResult getSharedProjects(String organizationId, String us } @Deprecated - public OpenCGAResult create(String id, String name, String description, String scientificName, String commonName, - String assembly, QueryOptions options, String sessionId) throws CatalogException { + public OpenCGAResult create(String organizationId, String id, String name, String description, String scientificName, + String commonName, String assembly, QueryOptions options, String sessionId) + throws CatalogException { ProjectCreateParams projectCreateParams = new ProjectCreateParams(id, name, description, null, null, new ProjectOrganism(scientificName, commonName, assembly), null, null); return create(organizationId, projectCreateParams, options, sessionId); @@ -334,7 +336,7 @@ private void validateProjectForCreation(Project project) throws CatalogParameter * @throws CatalogException CatalogException */ public OpenCGAResult get(String organizationId, String projectId, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); ObjectMap auditParams = new ObjectMap() .append("organizationId", organizationId) @@ -354,14 +356,14 @@ public OpenCGAResult get(String organizationId, String projectId, Query } } - public OpenCGAResult get(String organizationId, List projectList, QueryOptions options, boolean ignoreException, String sessionId) - throws CatalogException { + public OpenCGAResult get(String organizationId, List projectList, QueryOptions options, boolean ignoreException, + String token) throws CatalogException { OpenCGAResult result = OpenCGAResult.empty(); for (int i = 0; i < projectList.size(); i++) { String project = projectList.get(i); try { - OpenCGAResult projectResult = get(organizationId, project, options, sessionId); + OpenCGAResult projectResult = get(organizationId, project, options, token); result.append(projectResult); } catch (CatalogException e) { Event event = new Event(Event.Type.ERROR, projectList.get(i), e.getMessage()); @@ -391,7 +393,7 @@ public OpenCGAResult get(String organizationId, List projectLis public OpenCGAResult search(String organizationId, Query query, QueryOptions options, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); query = new Query(query); ObjectMap auditParams = new ObjectMap() @@ -425,7 +427,7 @@ public OpenCGAResult search(String organizationId, Query query, QueryOp /** * Update metada from projects. * - * @param organizationId + * @param organizationId Organization id. * @param projectId Project id or alias. * @param parameters Parameters to change. * @param options options @@ -452,7 +454,7 @@ public OpenCGAResult update(String organizationId, String projectId, Ob */ private OpenCGAResult update(String organizationId, String projectId, ObjectMap parameters, QueryOptions options, boolean allowProtectedUpdates, String token) throws CatalogException { - String userId = this.catalogManager.getUserManager().getUserId(token); + String userId = this.catalogManager.getUserManager().getUserId(organizationId, token); ObjectMap auditParams = new ObjectMap() .append("organizationId", organizationId) @@ -536,8 +538,8 @@ private OpenCGAResult update(String organizationId, String projectId, O if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated project - OpenCGAResult result = getProjectDBAdaptor(organizationId).get(new Query(ProjectDBAdaptor.QueryParams.UID.key(), projectUid), options, - userId); + OpenCGAResult result = getProjectDBAdaptor(organizationId) + .get(new Query(ProjectDBAdaptor.QueryParams.UID.key(), projectUid), options, userId); update.setResults(result.getResults()); } @@ -573,23 +575,24 @@ public OpenCGAResult setCellbaseConfiguration(String organizationId, St public Map facet(String organizationId, String projectStr, String fileFields, String sampleFields, String individualFields, String cohortFields, String familyFields, String jobFields, boolean defaultStats, String token) throws CatalogException, IOException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Project project = resolveId(organizationId, projectStr, userId); Query query = new Query(StudyDBAdaptor.QueryParams.PROJECT_UID.key(), project.getUid()); - OpenCGAResult studyDataResult = catalogManager.getStudyManager().search(organizationId, query, new QueryOptions(QueryOptions.INCLUDE, - Arrays.asList(StudyDBAdaptor.QueryParams.FQN.key(), StudyDBAdaptor.QueryParams.ID.key())), token); + OpenCGAResult studyDataResult = catalogManager.getStudyManager().search(organizationId, query, + new QueryOptions(QueryOptions.INCLUDE, + Arrays.asList(StudyDBAdaptor.QueryParams.FQN.key(), StudyDBAdaptor.QueryParams.ID.key())), token); Map result = new HashMap<>(); for (Study study : studyDataResult.getResults()) { - result.put(study.getId(), catalogManager.getStudyManager().facet(organizationId, study.getFqn(), fileFields, sampleFields, individualFields, - cohortFields, familyFields, jobFields, defaultStats, token)); + result.put(study.getId(), catalogManager.getStudyManager().facet(organizationId, study.getFqn(), fileFields, sampleFields, + individualFields, cohortFields, familyFields, jobFields, defaultStats, token)); } return result; } public OpenCGAResult incrementRelease(String organizationId, String projectStr, String sessionId) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); try { Project project = resolveId(organizationId, projectStr, userId); @@ -640,7 +643,7 @@ public OpenCGAResult incrementRelease(String organizationId, String pro public void importReleases(String organizationId, String owner, String inputDirStr, String sessionId) throws CatalogException, IOException { - String userId = catalogManager.getUserManager().getUserId(sessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); if (!authorizationManager.isInstallationAdministrator(userId)) { throw new CatalogAuthorizationException("Only admin of OpenCGA is authorised to import data"); } @@ -757,7 +760,7 @@ public void importReleases(String organizationId, String owner, String inputDirS public void exportByFileNames(String organizationId, String studyStr, File outputDir, File filePath, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); if (!authorizationManager.isInstallationAdministrator(userId)) { throw new CatalogAuthorizationException("Only admin of OpenCGA is authorised to export data"); } @@ -787,7 +790,7 @@ public void exportByFileNames(String organizationId, String studyStr, File outpu String owner = studyDataResult.first().getFqn().split("@")[0]; - String ownerToken = catalogManager.getUserManager().getNonExpiringToken(owner, Collections.emptyMap(), token); + String ownerToken = catalogManager.getUserManager().getNonExpiringToken(organizationId, owner, Collections.emptyMap(), token); try (BufferedReader buf = new BufferedReader(new FileReader(filePath))) { @@ -942,7 +945,7 @@ private void exportToFile(List dataList, File file, ObjectMapper objectM public void exportReleases(String organizationId, String projectStr, int release, String outputDirStr, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); if (!authorizationManager.isInstallationAdministrator(userId)) { throw new CatalogAuthorizationException("Only admin of OpenCGA is authorised to export data"); } @@ -1084,7 +1087,7 @@ public OpenCGAResult rank(String organizationId, String userId, Query query, Str ParamUtils.checkObj(userId, "userId"); ParamUtils.checkObj(token, "sessionId"); - String userOfQuery = this.catalogManager.getUserManager().getUserId(token); + String userOfQuery = this.catalogManager.getUserManager().getUserId(organizationId, token); if (!userOfQuery.equals(userId)) { // The user cannot read projects of other users. throw CatalogAuthorizationException.cantRead(userOfQuery, "Project", null, userId); @@ -1110,7 +1113,7 @@ public OpenCGAResult groupBy(String organizationId, String userId, Query query, ParamUtils.checkObj(userId, "userId"); ParamUtils.checkObj(token, "sessionId"); - String userOfQuery = this.catalogManager.getUserManager().getUserId(token); + String userOfQuery = this.catalogManager.getUserManager().getUserId(organizationId, token); if (!userOfQuery.equals(userId)) { // The user cannot read projects of other users. throw CatalogAuthorizationException.cantRead(userOfQuery, "Project", null, userId); @@ -1135,7 +1138,7 @@ public OpenCGAResult groupBy(String organizationId, String userId, Query query, ParamUtils.checkObj(userId, "userId"); ParamUtils.checkObj(token, "sessionId"); - String userOfQuery = this.catalogManager.getUserManager().getUserId(token); + String userOfQuery = this.catalogManager.getUserManager().getUserId(organizationId, token); if (!userOfQuery.equals(userId)) { // The user cannot read projects of other users. throw CatalogAuthorizationException.cantRead(userOfQuery, "Project", null, userId); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ResourceManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ResourceManager.java index a9dac803033..2e3b2b40d5b 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ResourceManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/ResourceManager.java @@ -53,7 +53,8 @@ public abstract class ResourceManager extends Abstra abstract Enums.Resource getEntity(); - OpenCGAResult internalGet(String organizationId, long studyUid, String entry, QueryOptions options, String user) throws CatalogException { + OpenCGAResult internalGet(String organizationId, long studyUid, String entry, QueryOptions options, String user) + throws CatalogException { return internalGet(organizationId, studyUid, entry, null, options, user); } @@ -75,7 +76,7 @@ abstract InternalGetDataResult internalGet(String organizationId, long studyU * Create an entry in catalog. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param entry entry that needs to be added in Catalog. * @param options QueryOptions object. * @param token Session id of the user logged in. @@ -89,7 +90,7 @@ public abstract OpenCGAResult create(String organizationId, String studyStr, * Fetch the R object. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param entryStr Entry id to be fetched. * @param options QueryOptions object, like "include", "exclude", "limit" and "skip". * @param token token @@ -98,7 +99,7 @@ public abstract OpenCGAResult create(String organizationId, String studyStr, */ public OpenCGAResult get(String organizationId, String studyStr, String entryStr, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); return internalGet(organizationId, study.getUid(), entryStr, options, userId); } @@ -107,7 +108,7 @@ public OpenCGAResult get(String organizationId, String studyStr, String entry * Fetch all the R objects matching the query. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param entryList Comma separated list of entries to be fetched. * @param options QueryOptions object, like "include", "exclude", "limit" and "skip". * @param token token @@ -119,14 +120,14 @@ public OpenCGAResult get(String organizationId, String studyStr, List return get(organizationId, studyStr, entryList, new Query(), options, false, token); } - public OpenCGAResult get(String organizationId, String studyStr, List entryList, QueryOptions options, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult get(String organizationId, String studyStr, List entryList, QueryOptions options, + boolean ignoreException, String token) throws CatalogException { return get(organizationId, studyStr, entryList, new Query(), options, ignoreException, token); } public OpenCGAResult get(String organizationId, String studyId, List entryList, Query query, QueryOptions options, boolean ignoreException, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId); query = ParamUtils.defaultObject(query, Query::new); @@ -147,7 +148,8 @@ public OpenCGAResult get(String organizationId, String studyId, List OpenCGAResult result = OpenCGAResult.empty(); options.remove(QueryOptions.LIMIT); - InternalGetDataResult responseResult = internalGet(organizationId, study.getUid(), entryList, query, options, userId, ignoreException); + InternalGetDataResult responseResult = internalGet(organizationId, study.getUid(), entryList, query, options, userId, + ignoreException); Map missingMap = new HashMap<>(); if (responseResult.getMissing() != null) { @@ -192,7 +194,7 @@ public OpenCGAResult get(String organizationId, String studyId, List * Obtain an entry iterator to iterate over the matching entries. * * @param organizationId Organization id. - * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object. * @param options QueryOptions object. * @param token Session id of the user logged in. @@ -206,7 +208,7 @@ public abstract DBIterator iterator(String organizationId, String studyStr, Q * Search of entries in catalog. * * @param organizationId Organization id. - * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object. * @param options QueryOptions object. * @param token Session id of the user logged in. @@ -219,8 +221,8 @@ public abstract OpenCGAResult search(String organizationId, String studyId, Q /** * Fetch a list containing all the distinct values of the key {@code field}. * - * @param organizationId - * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param organizationId Organization id. + * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param field The field for which to return distinct values. * @param query Query object. * @param token Token of the user logged in. @@ -236,7 +238,7 @@ public OpenCGAResult distinct(String organizationId, String studyId, String f * Fetch a list containing all the distinct values of the key {@code field}. * * @param organizationId Organization id. - * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param fields Fields for which to return distinct values. * @param query Query object. * @param token Token of the user logged in. @@ -250,7 +252,7 @@ public abstract OpenCGAResult distinct(String organizationId, String studyId, * Count matching entries in catalog. * * @param organizationId Organization id. - * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyId study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object. * @param token Session id of the user logged in. * @return A OpenCGAResult with the total number of entries matching the query. @@ -265,7 +267,7 @@ public abstract OpenCGAResult delete(String organizationId, String studyStr, Lis * Delete all entries matching the query. * * @param organizationId Organization id. - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object. * @param options Map containing additional parameters to be considered for the deletion. * @param token Session id of the user logged in. @@ -279,7 +281,7 @@ public abstract OpenCGAResult delete(String organizationId, String studyStr, Que * Ranks the elements queried, groups them by the field(s) given and return it sorted. * * @param organizationId Organization id. - * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object containing the query that will be executed. * @param field A field or a comma separated list of fields by which the results will be grouped in. * @param numResults Maximum number of results to be reported. @@ -295,7 +297,7 @@ public abstract OpenCGAResult rank(String organizationId, String studyStr, Query * Groups the matching entries by some fields. * * @param organizationId Organization id. - * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object. * @param fields A field or a comma separated list of fields by which the results will be grouped in. * @param options QueryOptions object. @@ -315,7 +317,7 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Q * Groups the matching entries by some fields. * * @param organizationId Organization id. - * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. + * @param studyStr study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] * @param query Query object. * @param fields A field or a comma separated list of fields by which the results will be grouped in. * @param options QueryOptions object. diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/SampleManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/SampleManager.java index 3016e647e5f..c4a2a8a1727 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/SampleManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/SampleManager.java @@ -98,8 +98,8 @@ Enums.Resource getEntity() { } @Override - InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, QueryOptions options, - String user, boolean ignoreException) throws CatalogException { + InternalGetDataResult internalGet(String organizationId, long studyUid, List entryList, @Nullable Query query, + QueryOptions options, String user, boolean ignoreException) throws CatalogException { if (ListUtils.isEmpty(entryList)) { throw new CatalogException("Missing sample entries."); } @@ -122,7 +122,7 @@ InternalGetDataResult internalGet(String organizationId, long studyUid, // Ensure the field by which we are querying for will be kept in the results queryOptions = keepFieldInQueryOptions(queryOptions, idQueryParam.key()); - OpenCGAResult sampleDataResult = sampleDBAdaptor.get(studyUid, queryCopy, queryOptions, user); + OpenCGAResult sampleDataResult = getSampleDBAdaptor(organizationId).get(studyUid, queryCopy, queryOptions, user); Function sampleStringFunction = Sample::getId; if (idQueryParam.equals(SampleDBAdaptor.QueryParams.UUID)) { @@ -133,7 +133,7 @@ InternalGetDataResult internalGet(String organizationId, long studyUid, return keepOriginalOrder(uniqueList, sampleStringFunction, sampleDataResult, ignoreException, versioned); } // Query without adding the user check - OpenCGAResult resultsNoCheck = sampleDBAdaptor.get(queryCopy, queryOptions); + OpenCGAResult resultsNoCheck = getSampleDBAdaptor(organizationId).get(queryCopy, queryOptions); if (resultsNoCheck.getNumResults() == sampleDataResult.getNumResults()) { throw CatalogException.notFound("samples", getMissingFields(uniqueList, sampleDataResult.getResults(), sampleStringFunction)); @@ -159,28 +159,29 @@ SampleDBAdaptor.QueryParams getFieldFilter(List idList) throws CatalogEx return idQueryParam; } - private OpenCGAResult getSample(long studyUid, String sampleUuid, QueryOptions options) throws CatalogException { + private OpenCGAResult getSample(String organizationId, long studyUid, String sampleUuid, QueryOptions options) + throws CatalogException { Query query = new Query() .append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), studyUid) .append(SampleDBAdaptor.QueryParams.UUID.key(), sampleUuid); - return sampleDBAdaptor.get(query, options); + return getSampleDBAdaptor(organizationId).get(query, options); } - void validateNewSample(Study study, Sample sample, String userId) throws CatalogException { + void validateNewSample(String organizationId, Study study, Sample sample, String userId) throws CatalogException { ParamUtils.checkIdentifier(sample.getId(), "id"); // Check the id is not in use Query query = new Query() .append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()) .append(SampleDBAdaptor.QueryParams.ID.key(), sample.getId()); - if (sampleDBAdaptor.count(query).getNumMatches() > 0) { + if (getSampleDBAdaptor(organizationId).count(query).getNumMatches() > 0) { throw new CatalogException("Sample '" + sample.getId() + "' already exists."); } if (StringUtils.isNotEmpty(sample.getIndividualId())) { // Check individual exists - OpenCGAResult individualDataResult = catalogManager.getIndividualManager().internalGet(organizationId, study.getUid(), - sample.getIndividualId(), IndividualManager.INCLUDE_INDIVIDUAL_IDS, userId); + OpenCGAResult individualDataResult = catalogManager.getIndividualManager().internalGet(organizationId, + study.getUid(), sample.getIndividualId(), IndividualManager.INCLUDE_INDIVIDUAL_IDS, userId); if (individualDataResult.getNumResults() == 0) { throw new CatalogException("Individual '" + sample.getIndividualId() + "' not found."); } @@ -216,20 +217,22 @@ void validateNewSample(Study study, Sample sample, String userId) throws Catalog sample.setAnnotationSets(ParamUtils.defaultObject(sample.getAnnotationSets(), Collections.emptyList())); sample.setUuid(UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.SAMPLE)); - sample.setRelease(studyManager.getCurrentRelease(study)); + sample.setRelease(studyManager.getCurrentRelease(organizationId, study)); sample.setVersion(1); validateNewAnnotationSets(study.getVariableSets(), sample.getAnnotationSets()); } @Override - public OpenCGAResult create(String organizationId, String studyStr, Sample sample, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult create(String organizationId, String studyStr, Sample sample, QueryOptions options, String token) + throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("sample", sample) .append("options", options) @@ -238,13 +241,14 @@ public OpenCGAResult create(String organizationId, String studyStr, Samp // 1. We check everything can be done authorizationManager.checkStudyPermission(study.getUid(), userId, StudyPermissions.Permissions.WRITE_SAMPLES); - validateNewSample(study, sample, userId); + validateNewSample(organizationId, study, sample, userId); // We create the sample - OpenCGAResult insert = sampleDBAdaptor.insert(study.getUid(), sample, study.getVariableSets(), options); + OpenCGAResult insert = getSampleDBAdaptor(organizationId).insert(study.getUid(), sample, study.getVariableSets(), + options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch created sample - OpenCGAResult result = getSample(study.getUid(), sample.getUuid(), options); + OpenCGAResult result = getSample(organizationId, study.getUid(), sample.getUuid(), options); insert.setResults(result.getResults()); } auditManager.auditCreate(userId, Enums.Resource.SAMPLE, sample.getId(), sample.getUuid(), study.getId(), study.getUuid(), @@ -258,42 +262,45 @@ public OpenCGAResult create(String organizationId, String studyStr, Samp } @Override - public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String sessionId) throws CatalogException { + public DBIterator iterator(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); Query finalQuery = new Query(query); - fixQueryObject(study, finalQuery, userId); + fixQueryObject(organizationId, study, finalQuery, userId); AnnotationUtils.fixQueryOptionAnnotation(options); finalQuery.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - return sampleDBAdaptor.iterator(study.getUid(), finalQuery, options, userId); + return getSampleDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, options, userId); } @Override - public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult search(String organizationId, String studyId, Query query, QueryOptions options, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("query", new Query(query)) .append("options", options) .append("token", token); try { - fixQueryObject(study, query, userId); + fixQueryObject(organizationId, study, query, userId); AnnotationUtils.fixQueryOptionAnnotation(options); query.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - OpenCGAResult queryResult = sampleDBAdaptor.get(study.getUid(), query, options, userId); + OpenCGAResult queryResult = getSampleDBAdaptor(organizationId).get(study.getUid(), query, options, userId); auditManager.auditSearch(userId, Enums.Resource.SAMPLE, study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -307,23 +314,25 @@ public OpenCGAResult search(String organizationId, String studyId, Query } @Override - public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) throws CatalogException { + public OpenCGAResult distinct(String organizationId, String studyId, List fields, Query query, String token) + throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("fields", fields) .append("query", new Query(query)) .append("token", token); try { - fixQueryObject(study, query, userId); + fixQueryObject(organizationId, study, query, userId); query.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - OpenCGAResult result = sampleDBAdaptor.distinct(study.getUid(), fields, query, userId); + OpenCGAResult result = getSampleDBAdaptor(organizationId).distinct(study.getUid(), fields, query, userId); auditManager.auditDistinct(userId, Enums.Resource.SAMPLE, study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -336,7 +345,7 @@ public OpenCGAResult distinct(String organizationId, String studyId, List count(String organizationId, String studyId, Query query, String token) throws CatalogException { - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); query = new Query(ParamUtils.defaultObject(query, Query::new)); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("query", query) .append("token", token); try { - fixQueryObject(study, query, userId); + fixQueryObject(organizationId, study, query, userId); query.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - OpenCGAResult queryResultAux = sampleDBAdaptor.count(query, userId); + OpenCGAResult queryResultAux = getSampleDBAdaptor(organizationId).count(query, userId); auditManager.auditCount(userId, Enums.Resource.SAMPLE, study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -446,23 +456,25 @@ public OpenCGAResult count(String organizationId, String studyId, Query } @Override - public OpenCGAResult delete(String organizationId, String studyStr, List sampleIds, QueryOptions options, String token) throws CatalogException { - return delete(studyStr, sampleIds, options, false, token); + public OpenCGAResult delete(String organizationId, String studyStr, List sampleIds, QueryOptions options, String token) + throws CatalogException { + return delete(organizationId, studyStr, sampleIds, options, false, token); } - public OpenCGAResult delete(String studyStr, List sampleIds, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, List sampleIds, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { if (sampleIds == null || ListUtils.isEmpty(sampleIds)) { throw new CatalogException("Missing list of sample ids"); } - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, new QueryOptions(QueryOptions.INCLUDE, StudyDBAdaptor.QueryParams.VARIABLE_SET.key())); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("sampleIds", sampleIds) .append("params", params) @@ -501,9 +513,9 @@ public OpenCGAResult delete(String studyStr, List sampleIds, ObjectMap p } // Check if the sample can be deleted - checkSampleCanBeDeleted(study.getUid(), sample, params.getBoolean(Constants.FORCE, false)); + checkSampleCanBeDeleted(organizationId, study.getUid(), sample, params.getBoolean(Constants.FORCE, false)); - result.append(sampleDBAdaptor.delete(sample)); + result.append(getSampleDBAdaptor(organizationId).delete(sample)); auditManager.auditDelete(operationId, userId, Enums.Resource.SAMPLE, sample.getId(), sample.getUuid(), study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -525,23 +537,25 @@ public OpenCGAResult delete(String studyStr, List sampleIds, ObjectMap p } @Override - public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { - return delete(studyStr, query, options, false, token); + public OpenCGAResult delete(String organizationId, String studyStr, Query query, QueryOptions options, String token) + throws CatalogException { + return delete(organizationId, studyStr, query, options, false, token); } - public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, boolean ignoreException, String token) - throws CatalogException { + public OpenCGAResult delete(String organizationId, String studyStr, Query query, ObjectMap params, boolean ignoreException, + String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); params = ParamUtils.defaultObject(params, ObjectMap::new); OpenCGAResult result = OpenCGAResult.empty(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationUuid = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("query", new Query(query)) .append("params", params) @@ -567,10 +581,10 @@ public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, bool // params.put(Constants.EMPTY_FILES_ACTION, "NONE"); // } - fixQueryObject(study, finalQuery, userId); + fixQueryObject(organizationId, study, finalQuery, userId); finalQuery.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - iterator = sampleDBAdaptor.iterator(study.getUid(), finalQuery, INCLUDE_SAMPLE_IDS, userId); + iterator = getSampleDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_SAMPLE_IDS, userId); // If the user is the owner or the admin, we won't check if he has permissions for every single entry checkPermissions = !authorizationManager.isOwnerOrAdmin(study.getUid(), userId); @@ -591,9 +605,9 @@ public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, bool } // Check if the sample can be deleted - checkSampleCanBeDeleted(study.getUid(), sample, params.getBoolean(Constants.FORCE, false)); + checkSampleCanBeDeleted(organizationId, study.getUid(), sample, params.getBoolean(Constants.FORCE, false)); - result.append(sampleDBAdaptor.delete(sample)); + result.append(getSampleDBAdaptor(organizationId).delete(sample)); auditManager.auditDelete(operationUuid, userId, Enums.Resource.SAMPLE, sample.getId(), sample.getUuid(), study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -615,8 +629,8 @@ public OpenCGAResult delete(String studyStr, Query query, ObjectMap params, bool } // TODO: This method should be private. This should only be accessible internally. - public OpenCGAResult resetRgaIndexes(String studyStr, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + public OpenCGAResult resetRgaIndexes(String organizationId, String studyStr, String token) throws CatalogException { + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -626,7 +640,8 @@ public OpenCGAResult resetRgaIndexes(String studyStr, String token) thro OpenCGAResult result; try { authorizationManager.isOwnerOrAdmin(study.getUid(), userId); - result = sampleDBAdaptor.setRgaIndexes(study.getUid(), new RgaIndex(RgaIndex.Status.NOT_INDEXED, TimeUtils.getTime())); + result = getSampleDBAdaptor(organizationId).setRgaIndexes(study.getUid(), new RgaIndex(RgaIndex.Status.NOT_INDEXED, + TimeUtils.getTime())); auditManager.audit(userId, Enums.Action.RESET_RGA_INDEXES, Enums.Resource.SAMPLE, "ALL", "", study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -640,12 +655,13 @@ public OpenCGAResult resetRgaIndexes(String studyStr, String token) thro } // TODO: This method should be somehow private. This should only be accessible internally. - public OpenCGAResult updateRgaIndexes(String studyStr, List samples, RgaIndex rgaIndex, String token) - throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + public OpenCGAResult updateRgaIndexes(String organizationId, String studyStr, List samples, RgaIndex rgaIndex, + String token) throws CatalogException { + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("samples", samples) .append("rgaIndex", rgaIndex) @@ -667,7 +683,7 @@ public OpenCGAResult updateRgaIndexes(String studyStr, List samp rgaIndex.setDate(TimeUtils.getTime()); sampleResult = internalGet(organizationId, study.getUid(), samples, INCLUDE_SAMPLE_IDS, userId, false); - result = sampleDBAdaptor.setRgaIndexes(study.getUid(), + result = getSampleDBAdaptor(organizationId).setRgaIndexes(study.getUid(), sampleResult.getResults().stream().map(Sample::getUid).collect(Collectors.toList()), rgaIndex); for (Sample sample : sampleResult.getResults()) { @@ -694,41 +710,44 @@ public OpenCGAResult updateRgaIndexes(String studyStr, List samp return result; } - public OpenCGAResult updateSampleInternalVariantIndex(Sample sample, SampleInternalVariantIndex index, String token) - throws CatalogException { - return updateSampleInternalVariant(sample, index, SampleDBAdaptor.QueryParams.INTERNAL_VARIANT_INDEX.key(), token); + public OpenCGAResult updateSampleInternalVariantIndex(String organizationId, Sample sample, SampleInternalVariantIndex index, + String token) throws CatalogException { + return updateSampleInternalVariant(organizationId, sample, index, SampleDBAdaptor.QueryParams.INTERNAL_VARIANT_INDEX.key(), token); } - public OpenCGAResult updateSampleInternalVariantSecondarySampleIndex( - Sample sample, SampleInternalVariantSecondarySampleIndex index, String token) + public OpenCGAResult updateSampleInternalVariantSecondarySampleIndex(String organizationId, Sample sample, + SampleInternalVariantSecondarySampleIndex index, String token) throws CatalogException { - return updateSampleInternalVariant(sample, index, Arrays.asList( + return updateSampleInternalVariant(organizationId, sample, index, Arrays.asList( SampleDBAdaptor.QueryParams.INTERNAL_VARIANT_SECONDARY_SAMPLE_INDEX.key(), SampleDBAdaptor.QueryParams.INTERNAL_VARIANT_GENOTYPE_INDEX.key()), token); } public OpenCGAResult updateSampleInternalVariantAnnotationIndex( - Sample sample, SampleInternalVariantAnnotationIndex index, String token) throws CatalogException { - return updateSampleInternalVariant(sample, index, SampleDBAdaptor.QueryParams.INTERNAL_VARIANT_ANNOTATION_INDEX.key(), token); + String organizationId, Sample sample, SampleInternalVariantAnnotationIndex index, String token) throws CatalogException { + return updateSampleInternalVariant(organizationId, sample, index, + SampleDBAdaptor.QueryParams.INTERNAL_VARIANT_ANNOTATION_INDEX.key(), token); } public OpenCGAResult updateSampleInternalVariantSecondaryAnnotationIndex( - Sample sample, SampleInternalVariantSecondaryAnnotationIndex index, String token) throws CatalogException { - return updateSampleInternalVariant(sample, index, + String organizationId, Sample sample, SampleInternalVariantSecondaryAnnotationIndex index, String token) + throws CatalogException { + return updateSampleInternalVariant(organizationId, sample, index, SampleDBAdaptor.QueryParams.INTERNAL_VARIANT_SECONDARY_ANNOTATION_INDEX.key(), token); } - private OpenCGAResult updateSampleInternalVariant(Sample sample, Object value, String fieldKey, String token) + private OpenCGAResult updateSampleInternalVariant(String organizationId, Sample sample, Object value, String fieldKey, String token) throws CatalogException { - return updateSampleInternalVariant(sample, value, Collections.singletonList(fieldKey), token); + return updateSampleInternalVariant(organizationId, sample, value, Collections.singletonList(fieldKey), token); } - private OpenCGAResult updateSampleInternalVariant(Sample sample, Object value, List fieldKeys, String token) - throws CatalogException { - String userId = userManager.getUserId(token); - Study study = studyDBAdaptor.get(sample.getStudyUid(), StudyManager.INCLUDE_STUDY_IDS).first(); + private OpenCGAResult updateSampleInternalVariant(String organizationId, Sample sample, Object value, List fieldKeys, + String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); + Study study = getStudyDBAdaptor(organizationId).get(sample.getStudyUid(), StudyManager.INCLUDE_STUDY_IDS).first(); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("sample", sample.getId()) .append("token", token); for (String fieldKey : fieldKeys) { @@ -747,48 +766,52 @@ private OpenCGAResult updateSampleInternalVariant(Sample sample, Object value } catch (JsonProcessingException e) { throw new CatalogException("Cannot parse SampleInternalVariant object: " + e.getMessage(), e); } - OpenCGAResult update = sampleDBAdaptor.update(sample.getUid(), params, QueryOptions.empty()); + OpenCGAResult update = getSampleDBAdaptor(organizationId).update(sample.getUid(), params, QueryOptions.empty()); auditManager.audit(userId, Enums.Action.UPDATE_INTERNAL, Enums.Resource.SAMPLE, sample.getId(), sample.getUuid(), study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); return new OpenCGAResult<>(update.getTime(), update.getEvents(), 1, Collections.emptyList(), 1); } - public OpenCGAResult updateAnnotationSet(String studyStr, String sampleStr, List annotationSetList, - ParamUtils.BasicUpdateAction action, QueryOptions options, String token) - throws CatalogException { + public OpenCGAResult updateAnnotationSet(String organizationId, String studyStr, String sampleStr, + List annotationSetList, ParamUtils.BasicUpdateAction action, + QueryOptions options, String token) throws CatalogException { SampleUpdateParams sampleUpdateParams = new SampleUpdateParams().setAnnotationSets(annotationSetList); options = ParamUtils.defaultObject(options, QueryOptions::new); options.put(Constants.ACTIONS, new ObjectMap(AnnotationSetManager.ANNOTATION_SETS, action)); - return update(studyStr, sampleStr, sampleUpdateParams, options, token); + return update(organizationId, studyStr, sampleStr, sampleUpdateParams, options, token); } - public OpenCGAResult addAnnotationSet(String studyStr, String sampleStr, AnnotationSet annotationSet, QueryOptions options, - String token) throws CatalogException { - return addAnnotationSets(studyStr, sampleStr, Collections.singletonList(annotationSet), options, token); + public OpenCGAResult addAnnotationSet(String organizationId, String studyStr, String sampleStr, AnnotationSet annotationSet, + QueryOptions options, String token) throws CatalogException { + return addAnnotationSets(organizationId, studyStr, sampleStr, Collections.singletonList(annotationSet), options, token); } - public OpenCGAResult addAnnotationSets(String studyStr, String sampleStr, List annotationSetList, - QueryOptions options, String token) throws CatalogException { - return updateAnnotationSet(studyStr, sampleStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, token); + public OpenCGAResult addAnnotationSets(String organizationId, String studyStr, String sampleStr, + List annotationSetList, QueryOptions options, String token) + throws CatalogException { + return updateAnnotationSet(organizationId, studyStr, sampleStr, annotationSetList, ParamUtils.BasicUpdateAction.ADD, options, + token); } - public OpenCGAResult removeAnnotationSet(String studyStr, String sampleStr, String annotationSetId, QueryOptions options, - String token) throws CatalogException { - return removeAnnotationSets(studyStr, sampleStr, Collections.singletonList(annotationSetId), options, token); + public OpenCGAResult removeAnnotationSet(String organizationId, String studyStr, String sampleStr, String annotationSetId, + QueryOptions options, String token) throws CatalogException { + return removeAnnotationSets(organizationId, studyStr, sampleStr, Collections.singletonList(annotationSetId), options, token); } - public OpenCGAResult removeAnnotationSets(String studyStr, String sampleStr, List annotationSetIdList, - QueryOptions options, String token) throws CatalogException { + public OpenCGAResult removeAnnotationSets(String organizationId, String studyStr, String sampleStr, + List annotationSetIdList, QueryOptions options, String token) + throws CatalogException { List annotationSetList = annotationSetIdList .stream() .map(id -> new AnnotationSet().setId(id)) .collect(Collectors.toList()); - return updateAnnotationSet(studyStr, sampleStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, token); + return updateAnnotationSet(organizationId, studyStr, sampleStr, annotationSetList, ParamUtils.BasicUpdateAction.REMOVE, options, + token); } - public OpenCGAResult updateAnnotations(String studyStr, String sampleStr, String annotationSetId, + public OpenCGAResult updateAnnotations(String organizationId, String studyStr, String sampleStr, String annotationSetId, Map annotations, ParamUtils.CompleteUpdateAction action, QueryOptions options, String token) throws CatalogException { if (annotations == null || annotations.isEmpty()) { @@ -799,27 +822,27 @@ public OpenCGAResult updateAnnotations(String studyStr, String sampleStr options = ParamUtils.defaultObject(options, QueryOptions::new); options.put(Constants.ACTIONS, new ObjectMap(AnnotationSetManager.ANNOTATIONS, action)); - return update(studyStr, sampleStr, sampleUpdateParams, options, token); + return update(organizationId, studyStr, sampleStr, sampleUpdateParams, options, token); } - public OpenCGAResult removeAnnotations(String studyStr, String sampleStr, String annotationSetId, List annotations, - QueryOptions options, String token) throws CatalogException { - return updateAnnotations(studyStr, sampleStr, annotationSetId, new ObjectMap("remove", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.REMOVE, options, token); + public OpenCGAResult removeAnnotations(String organizationId, String studyStr, String sampleStr, String annotationSetId, + List annotations, QueryOptions options, String token) throws CatalogException { + return updateAnnotations(organizationId, studyStr, sampleStr, annotationSetId, + new ObjectMap("remove", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.REMOVE, options, token); } - public OpenCGAResult resetAnnotations(String studyStr, String sampleStr, String annotationSetId, List annotations, - QueryOptions options, String token) throws CatalogException { - return updateAnnotations(studyStr, sampleStr, annotationSetId, new ObjectMap("reset", StringUtils.join(annotations, ",")), - ParamUtils.CompleteUpdateAction.RESET, options, token); + public OpenCGAResult resetAnnotations(String organizationId, String studyStr, String sampleStr, String annotationSetId, + List annotations, QueryOptions options, String token) throws CatalogException { + return updateAnnotations(organizationId, studyStr, sampleStr, annotationSetId, + new ObjectMap("reset", StringUtils.join(annotations, ",")), ParamUtils.CompleteUpdateAction.RESET, options, token); } - private void checkSampleCanBeDeleted(long studyId, Sample sample, boolean force) throws CatalogException { + private void checkSampleCanBeDeleted(String organizationId, long studyId, Sample sample, boolean force) throws CatalogException { // Look for files related with the sample Query query = new Query() .append(FileDBAdaptor.QueryParams.SAMPLE_IDS.key(), sample.getId()) .append(FileDBAdaptor.QueryParams.STUDY_UID.key(), studyId); - DBIterator fileIterator = fileDBAdaptor.iterator(query, QueryOptions.empty()); + DBIterator fileIterator = getFileDBAdaptor(organizationId).iterator(query, QueryOptions.empty()); List errorFiles = new ArrayList<>(); while (fileIterator.hasNext()) { File file = fileIterator.next(); @@ -844,7 +867,7 @@ private void checkSampleCanBeDeleted(long studyId, Sample sample, boolean force) query = new Query() .append(CohortDBAdaptor.QueryParams.SAMPLE_UIDS.key(), sample.getUid()) .append(CohortDBAdaptor.QueryParams.STUDY_UID.key(), studyId); - DBIterator cohortIterator = cohortDBAdaptor.iterator(query, QueryOptions.empty()); + DBIterator cohortIterator = getCohortDBAdaptor(organizationId).iterator(query, QueryOptions.empty()); List errorCohorts = new ArrayList<>(); boolean associatedToDefaultCohort = false; while (cohortIterator.hasNext()) { @@ -881,8 +904,9 @@ private void checkSampleCanBeDeleted(long studyId, Sample sample, boolean force) query = new Query() .append(IndividualDBAdaptor.QueryParams.SAMPLE_UIDS.key(), sample.getUid()) .append(IndividualDBAdaptor.QueryParams.STUDY_UID.key(), studyId); - OpenCGAResult individualDataResult = individualDBAdaptor.get(query, new QueryOptions(QueryOptions.INCLUDE, - Arrays.asList(IndividualDBAdaptor.QueryParams.UID.key(), IndividualDBAdaptor.QueryParams.ID.key()))); + OpenCGAResult individualDataResult = getIndividualDBAdaptor(organizationId).get(query, + new QueryOptions(QueryOptions.INCLUDE, + Arrays.asList(IndividualDBAdaptor.QueryParams.UID.key(), IndividualDBAdaptor.QueryParams.ID.key()))); if (individualDataResult.getNumResults() > 0) { throw new CatalogException("Sample from individual " + individualDataResult.first().getName() + "(" + individualDataResult.first().getUid() + ")"); @@ -890,16 +914,16 @@ private void checkSampleCanBeDeleted(long studyId, Sample sample, boolean force) } } - public OpenCGAResult update(String studyStr, Query query, SampleUpdateParams updateParams, QueryOptions options, String token) - throws CatalogException { - return update(studyStr, query, updateParams, false, options, token); + public OpenCGAResult update(String organizationId, String studyStr, Query query, SampleUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + return update(organizationId, studyStr, query, updateParams, false, options, token); } - public OpenCGAResult update(String studyStr, Query query, SampleUpdateParams updateParams, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { + public OpenCGAResult update(String organizationId, String studyStr, Query query, SampleUpdateParams updateParams, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { Query finalQuery = new Query(ParamUtils.defaultObject(query, Query::new)); - String userId = userManager.getUserId(token); + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -912,6 +936,7 @@ public OpenCGAResult update(String studyStr, Query query, SampleUpdatePa } ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("query", query) .append("updateParams", updateMap) @@ -921,11 +946,11 @@ public OpenCGAResult update(String studyStr, Query query, SampleUpdatePa DBIterator iterator; try { - fixQueryObject(study, finalQuery, userId); + fixQueryObject(organizationId, study, finalQuery, userId); finalQuery.append(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - iterator = sampleDBAdaptor.iterator(study.getUid(), finalQuery, INCLUDE_SAMPLE_IDS, userId); + iterator = getSampleDBAdaptor(organizationId).iterator(study.getUid(), finalQuery, INCLUDE_SAMPLE_IDS, userId); } catch (CatalogException e) { auditManager.auditUpdate(operationId, userId, Enums.Resource.SAMPLE, "", "", study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError())); @@ -937,7 +962,7 @@ public OpenCGAResult update(String studyStr, Query query, SampleUpdatePa while (iterator.hasNext()) { Sample sample = iterator.next(); try { - OpenCGAResult updateResult = update(study, sample, updateParams, options, userId); + OpenCGAResult updateResult = update(organizationId, study, sample, updateParams, options, userId); result.append(updateResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.SAMPLE, sample.getId(), sample.getUuid(), study.getId(), @@ -957,9 +982,9 @@ public OpenCGAResult update(String studyStr, Query query, SampleUpdatePa return endResult(result, ignoreException); } - public OpenCGAResult update(String studyStr, String sampleId, SampleUpdateParams updateParams, QueryOptions options, - String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, String sampleId, SampleUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -972,6 +997,7 @@ public OpenCGAResult update(String studyStr, String sampleId, SampleUpda } ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("sampleId", sampleId) .append("updateParams", updateMap) @@ -991,7 +1017,7 @@ public OpenCGAResult update(String studyStr, String sampleId, SampleUpda sampleId = sample.getId(); sampleUuid = sample.getUuid(); - OpenCGAResult updateResult = update(study, sample, updateParams, options, userId); + OpenCGAResult updateResult = update(organizationId, study, sample, updateParams, options, userId); result.append(updateResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.SAMPLE, sample.getId(), sample.getUuid(), study.getId(), @@ -1013,23 +1039,24 @@ public OpenCGAResult update(String studyStr, String sampleId, SampleUpda /** * Update Sample from catalog. * - * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy]. - * @param sampleIds List of Sample ids. Could be either the id or uuid. - * @param updateParams Data model filled only with the parameters to be updated. - * @param options QueryOptions object. - * @param token Session id of the user logged in. + * @param organizationId Organization id. + * @param studyStr Study id in string format. Could be one of [id|user@aliasProject:aliasStudy|aliasProject:aliasStudy|aliasStudy] + * @param sampleIds List of Sample ids. Could be either the id or uuid. + * @param updateParams Data model filled only with the parameters to be updated. + * @param options QueryOptions object. + * @param token Session id of the user logged in. * @return A OpenCGAResult with the objects updated. * @throws CatalogException if there is any internal error, the user does not have proper permissions or a parameter passed does not * exist or is not allowed to be updated. */ - public OpenCGAResult update(String studyStr, List sampleIds, SampleUpdateParams updateParams, QueryOptions options, - String token) throws CatalogException { - return update(studyStr, sampleIds, updateParams, false, options, token); + public OpenCGAResult update(String organizationId, String studyStr, List sampleIds, SampleUpdateParams updateParams, + QueryOptions options, String token) throws CatalogException { + return update(organizationId, studyStr, sampleIds, updateParams, false, options, token); } - public OpenCGAResult update(String studyStr, List sampleIds, SampleUpdateParams updateParams, boolean ignoreException, - QueryOptions options, String token) throws CatalogException { - String userId = userManager.getUserId(token); + public OpenCGAResult update(String organizationId, String studyStr, List sampleIds, SampleUpdateParams updateParams, + boolean ignoreException, QueryOptions options, String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyStr, userId, StudyManager.INCLUDE_VARIABLE_SET); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); @@ -1042,6 +1069,7 @@ public OpenCGAResult update(String studyStr, List sampleIds, Sam } ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("study", studyStr) .append("sampleIds", sampleIds) .append("updateParams", updateMap) @@ -1066,7 +1094,7 @@ public OpenCGAResult update(String studyStr, List sampleIds, Sam sampleId = sample.getId(); sampleUuid = sample.getUuid(); - OpenCGAResult updateResult = update(study, sample, updateParams, options, userId); + OpenCGAResult updateResult = update(organizationId, study, sample, updateParams, options, userId); result.append(updateResult); auditManager.auditUpdate(operationId, userId, Enums.Resource.SAMPLE, sample.getId(), sample.getUuid(), study.getId(), @@ -1086,8 +1114,8 @@ public OpenCGAResult update(String studyStr, List sampleIds, Sam return endResult(result, ignoreException); } - private OpenCGAResult update(Study study, Sample sample, SampleUpdateParams updateParams, QueryOptions options, String userId) - throws CatalogException { + private OpenCGAResult update(String organizationId, Study study, Sample sample, SampleUpdateParams updateParams, QueryOptions options, + String userId) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); SampleUpdateParams updateParamsClone; @@ -1148,8 +1176,8 @@ private OpenCGAResult update(Study study, Sample sample, SampleUpdateParams upda if (updateParamsClone != null && StringUtils.isNotEmpty(updateParamsClone.getIndividualId())) { // Check individual id exists - OpenCGAResult individualDataResult = catalogManager.getIndividualManager().internalGet(organizationId, study.getUid(), - updateParamsClone.getIndividualId(), IndividualManager.INCLUDE_INDIVIDUAL_IDS, userId); + OpenCGAResult individualDataResult = catalogManager.getIndividualManager().internalGet(organizationId, + study.getUid(), updateParamsClone.getIndividualId(), IndividualManager.INCLUDE_INDIVIDUAL_IDS, userId); if (individualDataResult.getNumResults() == 0) { throw new CatalogException("Individual '" + updateParamsClone.getIndividualId() + "' not found."); } @@ -1158,12 +1186,14 @@ private OpenCGAResult update(Study study, Sample sample, SampleUpdateParams upda parameters.put(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), individualDataResult.first().getId()); } - checkUpdateAnnotations(study, sample, parameters, options, VariableSet.AnnotableDataModels.SAMPLE, sampleDBAdaptor, userId); + checkUpdateAnnotations(organizationId, study, sample, parameters, options, VariableSet.AnnotableDataModels.SAMPLE, + getSampleDBAdaptor(organizationId), userId); - OpenCGAResult update = sampleDBAdaptor.update(sample.getUid(), parameters, study.getVariableSets(), options); + OpenCGAResult update = getSampleDBAdaptor(organizationId).update(sample.getUid(), parameters, study.getVariableSets(), + options); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated sample - OpenCGAResult queryResult = sampleDBAdaptor.get(study.getUid(), + OpenCGAResult queryResult = getSampleDBAdaptor(organizationId).get(study.getUid(), new Query(SampleDBAdaptor.QueryParams.UID.key(), sample.getUid()), options, userId); update.setResults(queryResult.getResults()); } @@ -1171,13 +1201,13 @@ private OpenCGAResult update(Study study, Sample sample, SampleUpdateParams upda } @Override - public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String sessionId) + public OpenCGAResult rank(String organizationId, String studyStr, Query query, String field, int numResults, boolean asc, String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); ParamUtils.checkObj(field, "field"); - ParamUtils.checkObj(sessionId, "sessionId"); + ParamUtils.checkObj(token, "token"); - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); // Fix query if it contains any annotation @@ -1191,22 +1221,22 @@ public OpenCGAResult rank(String organizationId, String studyStr, Query query, S OpenCGAResult queryResult = null; if (count) { // We do not need to check for permissions when we show the count of files - queryResult = sampleDBAdaptor.rank(query, field, numResults, asc); + queryResult = getSampleDBAdaptor(organizationId).rank(query, field, numResults, asc); } return ParamUtils.defaultObject(queryResult, OpenCGAResult::new); } @Override - public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, String sessionId) - throws CatalogException { + public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Query query, List fields, QueryOptions options, + String token) throws CatalogException { query = ParamUtils.defaultObject(query, Query::new); options = ParamUtils.defaultObject(options, QueryOptions::new); if (fields == null || fields.size() == 0) { throw new CatalogException("Empty fields parameter."); } - String userId = userManager.getUserId(sessionId); + String userId = userManager.getUserId(organizationId, token); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); // Fix query if it contains any annotation @@ -1216,27 +1246,28 @@ public OpenCGAResult groupBy(String organizationId, @Nullable String studyStr, Q // Add study id to the query query.put(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid()); - OpenCGAResult queryResult = sampleDBAdaptor.groupBy(query, fields, options, userId); + OpenCGAResult queryResult = getSampleDBAdaptor(organizationId).groupBy(query, fields, options, userId); return ParamUtils.defaultObject(queryResult, OpenCGAResult::new); } // ************************** ACLs ******************************** // - public OpenCGAResult> getAcls(String studyId, List sampleList, String member, - boolean ignoreException, String token) + public OpenCGAResult> getAcls(String organizationId, String studyId, List sampleList, + String member, boolean ignoreException, String token) throws CatalogException { - return getAcls(studyId, sampleList, StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), - ignoreException, token); + return getAcls(organizationId, studyId, sampleList, + StringUtils.isNotEmpty(member) ? Collections.singletonList(member) : Collections.emptyList(), ignoreException, token); } - public OpenCGAResult> getAcls(String studyId, List sampleList, + public OpenCGAResult> getAcls(String organizationId, String studyId, List sampleList, List members, boolean ignoreException, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); String operationId = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("sampleList", sampleList) .append("members", members) @@ -1247,7 +1278,8 @@ public OpenCGAResult> getAcls(String studyId, Li Map missingMap = new HashMap<>(); try { auditManager.initAuditBatch(operationId); - InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), sampleList, INCLUDE_SAMPLE_IDS, user, ignoreException); + InternalGetDataResult queryResult = internalGet(organizationId, study.getUid(), sampleList, INCLUDE_SAMPLE_IDS, user, + ignoreException); if (queryResult.getMissing() != null) { missingMap = queryResult.getMissing().stream() @@ -1309,14 +1341,15 @@ public OpenCGAResult> getAcls(String studyId, Li return sampleAcls; } - public OpenCGAResult> updateAcl(String studyId, List sampleStringList, + public OpenCGAResult> updateAcl(String organizationId, String studyId, List sampleStringList, String memberList, SampleAclParams sampleAclParams, ParamUtils.AclAction action, String token) throws CatalogException { - String user = userManager.getUserId(token); + String user = userManager.getUserId(organizationId, token); Study study = studyManager.resolveId(organizationId, studyId, user); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("sampleStringList", sampleStringList) .append("memberList", memberList) @@ -1358,7 +1391,8 @@ public OpenCGAResult> updateAcl(String studyId, if (StringUtils.isNotEmpty(sampleAclParams.getIndividual())) { Query query = new Query(IndividualDBAdaptor.QueryParams.ID.key(), sampleAclParams.getIndividual()); QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, IndividualDBAdaptor.QueryParams.SAMPLES.key()); - OpenCGAResult indDataResult = catalogManager.getIndividualManager().search(organizationId, studyId, query, options, token); + OpenCGAResult indDataResult = catalogManager.getIndividualManager().search(organizationId, studyId, query, + options, token); Set sampleSet = new HashSet<>(); for (Individual individual : indDataResult.getResults()) { @@ -1403,7 +1437,8 @@ public OpenCGAResult> updateAcl(String studyId, if (StringUtils.isNotEmpty(sampleAclParams.getCohort())) { Query query = new Query(CohortDBAdaptor.QueryParams.ID.key(), sampleAclParams.getCohort()); QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, CohortDBAdaptor.QueryParams.SAMPLES.key()); - OpenCGAResult cohortDataResult = catalogManager.getCohortManager().search(organizationId, studyId, query, options, token); + OpenCGAResult cohortDataResult = catalogManager.getCohortManager().search(organizationId, studyId, query, options, + token); Set sampleSet = new HashSet<>(); for (Cohort cohort : cohortDataResult.getResults()) { @@ -1422,7 +1457,7 @@ public OpenCGAResult> updateAcl(String studyId, } else { members = Collections.emptyList(); } - checkMembers(study.getUid(), members); + checkMembers(organizationId, study.getUid(), members); authorizationManager.checkNotAssigningPermissionsToAdminsGroup(members); } catch (CatalogException e) { if (sampleStringList != null) { @@ -1509,9 +1544,9 @@ public OpenCGAResult> updateAcl(String studyId, return aclResultList; } - public DataResult facet(String studyId, Query query, QueryOptions options, boolean defaultStats, String token) - throws CatalogException { - String userId = userManager.getUserId(token); + public DataResult facet(String organizationId, String studyId, Query query, QueryOptions options, boolean defaultStats, + String token) throws CatalogException { + String userId = userManager.getUserId(organizationId, token); // We need to add variableSets and groups to avoid additional queries as it will be used in the catalogSolrManager Study study = catalogManager.getStudyManager().resolveId(organizationId, studyId, userId, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList(StudyDBAdaptor.QueryParams.VARIABLE_SET.key(), StudyDBAdaptor.QueryParams.GROUPS.key()))); @@ -1520,6 +1555,7 @@ public DataResult facet(String studyId, Query query, QueryOptions op ParamUtils.defaultObject(options, QueryOptions::new); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("studyId", studyId) .append("query", new Query(query)) .append("options", options) @@ -1548,13 +1584,15 @@ public DataResult facet(String studyId, Query query, QueryOptions op } } - private List getIndividualsUidsFromSampleUids(long studyUid, List sampleUids) throws CatalogException { + private List getIndividualsUidsFromSampleUids(String organizationId, long studyUid, List sampleUids) + throws CatalogException { // Look for all the individuals owning the samples Query query = new Query() .append(IndividualDBAdaptor.QueryParams.STUDY_UID.key(), studyUid) .append(IndividualDBAdaptor.QueryParams.SAMPLE_UIDS.key(), sampleUids); - OpenCGAResult individualDataResult = individualDBAdaptor.get(query, IndividualManager.INCLUDE_INDIVIDUAL_IDS); + OpenCGAResult individualDataResult = getIndividualDBAdaptor(organizationId).get(query, + IndividualManager.INCLUDE_INDIVIDUAL_IDS); return individualDataResult.getResults().stream().map(Individual::getUid).collect(Collectors.toList()); } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/StudyManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/StudyManager.java index 259964b8acc..34f55e2373a 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/StudyManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/StudyManager.java @@ -276,7 +276,7 @@ private OpenCGAResult getStudy(String organizationId, long projectUid, St } @Deprecated - public OpenCGAResult create(String projectStr, String id, String alias, String name, String description, + public OpenCGAResult create(String organizationId, String projectStr, String id, String alias, String name, String description, StudyNotification notification, StudyInternal internal, Status status, Map attributes, QueryOptions options, String token) throws CatalogException { Study study = new Study() @@ -296,7 +296,7 @@ public OpenCGAResult create(String organizationId, String projectStr, Stu ParamUtils.checkObj(study, "study"); ParamUtils.checkIdentifier(study.getId(), "id"); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Project project = catalogManager.getProjectManager().resolveId(organizationId, projectStr, userId); ObjectMap auditParams = new ObjectMap() @@ -430,13 +430,13 @@ private void createDefaultVariableSets(String organizationId, Study study, Strin } } - public int getCurrentRelease(Study study, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + public int getCurrentRelease(String organizationId, Study study, String token) throws CatalogException { + String userId = catalogManager.getUserManager().getUserId(organizationId, token); authorizationManager.checkCanViewStudy(study.getUid(), userId); - return getCurrentRelease(study); + return getCurrentRelease(organizationId, study); } - int getCurrentRelease(Study study) throws CatalogException { + int getCurrentRelease(String organizationId, Study study) throws CatalogException { String[] split = StringUtils.split(study.getFqn(), ":"); String userId = StringUtils.split(split[0], "@")[0]; return catalogManager.getProjectManager().resolveId(organizationId, split[0], userId).getCurrentRelease(); @@ -456,7 +456,7 @@ MyResourceId getVariableSetId(String organizationId, String variableStr, @Nullab throw new CatalogException("More than one variable set found. Please, choose just one variable set"); } - userId = catalogManager.getUserManager().getUserId(sessionId); + userId = catalogManager.getUserManager().getUserId(organizationId, sessionId); Study study = catalogManager.getStudyManager().resolveId(organizationId, studyStr, userId); studyId = study.getUid(); @@ -478,7 +478,7 @@ MyResourceId getVariableSetId(String organizationId, String variableStr, @Nullab /** * Fetch a study from Catalog given a study id or alias. * - * @param organizationId + * @param organizationId Organization id. * @param studyStr Study id or alias. * @param options Read options * @param token sessionId @@ -488,7 +488,7 @@ MyResourceId getVariableSetId(String organizationId, String variableStr, @Nullab public OpenCGAResult get(String organizationId, String studyStr, QueryOptions options, String token) throws CatalogException { options = ParamUtils.defaultObject(options, QueryOptions::new); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); ObjectMap auditParams = new ObjectMap() .append("organizationId", organizationId) .append("studyStr", studyStr) @@ -534,7 +534,7 @@ public OpenCGAResult get(String organizationId, List studyList, Q /** * Fetch all the study objects matching the query. * - * @param organizationId + * @param organizationId Organization id. * @param projectStr Project id or alias. * @param query Query to catalog. * @param options Query options, like "include", "exclude", "limit" and "skip" @@ -571,7 +571,7 @@ public OpenCGAResult search(String organizationId, String projectStr, Que /** * Fetch all the study objects matching the query. * - * @param organizationId + * @param organizationId Organization id. * @param query Query to catalog. * @param options Query options, like "include", "exclude", "limit" and "skip" * @param token sessionId @@ -582,7 +582,7 @@ public OpenCGAResult search(String organizationId, Query query, QueryOpti query = ParamUtils.defaultObject(query, Query::new); QueryOptions qOptions = options != null ? new QueryOptions(options) : new QueryOptions(); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); ObjectMap auditParams = new ObjectMap() .append("organizationId", organizationId) @@ -623,7 +623,7 @@ private OpenCGAResult filterResults(OpenCGAResult result) { /** * Update an existing catalog study. * - * @param organizationId + * @param organizationId Organization id. * @param studyId Study id or alias. * @param parameters Parameters to change. * @param options options @@ -633,7 +633,7 @@ private OpenCGAResult filterResults(OpenCGAResult result) { */ public OpenCGAResult update(String organizationId, String studyId, StudyUpdateParams parameters, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); ObjectMap auditParams = new ObjectMap() .append("organizationId", organizationId) @@ -694,7 +694,7 @@ public OpenCGAResult update(String organizationId, String studyId, StudyU public OpenCGAResult createPermissionRule(String organizationId, String studyId, Enums.Entity entry, PermissionRule permissionRule, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId, INCLUDE_STUDY_IDS); ObjectMap auditParams = new ObjectMap() @@ -710,7 +710,8 @@ public OpenCGAResult createPermissionRule(String organizationId, authorizationManager.checkCanUpdatePermissionRules(study.getUid(), userId); validatePermissionRules(organizationId, study.getUid(), entry, permissionRule); - OpenCGAResult result = getStudyDBAdaptor(organizationId).createPermissionRule(study.getUid(), entry, permissionRule); + OpenCGAResult result = getStudyDBAdaptor(organizationId).createPermissionRule(study.getUid(), entry, + permissionRule); auditManager.audit(userId, Enums.Action.ADD_STUDY_PERMISSION_RULE, Enums.Resource.STUDY, study.getId(), study.getUuid(), study.getId(), study.getUuid(), auditParams, @@ -728,7 +729,7 @@ public OpenCGAResult createPermissionRule(String organizationId, public void markDeletedPermissionRule(String organizationId, String studyId, Enums.Entity entry, String permissionRuleId, PermissionRule.DeleteAction deleteAction, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -759,7 +760,7 @@ public void markDeletedPermissionRule(String organizationId, String studyId, Enu public OpenCGAResult getPermissionRules(String organizationId, String studyId, Enums.Entity entry, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -789,7 +790,7 @@ public OpenCGAResult rank(String organizationId, long projectId, Query query, St ParamUtils.checkObj(field, "field"); ParamUtils.checkObj(projectId, "projectId"); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); authorizationManager.checkCanViewProject(projectId, userId); // TODO: In next release, we will have to check the count parameter from the queryOptions object. @@ -816,7 +817,7 @@ public OpenCGAResult groupBy(String organizationId, long projectId, Query query, ParamUtils.checkObj(fields, "fields"); ParamUtils.checkObj(projectId, "projectId"); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); authorizationManager.checkCanViewProject(projectId, userId); // TODO: In next release, we will have to check the count parameter from the queryOptions object. @@ -855,16 +856,20 @@ public OpenCGAResult getSummary(String organizationId, String stud .getNumMatches(); studySummary.setFiles(nFiles); - Long nSamples = getSampleDBAdaptor(organizationId).count(new Query(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())).getNumMatches(); + Long nSamples = getSampleDBAdaptor(organizationId).count(new Query(SampleDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())) + .getNumMatches(); studySummary.setSamples(nSamples); - Long nJobs = getJobDBAdaptor(organizationId).count(new Query(JobDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())).getNumMatches(); + Long nJobs = getJobDBAdaptor(organizationId).count(new Query(JobDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())) + .getNumMatches(); studySummary.setJobs(nJobs); - Long nCohorts = getCohortDBAdaptor(organizationId).count(new Query(CohortDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())).getNumMatches(); + Long nCohorts = getCohortDBAdaptor(organizationId).count(new Query(CohortDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())) + .getNumMatches(); studySummary.setCohorts(nCohorts); - Long nIndividuals = getIndividualDBAdaptor(organizationId).count(new Query(IndividualDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())) + Long nIndividuals = getIndividualDBAdaptor(organizationId) + .count(new Query(IndividualDBAdaptor.QueryParams.STUDY_UID.key(), study.getUid())) .getNumMatches(); studySummary.setIndividuals(nIndividuals); @@ -898,7 +903,7 @@ public OpenCGAResult createGroup(String organizationId, String studyStr, } public OpenCGAResult createGroup(String organizationId, String studyId, Group group, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -961,7 +966,7 @@ public OpenCGAResult createGroup(String organizationId, String studyId, G } public OpenCGAResult getGroup(String organizationId, String studyId, String groupId, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -990,7 +995,7 @@ public OpenCGAResult getGroup(String organizationId, String studyId, Stri public OpenCGAResult getCustomGroups(String organizationId, String studyId, String groupId, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1059,7 +1064,7 @@ public OpenCGAResult getCustomGroups(String organizationId, String public OpenCGAResult updateGroup(String organizationId, String studyId, String groupId, ParamUtils.BasicUpdateAction action, GroupUpdateParams updateParams, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1146,7 +1151,7 @@ public OpenCGAResult updateGroup(String organizationId, String studyId, S public OpenCGAResult updateSummaryIndex(String organizationId, String studyStr, RecessiveGeneSummaryIndex summaryIndex, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyStr, userId); ObjectMap auditParams = new ObjectMap() @@ -1222,7 +1227,7 @@ public OpenCGAResult updateSummaryIndex(String organizationId, String studySt // } public OpenCGAResult deleteGroup(String organizationId, String studyId, String groupId, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1307,7 +1312,7 @@ private OpenCGAResult createVariableSet(String organizationId, Stud throws CatalogException { ParamUtils.checkParameter(variableSet.getId(), "id"); ParamUtils.checkObj(variableSet.getVariables(), "Variables from VariableSet"); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); authorizationManager.checkCanCreateUpdateDeleteVariableSets(study.getUid(), userId); variableSet.setDescription(ParamUtils.defaultString(variableSet.getDescription(), "")); @@ -1327,7 +1332,7 @@ private OpenCGAResult createVariableSet(String organizationId, Stud // variable.setRank(defaultString(variable.getDescription(), "")); } - variableSet.setRelease(getCurrentRelease(study)); + variableSet.setRelease(getCurrentRelease(organizationId, study)); AnnotationUtils.checkVariableSet(variableSet); OpenCGAResult result = getStudyDBAdaptor(organizationId).createVariableSet(study.getUid(), variableSet); @@ -1348,7 +1353,7 @@ public OpenCGAResult createVariableSet(String organizationId, Strin public OpenCGAResult createVariableSet(String organizationId, String studyId, VariableSet variableSet, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId); ObjectMap auditParams = new ObjectMap() @@ -1370,7 +1375,7 @@ public OpenCGAResult createVariableSet(String organizationId, Strin public OpenCGAResult getVariableSet(String organizationId, String studyId, String variableSetId, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId, StudyManager.INCLUDE_VARIABLE_SET); ObjectMap auditParams = new ObjectMap() @@ -1396,14 +1401,15 @@ public OpenCGAResult getVariableSet(String organizationId, String s public OpenCGAResult searchVariableSets(String organizationId, String studyStr, Query query, QueryOptions options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyStr, userId); // authorizationManager.checkStudyPermission(studyId, userId, StudyAclEntry.StudyPermissions.VIEW_VARIABLE_SET); options = ParamUtils.defaultObject(options, QueryOptions::new); query = ParamUtils.defaultObject(query, Query::new); if (query.containsKey(StudyDBAdaptor.VariableSetParams.UID.key())) { // Id could be either the id or the name - MyResourceId resource = getVariableSetId(organizationId, query.getString(StudyDBAdaptor.VariableSetParams.UID.key()), studyStr, token); + MyResourceId resource = getVariableSetId(organizationId, query.getString(StudyDBAdaptor.VariableSetParams.UID.key()), studyStr, + token); query.put(StudyDBAdaptor.VariableSetParams.UID.key(), resource.getResourceId()); } query.put(StudyDBAdaptor.VariableSetParams.STUDY_UID.key(), study.getUid()); @@ -1412,7 +1418,7 @@ public OpenCGAResult searchVariableSets(String organizationId, Stri public OpenCGAResult deleteVariableSet(String organizationId, String studyId, String variableSetId, boolean force, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId, StudyManager.INCLUDE_VARIABLE_SET); VariableSet variableSet = extractVariableSet(organizationId, study, variableSetId, userId); @@ -1438,7 +1444,7 @@ public OpenCGAResult deleteVariableSet(String organizationId, Strin public OpenCGAResult addFieldToVariableSet(String organizationId, String studyId, String variableSetId, Variable variable, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId, StudyManager.INCLUDE_VARIABLE_SET); VariableSet variableSet = extractVariableSet(organizationId, study, variableSetId, userId); @@ -1461,7 +1467,8 @@ public OpenCGAResult addFieldToVariableSet(String organizationId, S auditManager.audit(userId, Enums.Action.ADD_VARIABLE_TO_VARIABLE_SET, Enums.Resource.STUDY, variableSet.getId(), "", study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); - OpenCGAResult queryResult = getStudyDBAdaptor(organizationId).getVariableSet(variableSet.getUid(), QueryOptions.empty()); + OpenCGAResult queryResult = getStudyDBAdaptor(organizationId).getVariableSet(variableSet.getUid(), + QueryOptions.empty()); queryResult.setTime(queryResult.getTime() + result.getTime()); return queryResult; } catch (CatalogException e) { @@ -1473,7 +1480,7 @@ public OpenCGAResult addFieldToVariableSet(String organizationId, S public OpenCGAResult removeFieldFromVariableSet(String organizationId, String studyId, String variableSetId, String variableId, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyId, userId, StudyManager.INCLUDE_VARIABLE_SET); VariableSet variableSet = extractVariableSet(organizationId, study, variableSetId, userId); @@ -1491,7 +1498,8 @@ public OpenCGAResult removeFieldFromVariableSet(String organization variableSet.getId(), "", study.getId(), study.getUuid(), auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); - OpenCGAResult queryResult = getStudyDBAdaptor(organizationId).getVariableSet(variableSet.getUid(), QueryOptions.empty()); + OpenCGAResult queryResult = getStudyDBAdaptor(organizationId).getVariableSet(variableSet.getUid(), + QueryOptions.empty()); queryResult.setTime(queryResult.getTime() + result.getTime()); return queryResult; } catch (CatalogException e) { @@ -1502,7 +1510,8 @@ public OpenCGAResult removeFieldFromVariableSet(String organization } } - private VariableSet extractVariableSet(String organizationId, Study study, String variableSetId, String userId) throws CatalogException { + private VariableSet extractVariableSet(String organizationId, Study study, String variableSetId, String userId) + throws CatalogException { if (study == null || study.getVariableSets() == null || study.getVariableSets().isEmpty()) { throw new CatalogException(variableSetId + " not found."); } @@ -1525,7 +1534,7 @@ private VariableSet extractVariableSet(String organizationId, Study study, Strin public OpenCGAResult> getAcls(String organizationId, List studyIdList, String member, boolean ignoreException, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); List studyList = resolveIds(organizationId, studyIdList, userId); ObjectMap auditParams = new ObjectMap() @@ -1578,7 +1587,7 @@ public OpenCGAResult> updateAcl(Strin String memberIds, StudyAclParams aclParams, ParamUtils.AclAction action, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); List studies = resolveIds(organizationId, studyIdList, userId); ObjectMap auditParams = new ObjectMap() @@ -1701,18 +1710,18 @@ public Map facet(String organizationId, String studyStr, String String individualFields, String cohortFields, String familyFields, String jobFields, boolean defaultStats, String sessionId) throws CatalogException, IOException { Map result = new HashMap<>(); - result.put("sample", catalogManager.getSampleManager().facet(studyStr, new Query(), setFacetFields(sampleFields), defaultStats, - sessionId)); - result.put("file", catalogManager.getFileManager().facet(organizationId, studyStr, new Query(), setFacetFields(fileFields), defaultStats, - sessionId)); - result.put("individual", catalogManager.getIndividualManager().facet(organizationId, studyStr, new Query(), setFacetFields(individualFields), + result.put("sample", catalogManager.getSampleManager().facet(organizationId, studyStr, new Query(), setFacetFields(sampleFields), + defaultStats, sessionId)); + result.put("file", catalogManager.getFileManager().facet(organizationId, studyStr, new Query(), setFacetFields(fileFields), + defaultStats, sessionId)); + result.put("individual", catalogManager.getIndividualManager().facet(organizationId, studyStr, new Query(), + setFacetFields(individualFields), defaultStats, sessionId)); + result.put("family", catalogManager.getFamilyManager().facet(organizationId, studyStr, new Query(), setFacetFields(familyFields), + defaultStats, sessionId)); + result.put("cohort", catalogManager.getCohortManager().facet(organizationId, studyStr, new Query(), setFacetFields(cohortFields), + defaultStats, sessionId)); + result.put("job", catalogManager.getJobManager().facet(organizationId, studyStr, new Query(), setFacetFields(jobFields), defaultStats, sessionId)); - result.put("family", catalogManager.getFamilyManager().facet(organizationId, studyStr, new Query(), setFacetFields(familyFields), defaultStats, - sessionId)); - result.put("cohort", catalogManager.getCohortManager().facet(organizationId, studyStr, new Query(), setFacetFields(cohortFields), defaultStats, - sessionId)); - result.put("job", catalogManager.getJobManager().facet(organizationId, studyStr, new Query(), setFacetFields(jobFields), defaultStats, - sessionId)); return result; } @@ -1727,7 +1736,7 @@ private QueryOptions setFacetFields(String fields) { public void setVariantEngineConfigurationOptions(String organizationId, String studyStr, ObjectMap options, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = get(organizationId, studyStr, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList( StudyDBAdaptor.QueryParams.UID.key(), StudyDBAdaptor.QueryParams.INTERNAL_CONFIGURATION_VARIANT_ENGINE.key())), token).first(); @@ -1746,7 +1755,7 @@ public void setVariantEngineConfigurationOptions(String organizationId, String s public void setVariantEngineConfigurationSampleIndex(String organizationId, String studyStr, SampleIndexConfiguration sampleIndexConfiguration, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = get(organizationId, studyStr, new QueryOptions(QueryOptions.INCLUDE, Arrays.asList( StudyDBAdaptor.QueryParams.UID.key(), StudyDBAdaptor.QueryParams.INTERNAL_CONFIGURATION_VARIANT_ENGINE.key())), token).first(); @@ -1855,7 +1864,7 @@ public String getProjectFqn(String studyFqn) throws CatalogException { */ public OpenCGAResult uploadTemplate(String organizationId, String studyStr, String filename, InputStream inputStream, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyStr, userId, QueryOptions.empty()); String templateId = "template." + TimeUtils.getTime() + "." + RandomStringUtils.random(6, true, false); @@ -1941,7 +1950,7 @@ public OpenCGAResult uploadTemplate(String organizationId, String studyS /** * Delete a template from Catalog. * - * @param organizationId + * @param organizationId Organization id. * @param studyStr study where the template belongs to. * @param templateId Template id. * @param token Token of the user performing the upload. @@ -1950,7 +1959,7 @@ public OpenCGAResult uploadTemplate(String organizationId, String studyS */ public OpenCGAResult deleteTemplate(String organizationId, String studyStr, String templateId, String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study = resolveId(organizationId, studyStr, userId, QueryOptions.empty()); ObjectMap auditParams = new ObjectMap() diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/UserManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/UserManager.java index 84683c87509..14590155732 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/UserManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/managers/UserManager.java @@ -44,7 +44,6 @@ import org.opencb.opencga.core.models.JwtPayload; import org.opencb.opencga.core.models.audit.AuditRecord; import org.opencb.opencga.core.models.common.Enums; -import org.opencb.opencga.core.models.organizations.Organization; import org.opencb.opencga.core.models.project.Project; import org.opencb.opencga.core.models.study.Group; import org.opencb.opencga.core.models.study.GroupUpdateParams; @@ -134,7 +133,7 @@ public class UserManager extends AbstractManager { } } - public void changePassword(String userId, String oldPassword, String newPassword) throws CatalogException { + public void changePassword(String organizationId, String userId, String oldPassword, String newPassword) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(oldPassword, "oldPassword"); ParamUtils.checkParameter(newPassword, "newPassword"); @@ -143,8 +142,8 @@ public void changePassword(String userId, String oldPassword, String newPassword throw new CatalogException("New password is the same as the old password."); } - userDBAdaptor.checkId(userId); - String authOrigin = getAuthenticationOriginId(userId); + getUserDBAdaptor(organizationId).checkId(userId); + String authOrigin = getAuthenticationOriginId(organizationId, userId); authenticationManagerMap.get(authOrigin).changePassword(userId, oldPassword, newPassword); auditManager.auditUser(userId, Enums.Action.CHANGE_USER_PASSWORD, userId, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -204,7 +203,7 @@ public OpenCGAResult create(String organizationId, User user, String passw } } - checkUserExists(user.getId()); + checkUserExists(organizationId, user.getId()); try { if (StringUtils.isNotEmpty(password) && !PasswordUtils.isStrongPassword(password)) { @@ -215,14 +214,14 @@ public OpenCGAResult create(String organizationId, User user, String passw } catalogIOManager.createUser(organizationId, user.getId()); - userDBAdaptor.insert(user, password, QueryOptions.empty()); + getUserDBAdaptor(organizationId).insert(user, password, QueryOptions.empty()); auditManager.auditCreate(userId, Enums.Resource.USER, user.getId(), "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); - return userDBAdaptor.get(user.getId(), QueryOptions.empty()); + return getUserDBAdaptor(organizationId).get(user.getId(), QueryOptions.empty()); } catch (CatalogIOException | CatalogDBException e) { - if (userDBAdaptor.exists(user.getId())) { + if (getUserDBAdaptor(organizationId).exists(user.getId())) { logger.error("ERROR! DELETING USER! " + user.getId()); catalogIOManager.deleteUser(organizationId, user.getId()); } @@ -234,114 +233,30 @@ public OpenCGAResult create(String organizationId, User user, String passw } } - public OpenCGAResult create(User user, String password, @Nullable String token) throws CatalogException { - // Check if the users can be registered publicly or just the admin. - ObjectMap auditParams = new ObjectMap("user", user); - - // Initialise fields - ParamUtils.checkObj(user, "User"); - ParamUtils.checkValidUserId(user.getId()); - ParamUtils.checkParameter(user.getName(), "name"); - user.setEmail(ParamUtils.defaultString(user.getEmail(), "")); - if (StringUtils.isNotEmpty(user.getEmail())) { - checkEmail(user.getEmail()); - } - user.setOrganization(ParamUtils.defaultObject(user.getOrganization(), "")); - ParamUtils.checkObj(user.getAccount(), "account"); - user.getAccount().setType(ParamUtils.defaultObject(user.getAccount().getType(), Account.AccountType.GUEST)); - user.getAccount().setCreationDate(TimeUtils.getTime()); - user.getAccount().setExpirationDate(ParamUtils.defaultString(user.getAccount().getExpirationDate(), "")); - user.setInternal(new UserInternal(new UserStatus(UserStatus.READY))); - user.setQuota(ParamUtils.defaultObject(user.getQuota(), UserQuota::new)); - user.setProjects(ParamUtils.defaultObject(user.getProjects(), Collections::emptyList)); - user.setSharedProjects(ParamUtils.defaultObject(user.getSharedProjects(), Collections::emptyList)); - user.setConfigs(ParamUtils.defaultObject(user.getConfigs(), HashMap::new)); - user.setFilters(ParamUtils.defaultObject(user.getFilters(), LinkedList::new)); - user.setAttributes(ParamUtils.defaultObject(user.getAttributes(), Collections::emptyMap)); - - if (StringUtils.isEmpty(password)) { - // The authentication origin must be different than internal - Set authOrigins = configuration.getAuthentication().getAuthenticationOrigins() - .stream() - .map(AuthenticationOrigin::getId) - .collect(Collectors.toSet()); - if (!authOrigins.contains(user.getAccount().getAuthentication().getId())) { - throw new CatalogException("Unknown authentication origin id '" + user.getAccount().getAuthentication() + "'"); - } - } else { - user.getAccount().setAuthentication(new Account.AuthenticationOrigin(INTERNAL_AUTHORIZATION, false)); - } - - String userId = OPENCGA; - Organization organization; - if (OPENCGA.equals(user.getId())) { - organization = catalogManager.getOrganizationManager().internalGet(ParamConstants.ADMIN_ORGANIZATION, - OrganizationManager.INCLUDE_ORGANIZATION_ADMINS, userId).first(); - } else { - JwtPayload payload = authenticationManagerMap.get(INTERNAL_AUTHORIZATION).getPayload(token); - organization = catalogManager.getOrganizationManager().internalGet(ParamConstants.ADMIN_ORGANIZATION, - OrganizationManager.INCLUDE_ORGANIZATION_ADMINS, payload.getUserId()).first(); - if (!OPENCGA.equals(payload.getUserId())) { - // Check owner or admin is trying to create a new user for the organization - if (!payload.getOrganization().equals(user.getOrganization())) { - throw new CatalogException("Owner or admins can only create new users inside the organization"); - } - } - } - - checkUserExists(user.getId()); - - try { - if (StringUtils.isNotEmpty(password) && !PasswordUtils.isStrongPassword(password)) { - throw new CatalogException("Invalid password. Check password strength for user " + user.getId()); - } - if (user.getProjects() != null && !user.getProjects().isEmpty()) { - throw new CatalogException("Creating user and projects in a single transaction is forbidden"); - } - - catalogIOManager.createUser(Long.toString(organization.getUid()), user.getId()); - userDBAdaptor.insert(user, password, QueryOptions.empty()); - - auditManager.auditCreate(userId, Enums.Resource.USER, user.getId(), "", "", "", auditParams, - new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); - - return userDBAdaptor.get(user.getId(), QueryOptions.empty()); - } catch (CatalogIOException | CatalogDBException e) { - if (userDBAdaptor.exists(user.getId())) { - logger.error("ERROR! DELETING USER! " + user.getId()); - catalogIOManager.deleteUser(user.getOrganization(), user.getId()); - } - - auditManager.auditCreate(userId, Enums.Resource.USER, user.getId(), "", "", "", auditParams, - new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError())); - - throw e; - } - } - /** * Create a new user. * - * @param id User id - * @param name Name - * @param email Email - * @param password Encrypted Password - * @param organization Optional organization - * @param quota Maximum user disk quota - * @param type User account type. Full or guest. - * @param token JWT token. + * @param organizationId Organization id. + * @param id User id + * @param name Name + * @param email Email + * @param password Encrypted Password + * @param organization Optional organization + * @param quota Maximum user disk quota + * @param type User account type. Full or guest. + * @param token JWT token. * @return The created user * @throws CatalogException If user already exists, or unable to create a new user. */ - public OpenCGAResult create(String id, String name, String email, String password, String organization, Long quota, - Account.AccountType type, String token) throws CatalogException { + public OpenCGAResult create(String organizationId, String id, String name, String email, String password, String organization, + Long quota, Account.AccountType type, String token) throws CatalogException { User user = new User(id, name, email, organization, new UserInternal(new UserStatus())) .setAccount(new Account(type, "", "", null)) .setQuota(new UserQuota().setMaxDisk(quota != null ? quota : -1)); - return create(user, password, token); + return create(organizationId, user, password, token); } - public void syncAllUsersOfExternalGroup(String study, String authOrigin, String token) throws CatalogException { + public void syncAllUsersOfExternalGroup(String organizationId, String study, String authOrigin, String token) throws CatalogException { if (!OPENCGA.equals(authenticationManagerMap.get(INTERNAL_AUTHORIZATION).getUserId(token))) { throw new CatalogAuthorizationException("Only the root user can perform this action"); } @@ -373,7 +288,7 @@ public void syncAllUsersOfExternalGroup(String study, String authOrigin, String while (iterator.hasNext()) { User user = iterator.next(); try { - create(user, null, token); + create(organizationId, user, null, token); logger.info("User '{}' ({}) successfully created", user.getId(), user.getName()); } catch (CatalogParameterException e) { logger.warn("Could not create user '{}' ({}). {}", user.getId(), user.getName(), e.getMessage()); @@ -394,7 +309,8 @@ public void syncAllUsersOfExternalGroup(String study, String authOrigin, String logger.info("Associating members to the internal OpenCGA group"); updateParams = new GroupUpdateParams(new ArrayList<>(userList.stream().map(User::getId).collect(Collectors.toSet()))); } - catalogManager.getStudyManager().updateGroup(organizationId, study, group.getId(), ParamUtils.BasicUpdateAction.SET, updateParams, token); + catalogManager.getStudyManager().updateGroup(organizationId, study, group.getId(), ParamUtils.BasicUpdateAction.SET, + updateParams, token); } } if (!foundAny) { @@ -406,19 +322,21 @@ public void syncAllUsersOfExternalGroup(String study, String authOrigin, String * Register all the users belonging to a remote group. If internalGroup and study are not null, it will also associate the remote group * to the internalGroup defined. * - * @param authOrigin Authentication origin. - * @param remoteGroup Group name of the remote authentication origin. - * @param internalGroup Group name in Catalog that will be associated to the remote group. - * @param study Study where the internal group will be associated. - * @param sync Boolean indicating whether the remote group will be synced with the internal group or not. - * @param token JWT token. The token should belong to the root user. + * @param organizationId Organization id. + * @param authOrigin Authentication origin. + * @param remoteGroup Group name of the remote authentication origin. + * @param internalGroup Group name in Catalog that will be associated to the remote group. + * @param study Study where the internal group will be associated. + * @param sync Boolean indicating whether the remote group will be synced with the internal group or not. + * @param token JWT token. The token should belong to the root user. * @throws CatalogException If any of the parameters is wrong or there is any internal error. */ - public void importRemoteGroupOfUsers(String authOrigin, String remoteGroup, @Nullable String internalGroup, @Nullable String study, - boolean sync, String token) throws CatalogException { - String userId = getUserId(token); + public void importRemoteGroupOfUsers(String organizationId, String authOrigin, String remoteGroup, @Nullable String internalGroup, + @Nullable String study, boolean sync, String token) throws CatalogException { + String userId = getUserId(organizationId, token); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("authOrigin", authOrigin) .append("remoteGroup", remoteGroup) .append("internalGroup", internalGroup) @@ -448,7 +366,7 @@ public void importRemoteGroupOfUsers(String authOrigin, String remoteGroup, @Nul userList = authenticationManagerMap.get(authOrigin).getUsersFromRemoteGroup(remoteGroup); for (User user : userList) { try { - create(user, null, token); + create(organizationId, user, null, token); logger.info("User '{}' successfully created", user.getId()); } catch (CatalogException e) { logger.warn("{}", e.getMessage()); @@ -494,17 +412,19 @@ public void importRemoteGroupOfUsers(String authOrigin, String remoteGroup, @Nul /** * Register all the ids. If internalGroup and study are not null, it will also associate the users to the internalGroup defined. * - * @param authOrigin Authentication origin. - * @param idList List of entity ids existing in the authentication origin. - * @param isApplication boolean indicating whether the id list belong to external applications or users. - * @param internalGroup Group name in Catalog that will be associated to the remote group. - * @param study Study where the internal group will be associated. - * @param token JWT token. The token should belong to the root user. + * @param organizationId Organization id. + * @param authOrigin Authentication origin. + * @param idList List of entity ids existing in the authentication origin. + * @param isApplication boolean indicating whether the id list belong to external applications or users. + * @param internalGroup Group name in Catalog that will be associated to the remote group. + * @param study Study where the internal group will be associated. + * @param token JWT token. The token should belong to the root user. * @throws CatalogException If any of the parameters is wrong or there is any internal error. */ - public void importRemoteEntities(String authOrigin, List idList, boolean isApplication, @Nullable String internalGroup, - @Nullable String study, String token) throws CatalogException { + public void importRemoteEntities(String organizationId, String authOrigin, List idList, boolean isApplication, + @Nullable String internalGroup, @Nullable String study, String token) throws CatalogException { ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("authOrigin", authOrigin) .append("idList", idList) .append("isApplication", isApplication) @@ -512,7 +432,7 @@ public void importRemoteEntities(String authOrigin, List idList, boolean .append("study", study) .append("token", token); - String userId = getUserId(token); + String userId = getUserId(organizationId, token); try { if (!OPENCGA.equals(userId)) { @@ -530,7 +450,7 @@ public void importRemoteEntities(String authOrigin, List idList, boolean logger.info("Fetching user information from authentication origin '{}'", authOrigin); List parsedUserList = authenticationManagerMap.get(authOrigin).getRemoteUserInformation(idList); for (User user : parsedUserList) { - create(user, null, token); + create(organizationId, user, null, token); auditManager.audit(userId, Enums.Action.IMPORT_EXTERNAL_USERS, Enums.Resource.USER, user.getId(), "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); logger.info("User '{}' successfully created", user.getId()); @@ -541,7 +461,7 @@ public void importRemoteEntities(String authOrigin, List idList, boolean .setType(Account.AccountType.GUEST) .setAuthentication(new Account.AuthenticationOrigin(authOrigin, true))) .setEmail("mail@mail.co.uk"); - create(application, null, token); + create(organizationId, application, null, token); auditManager.audit(userId, Enums.Action.IMPORT_EXTERNAL_USERS, Enums.Resource.USER, application.getId(), "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); logger.info("User (application) '{}' successfully created", application.getId()); @@ -581,14 +501,15 @@ public void importRemoteEntities(String authOrigin, List idList, boolean /** * Gets the user information. * - * @param userId User id - * @param options QueryOptions - * @param token SessionId of the user performing this operation. + * @param organizationId Organization id. + * @param userId User id + * @param options QueryOptions + * @param token SessionId of the user performing this operation. * @return The requested user * @throws CatalogException CatalogException */ - public OpenCGAResult get(String userId, QueryOptions options, String token) throws CatalogException { - return get(Collections.singletonList(userId), options, token); + public OpenCGAResult get(String organizationId, String userId, QueryOptions options, String token) throws CatalogException { + return get(organizationId, Collections.singletonList(userId), options, token); // ParamUtils.checkParameter(userId, "userId"); // ParamUtils.checkParameter(token, "sessionId"); // options = ParamUtils.defaultObject(options, QueryOptions::new); @@ -599,7 +520,7 @@ public OpenCGAResult get(String userId, QueryOptions options, String token // .append("token", token); // try { // userId = getCatalogUserId(userId, token); -// OpenCGAResult userDataResult = userDBAdaptor.get(userId, options); +// OpenCGAResult userDataResult = getUserDBAdaptor(organizationId).get(userId, options); // // // Remove some unnecessary and prohibited parameters // for (User user : userDataResult.getResults()) { @@ -627,23 +548,25 @@ public OpenCGAResult get(String userId, QueryOptions options, String token /** * Gets the user information. * - * @param userIdList List of user id - * @param options QueryOptions - * @param token Token belonging to the user itself or administrator of any study shared with the user list requested. + * @param organizationId Organization id. + * @param userIdList List of user id + * @param options QueryOptions + * @param token Token belonging to the user itself or administrator of any study shared with the user list requested. * @return The requested users * @throws CatalogException CatalogException */ - public OpenCGAResult get(List userIdList, QueryOptions options, String token) + public OpenCGAResult get(String organizationId, List userIdList, QueryOptions options, String token) throws CatalogException { ParamUtils.checkNotEmptyArray(userIdList, "userId"); ParamUtils.checkParameter(token, "token"); options = ParamUtils.defaultObject(options, QueryOptions::new); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userIdList", userIdList) .append("options", options) .append("token", token); - String userId = getUserId(token); + String userId = getUserId(organizationId, token); String operationUuid = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); auditManager.initAuditBatch(operationUuid); @@ -651,7 +574,7 @@ public OpenCGAResult get(List userIdList, QueryOptions options, St OpenCGAResult userDataResult; if (userIdList.size() == 1 && userId.equals(userIdList.get(0))) { - userDataResult = userDBAdaptor.get(userId, options); + userDataResult = getUserDBAdaptor(organizationId).get(userId, options); auditManager.auditInfo(operationUuid, userId, Enums.Resource.USER, userId, "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); return userDataResult; @@ -661,7 +584,7 @@ public OpenCGAResult get(List userIdList, QueryOptions options, St UserDBAdaptor.QueryParams.PROJECTS.key() + "." + ProjectDBAdaptor.QueryParams.STUDIES.key() + "." + StudyDBAdaptor.QueryParams.GROUPS.key(), UserDBAdaptor.QueryParams.SHARED_PROJECTS.key() + "." + ProjectDBAdaptor.QueryParams.STUDIES.key() + "." + StudyDBAdaptor.QueryParams.GROUPS.key())); - userDataResult = userDBAdaptor.get(userId, adminOptions); + userDataResult = getUserDBAdaptor(organizationId).get(userId, adminOptions); User admin = userDataResult.first(); Set users = new HashSet<>(); @@ -713,7 +636,7 @@ public OpenCGAResult get(List userIdList, QueryOptions options, St List auxUserList = userIdList.stream().filter(users::contains).collect(Collectors.toList()); Query query = new Query(UserDBAdaptor.QueryParams.ID.key(), auxUserList); - OpenCGAResult result = userDBAdaptor.get(query, options); + OpenCGAResult result = getUserDBAdaptor(organizationId).get(query, options); Map userMap = new HashMap<>(); for (User user : result.getResults()) { userMap.put(user.getId(), user); @@ -753,10 +676,12 @@ public OpenCGAResult get(List userIdList, QueryOptions options, St } } - public OpenCGAResult update(String userId, ObjectMap parameters, QueryOptions options, String token) throws CatalogException { - String loggedUser = getUserId(token); + public OpenCGAResult update(String organizationId, String userId, ObjectMap parameters, QueryOptions options, String token) + throws CatalogException { + String loggedUser = getUserId(organizationId, token); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("updateParams", parameters) .append("options", options) @@ -767,7 +692,7 @@ public OpenCGAResult update(String userId, ObjectMap parameters, QueryOpti ParamUtils.checkObj(parameters, "parameters"); ParamUtils.checkParameter(token, "token"); - userId = getCatalogUserId(userId, token); + userId = getCatalogUserId(organizationId, userId, token); for (String s : parameters.keySet()) { if (!s.matches("name|email|organization|attributes")) { throw new CatalogDBException("Parameter '" + s + "' can't be changed"); @@ -777,13 +702,13 @@ public OpenCGAResult update(String userId, ObjectMap parameters, QueryOpti if (parameters.containsKey("email")) { checkEmail(parameters.getString("email")); } - OpenCGAResult updateResult = userDBAdaptor.update(userId, parameters); + OpenCGAResult updateResult = getUserDBAdaptor(organizationId).update(userId, parameters); auditManager.auditUpdate(loggedUser, Enums.Resource.USER, userId, "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); if (options.getBoolean(ParamConstants.INCLUDE_RESULT_PARAM)) { // Fetch updated user - OpenCGAResult result = userDBAdaptor.get(userId, options); + OpenCGAResult result = getUserDBAdaptor(organizationId).get(userId, options); updateResult.setResults(result.getResults()); } @@ -798,23 +723,26 @@ public OpenCGAResult update(String userId, ObjectMap parameters, QueryOpti /** * Delete entries from Catalog. * - * @param userIdList Comma separated list of ids corresponding to the objects to delete - * @param options Deleting options. - * @param token Token + * @param organizationId Organization id. + * @param userIdList Comma separated list of ids corresponding to the objects to delete + * @param options Deleting options. + * @param token Token * @return A list with the deleted objects * @throws CatalogException CatalogException. */ - public OpenCGAResult delete(String userIdList, QueryOptions options, String token) throws CatalogException { + public OpenCGAResult delete(String organizationId, String userIdList, QueryOptions options, String token) + throws CatalogException { ParamUtils.checkParameter(userIdList, "userIdList"); ParamUtils.checkParameter(token, "token"); String operationUuid = UuidUtils.generateOpenCgaUuid(UuidUtils.Entity.AUDIT); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userIdList", userIdList) .append("options", options) .append("token", token); - String tokenUser = getUserId(token); + String tokenUser = getUserId(organizationId, token); List userIds = Arrays.asList(userIdList.split(",")); OpenCGAResult deletedUsers = OpenCGAResult.empty(); @@ -822,7 +750,7 @@ public OpenCGAResult delete(String userIdList, QueryOptions options, Strin // Only if the user asking the deletion is the ADMINISTRATOR or the user to be deleted itself... if (OPENCGA.equals(tokenUser) || userId.equals(tokenUser)) { try { - OpenCGAResult result = userDBAdaptor.delete(userId, options); + OpenCGAResult result = getUserDBAdaptor(organizationId).delete(userId, options); auditManager.auditDelete(operationUuid, tokenUser, Enums.Resource.USER, userId, "", "", "", auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -830,7 +758,7 @@ public OpenCGAResult delete(String userIdList, QueryOptions options, Strin Query query = new Query() .append(UserDBAdaptor.QueryParams.ID.key(), userId) .append(UserDBAdaptor.QueryParams.INTERNAL_STATUS_ID.key(), UserStatus.DELETED); - OpenCGAResult deletedUser = userDBAdaptor.get(query, QueryOptions.empty()); + OpenCGAResult deletedUser = getUserDBAdaptor(organizationId).get(query, QueryOptions.empty()); deletedUser.setTime(deletedUser.getTime() + result.getTime()); deletedUsers.append(deletedUser); @@ -846,32 +774,34 @@ public OpenCGAResult delete(String userIdList, QueryOptions options, Strin /** * Delete the entries satisfying the query. * - * @param query Query of the objects to be deleted. - * @param options Deleting options. - * @param sessionId sessionId. + * @param organizationId Organization id. + * @param query Query of the objects to be deleted. + * @param options Deleting options. + * @param sessionId sessionId. * @return A list with the deleted objects. * @throws CatalogException CatalogException * @throws IOException IOException. */ - public OpenCGAResult delete(Query query, QueryOptions options, String sessionId) throws CatalogException, IOException { + public OpenCGAResult delete(String organizationId, Query query, QueryOptions options, String sessionId) + throws CatalogException, IOException { QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.ID.key()); - OpenCGAResult userDataResult = userDBAdaptor.get(query, queryOptions); + OpenCGAResult userDataResult = getUserDBAdaptor(organizationId).get(query, queryOptions); List userIds = userDataResult.getResults().stream().map(User::getId).collect(Collectors.toList()); String userIdStr = StringUtils.join(userIds, ","); - return delete(userIdStr, options, sessionId); + return delete(organizationId, userIdStr, options, sessionId); } public OpenCGAResult restore(String ids, QueryOptions options, String sessionId) throws CatalogException { throw new UnsupportedOperationException(); } - public OpenCGAResult resetPassword(String userId, String token) throws CatalogException { + public OpenCGAResult resetPassword(String organizationId, String userId, String token) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "token"); try { - String authenticatedUserId = getUserId(token); + String authenticatedUserId = getUserId(organizationId, token); authorizationManager.checkIsInstallationAdministrator(authenticatedUserId); - String authOrigin = getAuthenticationOriginId(userId); + String authOrigin = getAuthenticationOriginId(organizationId, userId); OpenCGAResult writeResult = authenticationManagerMap.get(authOrigin).resetPassword(userId); auditManager.auditUser(userId, Enums.Action.RESET_USER_PASSWORD, userId, @@ -885,18 +815,17 @@ public OpenCGAResult resetPassword(String userId, String token) throws CatalogEx } public AuthenticationResponse loginAsAdmin(String password) throws CatalogException { - return login(OPENCGA, password); + return login(ParamConstants.ADMIN_ORGANIZATION, OPENCGA, password); } public AuthenticationResponse login(String organizationId, String username, String password) throws CatalogException { - ParamUtils.checkParameter(organizationId, "organizationId"); ParamUtils.checkParameter(username, "userId"); ParamUtils.checkParameter(password, "password"); String authId = null; AuthenticationResponse response = null; - OpenCGAResult userOpenCGAResult = userDBAdaptor.get(username, INCLUDE_ACCOUNT); + OpenCGAResult userOpenCGAResult = getUserDBAdaptor(organizationId).get(username, INCLUDE_ACCOUNT); if (userOpenCGAResult.getNumResults() == 1) { authId = userOpenCGAResult.first().getAccount().getAuthentication().getId(); if (!authenticationManagerMap.containsKey(authId)) { @@ -936,89 +865,20 @@ public AuthenticationResponse login(String organizationId, String username, Stri // External authorization try { // If the user is not registered, an exception will be raised - userDBAdaptor.checkId(userId); + getUserDBAdaptor(organizationId).checkId(userId); } catch (CatalogDBException e) { // The user does not exist so we register it User user = authenticationManagerMap.get(authId).getRemoteUserInformation(Collections.singletonList(userId)).get(0); // Generate a root token to be able to create the user even if the installation is private String rootToken = authenticationManagerMap.get(INTERNAL_AUTHORIZATION).createToken(OPENCGA); - create(user, null, rootToken); + create(organizationId, user, null, rootToken); } try { List remoteGroups = authenticationManagerMap.get(authId).getRemoteGroups(response.getToken()); // Resync synced groups of user in OpenCGA - studyDBAdaptor.resyncUserWithSyncedGroups(userId, remoteGroups, authId); - } catch (CatalogException e) { - logger.error("Could not update synced groups for user '" + userId + "'\n" + e.getMessage(), e); - } - } - - return response; - } - - public AuthenticationResponse login(String username, String password) throws CatalogException { - ParamUtils.checkParameter(username, "userId"); - ParamUtils.checkParameter(password, "password"); - - String authId = null; - AuthenticationResponse response = null; - - OpenCGAResult userOpenCGAResult = userDBAdaptor.get(username, INCLUDE_ACCOUNT); - if (userOpenCGAResult.getNumResults() == 1) { - authId = userOpenCGAResult.first().getAccount().getAuthentication().getId(); - if (!authenticationManagerMap.containsKey(authId)) { - throw new CatalogException("Could not authenticate user '" + username + "'. The authentication origin '" + authId - + "' could not be found."); - } - try { - response = authenticationManagerMap.get(authId).authenticate(username, password); - } catch (CatalogAuthenticationException e) { - auditManager.auditUser(username, Enums.Action.LOGIN, username, - new AuditRecord.Status(AuditRecord.Status.Result.ERROR, e.getError())); - throw e; - } - } else { - // We attempt to login the user with the different authentication managers - for (Map.Entry entry : authenticationManagerMap.entrySet()) { - AuthenticationManager authenticationManager = entry.getValue(); - try { - response = authenticationManager.authenticate(username, password); - authId = entry.getKey(); - break; - } catch (CatalogAuthenticationException e) { - logger.debug("Attempted authentication failed with {} for user '{}'\n{}", entry.getKey(), username, e.getMessage(), e); - } - } - } - - if (response == null) { - auditManager.auditUser(username, Enums.Action.LOGIN, username, - new AuditRecord.Status(AuditRecord.Status.Result.ERROR, new Error(0, "", "Incorrect user or password."))); - throw CatalogAuthenticationException.incorrectUserOrPassword(); - } - - auditManager.auditUser(username, Enums.Action.LOGIN, username, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); - String userId = authenticationManagerMap.get(authId).getUserId(response.getToken()); - if (!INTERNAL_AUTHORIZATION.equals(authId)) { - // External authorization - try { - // If the user is not registered, an exception will be raised - userDBAdaptor.checkId(userId); - } catch (CatalogDBException e) { - // The user does not exist so we register it - User user = authenticationManagerMap.get(authId).getRemoteUserInformation(Collections.singletonList(userId)).get(0); - // Generate a root token to be able to create the user even if the installation is private - String rootToken = authenticationManagerMap.get(INTERNAL_AUTHORIZATION).createToken(OPENCGA); - create(user, null, rootToken); - } - - try { - List remoteGroups = authenticationManagerMap.get(authId).getRemoteGroups(response.getToken()); - - // Resync synced groups of user in OpenCGA - studyDBAdaptor.resyncUserWithSyncedGroups(userId, remoteGroups, authId); + getStudyDBAdaptor(organizationId).resyncUserWithSyncedGroups(userId, remoteGroups, authId); } catch (CatalogException e) { logger.error("Could not update synced groups for user '" + userId + "'\n" + e.getMessage(), e); } @@ -1030,11 +890,12 @@ public AuthenticationResponse login(String username, String password) throws Cat /** * Create a new token if the token provided corresponds to the user and it is not expired yet. * - * @param token active token. + * @param organizationId Organization id. + * @param token active token. * @return a new AuthenticationResponse object. * @throws CatalogException if the token does not correspond to the user or the token is expired. */ - public AuthenticationResponse refreshToken(String token) throws CatalogException { + public AuthenticationResponse refreshToken(String organizationId, String token) throws CatalogException { AuthenticationResponse response = null; CatalogAuthenticationException exception = null; String userId = ""; @@ -1066,21 +927,23 @@ public AuthenticationResponse refreshToken(String token) throws CatalogException /** * This method will be only callable by the system. It generates a new session id for the user. * - * @param userId user id for which a session will be generated. - * @param attributes attributes to be put as part of the claims section in the JWT. - * @param expiration Expiration time in seconds. If null, default expiration time will be used. - * @param token Password or active session of the OpenCGA admin. + * @param organizationId Organization id. + * @param userId user id for which a session will be generated. + * @param attributes attributes to be put as part of the claims section in the JWT. + * @param expiration Expiration time in seconds. If null, default expiration time will be used. + * @param token Password or active session of the OpenCGA admin. * @return an objectMap containing the new sessionId * @throws CatalogException if the password is not correct or the userId does not exist. */ - public String getToken(String userId, Map attributes, Long expiration, String token) throws CatalogException { - if (!OPENCGA.equals(getUserId(token))) { + public String getToken(String organizationId, String userId, Map attributes, Long expiration, String token) + throws CatalogException { + if (!OPENCGA.equals(getUserId(organizationId, token))) { throw new CatalogException("Only user '" + OPENCGA + "' is allowed to create tokens"); } if (expiration != null && expiration <= 0) { throw new CatalogException("Expiration time must be higher than 0"); } - AuthenticationManager authManager = getAuthenticationManagerForUser(userId); + AuthenticationManager authManager = getAuthenticationManagerForUser(organizationId, userId); return expiration != null ? authManager.createToken(userId, attributes, expiration) : authManager.createToken(userId, attributes); @@ -1089,22 +952,24 @@ public String getToken(String userId, Map attributes, Long expir /** * This method will be only callable by the system. It generates a new session id for the user. * - * @param userId user id for which a session will be generated. - * @param attributes attributes to be put as part of the claims section in the JWT. - * @param token Password or active session of the OpenCGA admin. + * @param organizationId Organization id. + * @param userId user id for which a session will be generated. + * @param attributes attributes to be put as part of the claims section in the JWT. + * @param token Password or active session of the OpenCGA admin. * @return an objectMap containing the new sessionId * @throws CatalogException if the password is not correct or the userId does not exist. */ - public String getNonExpiringToken(String userId, Map attributes, String token) throws CatalogException { - if (!OPENCGA.equals(getUserId(token))) { + public String getNonExpiringToken(String organizationId, String userId, Map attributes, String token) + throws CatalogException { + if (!OPENCGA.equals(getUserId(organizationId, token))) { throw new CatalogException("Only user '" + OPENCGA + "' is allowed to create tokens"); } - AuthenticationManager authManager = getAuthenticationManagerForUser(userId); + AuthenticationManager authManager = getAuthenticationManagerForUser(organizationId, userId); return authManager.createNonExpiringToken(userId, attributes); } - private AuthenticationManager getAuthenticationManagerForUser(String user) throws CatalogException { - OpenCGAResult userOpenCGAResult = userDBAdaptor.get(user, INCLUDE_ACCOUNT); + private AuthenticationManager getAuthenticationManagerForUser(String organizationId, String user) throws CatalogException { + OpenCGAResult userOpenCGAResult = getUserDBAdaptor(organizationId).get(user, INCLUDE_ACCOUNT); if (userOpenCGAResult.getNumResults() == 1) { String authId = userOpenCGAResult.first().getAccount().getAuthentication().getId(); if (!authenticationManagerMap.containsKey(authId)) { @@ -1121,19 +986,20 @@ private AuthenticationManager getAuthenticationManagerForUser(String user) throw * Add a new filter to the user account. *

* - * @param userId user id to whom the filter will be associated. - * @param id Filter id. - * @param description Filter description. - * @param resource Resource where the filter should be applied. - * @param query Query object. - * @param queryOptions Query options object. - * @param token session id of the user asking to store the filter. + * @param organizationId Organization id. + * @param userId user id to whom the filter will be associated. + * @param id Filter id. + * @param description Filter description. + * @param resource Resource where the filter should be applied. + * @param query Query object. + * @param queryOptions Query options object. + * @param token session id of the user asking to store the filter. * @return the created filter. * @throws CatalogException if there already exists a filter with that same name for the user or if the user corresponding to the * session id is not the same as the provided user id. */ - public OpenCGAResult addFilter(String userId, String id, String description, Enums.Resource resource, Query query, - QueryOptions queryOptions, String token) throws CatalogException { + public OpenCGAResult addFilter(String organizationId, String userId, String id, String description, Enums.Resource resource, + Query query, QueryOptions queryOptions, String token) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "sessionId"); ParamUtils.checkParameter(id, "id"); @@ -1153,18 +1019,18 @@ public OpenCGAResult addFilter(String userId, String id, String desc .append("queryOptions", queryOptions) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); Query queryExists = new Query() .append(UserDBAdaptor.QueryParams.ID.key(), userId) .append(UserDBAdaptor.QueryParams.FILTERS_ID.key(), id); - if (userDBAdaptor.count(queryExists).getNumMatches() > 0) { + if (getUserDBAdaptor(organizationId).count(queryExists).getNumMatches() > 0) { throw new CatalogException("There already exists a filter called " + id + " for user " + userId); } UserFilter filter = new UserFilter(id, description, resource, query, queryOptions); - OpenCGAResult result = userDBAdaptor.addFilter(userId, filter); + OpenCGAResult result = getUserDBAdaptor(organizationId).addFilter(userId, filter); auditManager.auditUser(userId, Enums.Action.CHANGE_USER_CONFIG, userId, auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); return new OpenCGAResult<>(result.getTime(), Collections.emptyList(), 1, Collections.singletonList(filter), 1); @@ -1179,37 +1045,40 @@ public OpenCGAResult addFilter(String userId, String id, String desc * Update the filter information. *

* - * @param userId user id to whom the filter should be updated. - * @param name Filter name. - * @param params Map containing the parameters to be updated. - * @param token session id of the user asking to update the filter. + * @param organizationId Organization id. + * @param userId user id to whom the filter should be updated. + * @param name Filter name. + * @param params Map containing the parameters to be updated. + * @param token session id of the user asking to update the filter. * @return the updated filter. * @throws CatalogException if the filter could not be updated because the filter name is not correct or if the user corresponding to * the session id is not the same as the provided user id. */ - public OpenCGAResult updateFilter(String userId, String name, ObjectMap params, String token) throws CatalogException { + public OpenCGAResult updateFilter(String organizationId, String userId, String name, ObjectMap params, String token) + throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "token"); ParamUtils.checkParameter(name, "name"); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("name", name) .append("params", params) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); Query queryExists = new Query() .append(UserDBAdaptor.QueryParams.ID.key(), userId) .append(UserDBAdaptor.QueryParams.FILTERS_ID.key(), name); - if (userDBAdaptor.count(queryExists).getNumMatches() == 0) { + if (getUserDBAdaptor(organizationId).count(queryExists).getNumMatches() == 0) { throw new CatalogException("There is no filter called " + name + " for user " + userId); } - OpenCGAResult result = userDBAdaptor.updateFilter(userId, name, params); - UserFilter filter = getFilter(userId, name); + OpenCGAResult result = getUserDBAdaptor(organizationId).updateFilter(userId, name, params); + UserFilter filter = getFilter(organizationId, userId, name); if (filter == null) { throw new CatalogException("Internal error: The filter " + name + " could not be found."); } @@ -1227,32 +1096,34 @@ public OpenCGAResult updateFilter(String userId, String name, Object * Delete the filter. *

* - * @param userId user id to whom the filter should be deleted. - * @param name filter name to be deleted. - * @param token session id of the user asking to delete the filter. + * @param organizationId Organization id. + * @param userId user id to whom the filter should be deleted. + * @param name filter name to be deleted. + * @param token session id of the user asking to delete the filter. * @return the deleted filter. * @throws CatalogException when the filter cannot be removed or the name is not correct or if the user corresponding to the session id * is not the same as the provided user id. */ - public OpenCGAResult deleteFilter(String userId, String name, String token) throws CatalogException { + public OpenCGAResult deleteFilter(String organizationId, String userId, String name, String token) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "token"); ParamUtils.checkParameter(name, "name"); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("name", name) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); - UserFilter filter = getFilter(userId, name); + UserFilter filter = getFilter(organizationId, userId, name); if (filter == null) { throw new CatalogException("There is no filter called " + name + " for user " + userId); } - OpenCGAResult result = userDBAdaptor.deleteFilter(userId, name); + OpenCGAResult result = getUserDBAdaptor(organizationId).deleteFilter(userId, name); auditManager.auditUser(userId, Enums.Action.CHANGE_USER_CONFIG, userId, auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); return new OpenCGAResult<>(result.getTime(), Collections.emptyList(), 1, Collections.singletonList(filter), 1); @@ -1267,26 +1138,28 @@ public OpenCGAResult deleteFilter(String userId, String name, String * Retrieves a filter. *

* - * @param userId user id having the filter stored. - * @param name Filter name to be fetched. - * @param token session id of the user fetching the filter. + * @param organizationId Organization id. + * @param userId user id having the filter stored. + * @param name Filter name to be fetched. + * @param token session id of the user fetching the filter. * @return the filter. * @throws CatalogException if the user corresponding to the session id is not the same as the provided user id. */ - public OpenCGAResult getFilter(String userId, String name, String token) throws CatalogException { + public OpenCGAResult getFilter(String organizationId, String userId, String name, String token) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "sessionId"); ParamUtils.checkParameter(name, "name"); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("name", name) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); - UserFilter filter = getFilter(userId, name); + UserFilter filter = getFilter(organizationId, userId, name); auditManager.auditUser(userId, Enums.Action.FETCH_USER_CONFIG, userId, auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -1305,26 +1178,28 @@ public OpenCGAResult getFilter(String userId, String name, String to /** * Retrieves all the user filters. * - * @param userId user id having the filters. - * @param token session id of the user fetching the filters. + * @param organizationId Organization id. + * @param userId user id having the filters. + * @param token session id of the user fetching the filters. * @return the filters. * @throws CatalogException if the user corresponding to the session id is not the same as the provided user id. */ - public OpenCGAResult getAllFilters(String userId, String token) throws CatalogException { + public OpenCGAResult getAllFilters(String organizationId, String userId, String token) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "sessionId"); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); Query query = new Query() .append(UserDBAdaptor.QueryParams.ID.key(), userId); QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.FILTERS.key()); - OpenCGAResult userDataResult = userDBAdaptor.get(query, queryOptions); + OpenCGAResult userDataResult = getUserDBAdaptor(organizationId).get(query, queryOptions); if (userDataResult.getNumResults() != 1) { throw new CatalogException("Internal error: User " + userId + " not found."); @@ -1346,30 +1221,33 @@ public OpenCGAResult getAllFilters(String userId, String token) thro * Creates or updates a configuration. *

* - * @param userId user id to whom the config will be associated. - * @param name Name of the configuration (normally, name of the application). - * @param config Configuration to be stored. - * @param token session id of the user asking to store the config. + * @param organizationId Organization id. + * @param userId user id to whom the config will be associated. + * @param name Name of the configuration (normally, name of the application). + * @param config Configuration to be stored. + * @param token session id of the user asking to store the config. * @return the set configuration. * @throws CatalogException if the user corresponding to the session id is not the same as the provided user id. */ - public OpenCGAResult setConfig(String userId, String name, Map config, String token) throws CatalogException { + public OpenCGAResult setConfig(String organizationId, String userId, String name, Map config, String token) + throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "sessionId"); ParamUtils.checkParameter(name, "name"); ParamUtils.checkObj(config, "ObjectMap"); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("name", name) .append("config", config) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); - OpenCGAResult result = userDBAdaptor.setConfig(userId, name, config); + OpenCGAResult result = getUserDBAdaptor(organizationId).setConfig(userId, name, config); auditManager.auditUser(userId, Enums.Action.CHANGE_USER_CONFIG, userId, auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); @@ -1385,28 +1263,30 @@ public OpenCGAResult setConfig(String userId, String name, Map c * Deletes a configuration. *

* - * @param userId user id to whom the configuration should be deleted. - * @param name Name of the configuration to be deleted (normally, name of the application). - * @param token session id of the user asking to delete the configuration. + * @param organizationId Organization id. + * @param userId user id to whom the configuration should be deleted. + * @param name Name of the configuration to be deleted (normally, name of the application). + * @param token session id of the user asking to delete the configuration. * @return the deleted configuration. * @throws CatalogException if the user corresponding to the session id is not the same as the provided user id or the configuration did * not exist. */ - public OpenCGAResult deleteConfig(String userId, String name, String token) throws CatalogException { + public OpenCGAResult deleteConfig(String organizationId, String userId, String name, String token) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "token"); ParamUtils.checkParameter(name, "name"); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("name", name) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.CONFIGS.key()); - OpenCGAResult userDataResult = userDBAdaptor.get(userId, options); + OpenCGAResult userDataResult = getUserDBAdaptor(organizationId).get(userId, options); if (userDataResult.getNumResults() == 0) { throw new CatalogException("Internal error: Could not get user " + userId); } @@ -1420,7 +1300,7 @@ public OpenCGAResult deleteConfig(String userId, String name, String token) thro throw new CatalogException("Error: Cannot delete configuration with name " + name + ". Configuration name not found."); } - OpenCGAResult result = userDBAdaptor.deleteConfig(userId, name); + OpenCGAResult result = getUserDBAdaptor(organizationId).deleteConfig(userId, name); auditManager.auditUser(userId, Enums.Action.CHANGE_USER_CONFIG, userId, auditParams, new AuditRecord.Status(AuditRecord.Status.Result.SUCCESS)); return new OpenCGAResult(result.getTime(), Collections.emptyList(), 1, Collections.singletonList(configs.get(name)), 1); @@ -1435,27 +1315,29 @@ public OpenCGAResult deleteConfig(String userId, String name, String token) thro * Retrieves a configuration. *

* - * @param userId user id having the configuration stored. - * @param name Name of the configuration to be fetched (normally, name of the application). - * @param token session id of the user attempting to fetch the configuration. + * @param organizationId Organization id. + * @param userId user id having the configuration stored. + * @param name Name of the configuration to be fetched (normally, name of the application). + * @param token session id of the user attempting to fetch the configuration. * @return the configuration. * @throws CatalogException if the user corresponding to the session id is not the same as the provided user id or the configuration * does not exist. */ - public OpenCGAResult getConfig(String userId, String name, String token) throws CatalogException { + public OpenCGAResult getConfig(String organizationId, String userId, String name, String token) throws CatalogException { ParamUtils.checkParameter(userId, "userId"); ParamUtils.checkParameter(token, "sessionId"); ObjectMap auditParams = new ObjectMap() + .append("organizationId", organizationId) .append("userId", userId) .append("name", name) .append("token", token); try { - userId = getCatalogUserId(userId, token); - userDBAdaptor.checkId(userId); + userId = getCatalogUserId(organizationId, userId, token); + getUserDBAdaptor(organizationId).checkId(userId); QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.CONFIGS.key()); - OpenCGAResult userDataResult = userDBAdaptor.get(userId, options); + OpenCGAResult userDataResult = getUserDBAdaptor(organizationId).get(userId, options); if (userDataResult.getNumResults() == 0) { throw new CatalogException("Internal error: Could not get user " + userId); } @@ -1481,11 +1363,11 @@ public OpenCGAResult getConfig(String userId, String name, String token) throws } } - private UserFilter getFilter(String userId, String name) throws CatalogException { + private UserFilter getFilter(String organizationId, String userId, String name) throws CatalogException { Query query = new Query() .append(UserDBAdaptor.QueryParams.ID.key(), userId); QueryOptions queryOptions = new QueryOptions(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.FILTERS.key()); - OpenCGAResult userDataResult = userDBAdaptor.get(query, queryOptions); + OpenCGAResult userDataResult = getUserDBAdaptor(organizationId).get(query, queryOptions); if (userDataResult.getNumResults() != 1) { throw new CatalogException("Internal error: User " + userId + " not found."); @@ -1500,18 +1382,18 @@ private UserFilter getFilter(String userId, String name) throws CatalogException return null; } - private void checkUserExists(String userId) throws CatalogException { + private void checkUserExists(String organizationId, String userId) throws CatalogException { if (userId.toLowerCase().equals(ANONYMOUS)) { throw new CatalogException("Permission denied: Cannot create users with special treatments in catalog."); } - if (userDBAdaptor.exists(userId)) { + if (getUserDBAdaptor(organizationId).exists(userId)) { throw new CatalogException("The user already exists in our database."); } } - private String getAuthenticationOriginId(String userId) throws CatalogException { - OpenCGAResult user = userDBAdaptor.get(userId, new QueryOptions()); + private String getAuthenticationOriginId(String organizationId, String userId) throws CatalogException { + OpenCGAResult user = getUserDBAdaptor(organizationId).get(userId, new QueryOptions()); if (user == null || user.getNumResults() == 0) { throw new CatalogException(userId + " user not found"); } @@ -1523,15 +1405,16 @@ private String getAuthenticationOriginId(String userId) throws CatalogException * fetch the user of the token from Catalog and check whether the email matches. If it matches, it will return the corresponding user * id. * - * @param userId User id provided by the user. - * @param token Token. + * @param organizationId Organization id. + * @param userId User id provided by the user. + * @param token Token. * @return A valid user id for the user and token provided. * @throws CatalogException if the user cannot be retrieved for whatever reason. */ - private String getCatalogUserId(String userId, String token) throws CatalogException { + private String getCatalogUserId(String organizationId, String userId, String token) throws CatalogException { ParamUtils.checkParameter(userId, "User id"); - String userFromToken = getUserId(token); + String userFromToken = getUserId(organizationId, token); if (userFromToken.equals(userId)) { return userId; @@ -1539,7 +1422,7 @@ private String getCatalogUserId(String userId, String token) throws CatalogExcep // User might be using the email as an id QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.EMAIL.key()); - OpenCGAResult userOpenCGAResult = userDBAdaptor.get(userFromToken, options); + OpenCGAResult userOpenCGAResult = getUserDBAdaptor(organizationId).get(userFromToken, options); if (userOpenCGAResult.getNumResults() == 0) { throw new CatalogException("User '" + userFromToken + "' not found. Please, call to login first or talk to your administrator"); } @@ -1574,16 +1457,17 @@ public JwtPayload getTokenPayload(String token) throws CatalogException { /** * Get the userId from the sessionId. * - * @param token Token + * @param organizationId Organization id. + * @param token Token * @return UserId owner of the sessionId. Empty string if SessionId does not match. * @throws CatalogException when the session id does not correspond to any user or the token has expired. */ - public String getUserId(String token) throws CatalogException { + public String getUserId(String organizationId, String token) throws CatalogException { for (Map.Entry entry : authenticationManagerMap.entrySet()) { AuthenticationManager authenticationManager = entry.getValue(); try { String userId = authenticationManager.getUserId(token); - userDBAdaptor.checkId(userId); + getUserDBAdaptor(organizationId).checkId(userId); return userId; } catch (Exception e) { logger.debug("Could not get user from token using {} authentication manager. {}", entry.getKey(), e.getMessage(), e); diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/migration/MigrationManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/migration/MigrationManager.java index a5921bb9cec..4aea6fb7af4 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/migration/MigrationManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/migration/MigrationManager.java @@ -16,7 +16,6 @@ import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.commons.utils.FileUtils; import org.opencb.opencga.catalog.db.DBAdaptorFactory; -import org.opencb.opencga.catalog.db.api.MigrationDBAdaptor; import org.opencb.opencga.catalog.db.mongodb.MongoDBAdaptorFactory; import org.opencb.opencga.catalog.exceptions.CatalogDBException; import org.opencb.opencga.catalog.exceptions.CatalogException; @@ -58,7 +57,7 @@ public class MigrationManager { private final CatalogManager catalogManager; private final Configuration configuration; // private final StorageConfiguration storageConfiguration; - private final MigrationDBAdaptor migrationDBAdaptor; +// private final MigrationDBAdaptor migrationDBAdaptor; private final Logger logger; private final MongoDBAdaptorFactory dbAdaptorFactory; @@ -66,23 +65,23 @@ public class MigrationManager { public MigrationManager(CatalogManager catalogManager, DBAdaptorFactory dbAdaptorFactory, Configuration configuration) { this.catalogManager = catalogManager; this.configuration = configuration; - this.migrationDBAdaptor = dbAdaptorFactory.getMigrationDBAdaptor(); +// this.migrationDBAdaptor = dbAdaptorFactory.getMigrationDBAdaptor(); this.dbAdaptorFactory = (MongoDBAdaptorFactory) dbAdaptorFactory; this.logger = LoggerFactory.getLogger(MigrationManager.class); } - public MigrationRun runManualMigration(String version, String id, Path appHome, ObjectMap params, String token) + public MigrationRun runManualMigration(String organizationId, String version, String id, Path appHome, ObjectMap params, String token) throws CatalogException { - return runManualMigration(version, id, appHome, false, false, params, token); + return runManualMigration(organizationId, version, id, appHome, false, false, params, token); } - public MigrationRun runManualMigration(String version, String id, Path appHome, boolean force, boolean offline, ObjectMap params, - String token) throws CatalogException { - token = validateAdmin(token); + public MigrationRun runManualMigration(String organizationId, String version, String id, Path appHome, boolean force, boolean offline, + ObjectMap params, String token) throws CatalogException { + token = validateAdmin(organizationId, token); for (Class c : getAvailableMigrations()) { Migration migration = getMigrationAnnotation(c); if (migration.id().equals(id) && migration.version().equals(version)) { - MigrationRun migrationRun = updateMigrationRun(migration, token); + MigrationRun migrationRun = updateMigrationRun(organizationId, migration, token); if (!offline && migration.offline()) { throw MigrationException.offlineMigrationException(migration); } @@ -98,19 +97,19 @@ public MigrationRun runManualMigration(String version, String id, Path appHome, break; } } - return run(c, appHome, params, token); + return run(organizationId, c, appHome, params, token); } } throw new MigrationException("Unable to find migration '" + id + "'"); } - public void runMigration(String version, Collection domainsFilter, + public void runMigration(String organizationId, String version, Collection domainsFilter, Collection languageFilter, boolean offline, String appHome, String token) throws CatalogException, IOException { - runMigration(version, domainsFilter, languageFilter, offline, appHome, new ObjectMap(), token); + runMigration(organizationId, version, domainsFilter, languageFilter, offline, appHome, new ObjectMap(), token); } - public void runMigration(String version, Collection domains, + public void runMigration(String organizationId, String version, Collection domains, Collection languages, boolean offline, String appHome, ObjectMap params, String token) throws CatalogException, IOException { @@ -128,18 +127,18 @@ public void runMigration(String version, Collection d Path appHomePath = Paths.get(appHome); FileUtils.checkDirectory(appHomePath); - token = validateAdmin(token); + token = validateAdmin(organizationId, token); // 0. Fetch all migrations - updateMigrationRuns(token); + updateMigrationRuns(organizationId, token); Set> availableMigrations = getAvailableMigrations(); // 1. Fetch required migrations sorted by rank - List> runnableMigrations = filterRunnableMigrations(version, domains, languages, + List> runnableMigrations = filterRunnableMigrations(organizationId, version, domains, languages, availableMigrations); // 2. Get pending migrations - List> pendingMigrations = filterPendingMigrations(version, availableMigrations); + List> pendingMigrations = filterPendingMigrations(organizationId, version, availableMigrations); if (runnableMigrations.isEmpty() && pendingMigrations.isEmpty()) { logger.info("Nothing to run. OpenCGA is up to date"); @@ -172,20 +171,21 @@ public void runMigration(String version, Collection d // 3. Execute pending migrations for (Class migration : pendingMigrations) { - run(migration, appHomePath, new ObjectMap(), token); + run(organizationId, migration, appHomePath, new ObjectMap(), token); } // 4. Execute target migration for (Class migration : runnableMigrations) { - run(migration, appHomePath, params, token); + run(organizationId, migration, appHomePath, params, token); } } - public List> getPendingMigrations(String version, String token) throws CatalogException { - validateAdmin(token); - updateMigrationRuns(token); + public List> getPendingMigrations(String organizationId, String version, String token) + throws CatalogException { + validateAdmin(organizationId, token); + updateMigrationRuns(organizationId, token); Set> availableMigrations = getAvailableMigrations(); - return filterPendingMigrations(version, availableMigrations); + return filterPendingMigrations(organizationId, version, availableMigrations); } private List getMigrations() { @@ -197,8 +197,8 @@ private List getMigrations() { return migrations; } - public MigrationSummary getMigrationSummary() throws CatalogException { - List> runs = getMigrationRuns(null, null, null); + public MigrationSummary getMigrationSummary(String organizationId) throws CatalogException { + List> runs = getMigrationRuns(organizationId, null, null, null); MigrationSummary migrationSummary = new MigrationSummary() .setStatusCount(runs.stream().collect(Collectors.groupingBy( @@ -219,22 +219,23 @@ public MigrationSummary getMigrationSummary() throws CatalogException { return migrationSummary; } - public List> getMigrationRuns(String token) throws CatalogException { - return getMigrationRuns(null, null, null, token); + public List> getMigrationRuns(String organizationId, String token) throws CatalogException { + return getMigrationRuns(organizationId, null, null, null, token); } - public List> getMigrationRuns(String version, List domain, - List status, String token) throws CatalogException { - validateAdmin(token); + public List> getMigrationRuns(String organizationId, String version, + List domain, List status, String token) + throws CatalogException { + validateAdmin(organizationId, token); // 0. Update migration runs - updateMigrationRuns(token); + updateMigrationRuns(organizationId, token); - return getMigrationRuns(version, domain, status); + return getMigrationRuns(organizationId, version, domain, status); } - private List> getMigrationRuns(String version, List domain, - List status) + private List> getMigrationRuns(String organizationId, String version, + List domain, List status) throws CatalogException { // 1. Get migrations and filter @@ -247,7 +248,8 @@ private List> getMigrationRuns(String version, Lis } // 2. Get migration runs and filter by status - List migrationRuns = migrationDBAdaptor.get(migrations.stream().map(Migration::id).collect(Collectors.toList())) + List migrationRuns = dbAdaptorFactory.getMigrationDBAdaptor(organizationId) + .get(migrations.stream().map(Migration::id).collect(Collectors.toList())) .getResults(); Map> map = new HashMap<>(migrations.size()); @@ -277,8 +279,8 @@ private List> getMigrationRuns(String version, Lis } // This method should only be called when installing OpenCGA for the first time so it skips all available (and old) migrations. - public void skipPendingMigrations(String token) throws CatalogException { - validateAdmin(token); + public void skipPendingMigrations(String organizationId, String token) throws CatalogException { + validateAdmin(organizationId, token); // 0. Fetch all migrations Set> availableMigrations = getAvailableMigrations(); @@ -290,28 +292,28 @@ public void skipPendingMigrations(String token) throws CatalogException { MigrationRun migrationRun = new MigrationRun(annotation.id(), annotation.description(), annotation.version(), TimeUtils.getDate(), TimeUtils.getDate(), annotation.patch(), MigrationRun.MigrationStatus.REDUNDANT, ""); try { - migrationDBAdaptor.upsert(migrationRun); + dbAdaptorFactory.getMigrationDBAdaptor(organizationId).upsert(migrationRun); } catch (CatalogDBException e) { throw new MigrationException("Could not register migration in OpenCGA", e); } } } - public void updateMigrationRuns(String token) throws CatalogException { - validateAdmin(token); + public void updateMigrationRuns(String organizationId, String token) throws CatalogException { + validateAdmin(organizationId, token); // 0. Fetch all migrations Set> availableMigrations = getAvailableMigrations(); // 1. Update migration run status for (Class runnableMigration : availableMigrations) { - updateMigrationRun(getMigrationAnnotation(runnableMigration), token); + updateMigrationRun(organizationId, getMigrationAnnotation(runnableMigration), token); } } - private MigrationRun updateMigrationRun(Migration migration, String token) throws CatalogException { - MigrationRun migrationRun = migrationDBAdaptor.get(migration.id()).first(); + private MigrationRun updateMigrationRun(String organizationId, Migration migration, String token) throws CatalogException { + MigrationRun migrationRun = dbAdaptorFactory.getMigrationDBAdaptor(organizationId).get(migration.id()).first(); boolean updated = false; if (migrationRun == null) { @@ -337,7 +339,7 @@ private MigrationRun updateMigrationRun(Migration migration, String token) throw break; case ON_HOLD: // Check jobs - MigrationRun.MigrationStatus status = getOnHoldMigrationRunStatus(migration, migrationRun, token); + MigrationRun.MigrationStatus status = getOnHoldMigrationRunStatus(organizationId, migration, migrationRun, token); migrationRun.setStatus(status); if (status != MigrationRun.MigrationStatus.ON_HOLD) { updated = true; @@ -353,18 +355,19 @@ private MigrationRun updateMigrationRun(Migration migration, String token) throw } } if (updated) { - migrationDBAdaptor.upsert(migrationRun); + dbAdaptorFactory.getMigrationDBAdaptor(organizationId).upsert(migrationRun); } return migrationRun; } - private MigrationRun.MigrationStatus getOnHoldMigrationRunStatus(Migration migration, MigrationRun migrationRun, String token) - throws CatalogException { + private MigrationRun.MigrationStatus getOnHoldMigrationRunStatus(String organizationId, Migration migration, MigrationRun migrationRun, + String token) throws CatalogException { boolean allDone = true; boolean anyError = false; for (JobReferenceParam jobR : migrationRun.getJobs()) { Job job = catalogManager.getJobManager() - .get(organizationId, jobR.getStudyId(), jobR.getId(), new QueryOptions(QueryOptions.INCLUDE, "id,internal"), token).first(); + .get(organizationId, jobR.getStudyId(), jobR.getId(), new QueryOptions(QueryOptions.INCLUDE, "id,internal"), token) + .first(); String jobStatus = job.getInternal().getStatus().getId(); if (jobStatus.equals(Enums.ExecutionStatus.ERROR) || jobStatus.equals(Enums.ExecutionStatus.ABORTED)) { @@ -389,7 +392,7 @@ private MigrationRun.MigrationStatus getOnHoldMigrationRunStatus(Migration migra } } - private List> filterPendingMigrations(String version, + private List> filterPendingMigrations(String organizationId, String version, Set> availableMigrations) throws MigrationException { @@ -420,15 +423,15 @@ private List> filterPendingMigrations(String vers } // Exclude successfully executed migrations - filterOutExecutedMigrations(migrations); + filterOutExecutedMigrations(organizationId, migrations); return migrations; } - private String validateAdmin(String token) throws CatalogException { - String userId = catalogManager.getUserManager().getUserId(token); + private String validateAdmin(String organizationId, String token) throws CatalogException { + String userId = catalogManager.getUserManager().getUserId(organizationId, token); catalogManager.getAuthorizationManager().checkIsInstallationAdministrator(userId); // Extend token life - return catalogManager.getUserManager().getNonExpiringToken(AbstractManager.OPENCGA, Collections.emptyMap(), token); + return catalogManager.getUserManager().getNonExpiringToken(organizationId, AbstractManager.OPENCGA, Collections.emptyMap(), token); } private Set> getAvailableMigrations() { @@ -540,7 +543,7 @@ protected static int compareVersion(String version1, String version2) { return 0; } - private List> filterRunnableMigrations(String version, + private List> filterRunnableMigrations(String organizationId, String version, Collection domain, Collection language, Set> allMigrations) @@ -562,12 +565,12 @@ private List> filterRunnableMigrations(String ver .sorted(this::compareTo) .collect(Collectors.toList()); - filterOutExecutedMigrations(filteredMigrations); + filterOutExecutedMigrations(organizationId, filteredMigrations); return filteredMigrations; } - private MigrationRun run(Class runnableMigration, Path appHome, ObjectMap params, String token) - throws MigrationException { + private MigrationRun run(String organizationId, Class runnableMigration, Path appHome, ObjectMap params, + String token) throws MigrationException { Migration annotation = getMigrationAnnotation(runnableMigration); MigrationTool migrationTool; @@ -580,7 +583,7 @@ private MigrationRun run(Class runnableMigration, Path Date start = TimeUtils.getDate(); MigrationRun migrationRun; try { - migrationRun = migrationDBAdaptor.get(annotation.id()).first(); + migrationRun = dbAdaptorFactory.getMigrationDBAdaptor(organizationId).get(annotation.id()).first(); if (migrationRun == null) { migrationRun = new MigrationRun(); } @@ -625,7 +628,7 @@ private MigrationRun run(Class runnableMigration, Path if (migrationRun.getJobs().isEmpty()) { status = MigrationRun.MigrationStatus.DONE; } else { - status = getOnHoldMigrationRunStatus(migrationTool.getAnnotation(), migrationRun, token); + status = getOnHoldMigrationRunStatus(organizationId, migrationTool.getAnnotation(), migrationRun, token); } } // Clear exception @@ -664,9 +667,10 @@ private MigrationRun run(Class runnableMigration, Path migrationRun.setPatch(annotation.patch()); try { String adminStudy = "opencga@admin:admin"; - migrationDBAdaptor.upsert(migrationRun); + dbAdaptorFactory.getMigrationDBAdaptor(organizationId).upsert(migrationRun); OpenCGAResult outdir = catalogManager.getFileManager() - .createFolder(organizationId, adminStudy, path, true, "Migration job " + migrationRun.getId(), null, QueryOptions.empty(), token); + .createFolder(organizationId, adminStudy, path, true, "Migration job " + migrationRun.getId(), null, + QueryOptions.empty(), token); OpenCGAResult stderr = catalogManager.getFileManager() .link(organizationId, adminStudy, new FileLinkParams() .setPath(Paths.get(path, logFile).toString()) @@ -722,12 +726,13 @@ private MigrationRun run(Class runnableMigration, Path return migrationRun; } - private void filterOutExecutedMigrations(List> migrations) throws MigrationException { + private void filterOutExecutedMigrations(String organizationId, List> migrations) + throws MigrationException { // Remove migrations successfully executed from list List migrationIdList = migrations.stream().map(m -> getMigrationAnnotation(m).id()).collect(Collectors.toList()); OpenCGAResult migrationResult; try { - migrationResult = migrationDBAdaptor.get(migrationIdList); + migrationResult = dbAdaptorFactory.getMigrationDBAdaptor(organizationId).get(migrationIdList); } catch (CatalogDBException e) { throw new MigrationException(e.getMessage(), e); } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/TemplateManager.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/TemplateManager.java index 457b0d4d775..0019269c283 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/TemplateManager.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/TemplateManager.java @@ -79,23 +79,24 @@ public void execute(TemplateManifest manifest, Path path) throws CatalogExceptio List projectIndexVcfJobIds = new ArrayList<>(); List statsJobIds = new ArrayList<>(); + String organizationId = manifest.getConfiguration().getOrganizationId(); TemplateStudy study = manifest.getStudy(); // NOTE: Do not change the order of the following resource creation. - String studyFqn = addStudyMetadata(manifest.getConfiguration().getProjectId(), study); + String studyFqn = addStudyMetadata(organizationId, manifest.getConfiguration().getProjectId(), study); - createIndividuals(studyFqn, path); - createSamples(studyFqn, path); - createCohorts(studyFqn, path); - createFamilies(studyFqn, path); - createPanels(studyFqn, path); - createClinicalAnalyses(studyFqn, path); + createIndividuals(organizationId, studyFqn, path); + createSamples(organizationId, studyFqn, path); + createCohorts(organizationId, studyFqn, path); + createFamilies(organizationId, studyFqn, path); + createPanels(organizationId, studyFqn, path); + createClinicalAnalyses(organizationId, studyFqn, path); // TODO: What is this? // if (study.getVariantEngineConfiguration() != null) { // configureVariantEngine(studyFqn, study); // } - createFiles(studyFqn, path); + createFiles(organizationId, studyFqn, path); // if (CollectionUtils.isNotEmpty(study.getFiles())) { // List studyIndexVcfJobIds = fetchFiles(template, studyFqn, study); // projectIndexVcfJobIds.addAll(studyIndexVcfJobIds); @@ -114,6 +115,9 @@ public void validate(TemplateManifest manifest) throws CatalogException { if (manifest.getConfiguration() == null) { throw new IllegalStateException("Missing 'configuration' section from the Manifest file"); } + if (StringUtils.isEmpty(manifest.getConfiguration().getOrganizationId())) { + throw new IllegalStateException("Missing 'configuration.organizationId' from the Manifest file"); + } if (StringUtils.isEmpty(manifest.getConfiguration().getProjectId())) { throw new IllegalStateException("Missing 'configuration.projectId' from the Manifest file"); } @@ -129,7 +133,7 @@ public void validate(TemplateManifest manifest) throws CatalogException { String version = gitRepositoryState.getBuildVersion(); String versionShort; if (version.contains("-")) { - logger.warn("Using development OpenCGA version: " + version); + logger.warn("Using development OpenCGA version: {}", version); versionShort = version.split("-")[0]; } else { versionShort = version; @@ -138,8 +142,9 @@ public void validate(TemplateManifest manifest) throws CatalogException { checkVersion(versionShort, templateVersion); // Study should already exist - Study study = getStudy(manifest.getConfiguration().getProjectId(), manifest.getStudy().getId()); - String userId = catalogManager.getUserManager().getUserId(token); + Study study = getStudy(manifest.getConfiguration().getOrganizationId(), manifest.getConfiguration().getProjectId(), + manifest.getStudy().getId()); + String userId = catalogManager.getUserManager().getUserId(manifest.getConfiguration().getOrganizationId(), token); catalogManager.getAuthorizationManager().checkIsOwnerOrAdmin(study.getUid(), userId); // // Check if any study exists before we start, if a study exists we should fail. Projects are allowed to exist. @@ -166,17 +171,17 @@ private void checkVersion(String opencgaVersion, String templateVersion) { } } logger.warn("Using a template version lower than the OpenCGA installation version. Some things may not work properly. " - + "Template version: " + templateVersion + ", OpenCGA version: " + opencgaVersion); + + "Template version: {}, OpenCGA version: {}", templateVersion, opencgaVersion); } - private Study getStudy(String projectId, String studyId) throws CatalogException { + private Study getStudy(String organizationId, String projectId, String studyId) throws CatalogException { OpenCGAResult studyOpenCGAResult = catalogManager.getStudyManager().get(organizationId, projectId + ":" + studyId, QueryOptions.empty(), token); return studyOpenCGAResult.first(); } - private String addStudyMetadata(String projectId, TemplateStudy tmplStudy) throws CatalogException { - Study origStudy = getStudy(projectId, tmplStudy.getId()); + private String addStudyMetadata(String organizationId, String projectId, TemplateStudy tmplStudy) throws CatalogException { + Study origStudy = getStudy(organizationId, projectId, tmplStudy.getId()); String fqn; // if (origStudy == null) { // Study study = new Study() @@ -261,7 +266,7 @@ private String addStudyMetadata(String projectId, TemplateStudy tmplStudy) throw // return openCGAClient.getUserId() + "@" + project.getId() + ":" + study.getId(); // } - private void createIndividuals(String studyFqn, Path path) throws CatalogException { + private void createIndividuals(String organizationId, String studyFqn, Path path) throws CatalogException { boolean hasParents = false; // Process/Create individuals without parents try (TemplateEntryIterator iterator = @@ -293,7 +298,8 @@ private void createIndividuals(String studyFqn, Path path) throws CatalogExcepti // Create individual logger.info("Create individual '{}'", individual.getId()); - catalogManager.getIndividualManager().create(organizationId, studyFqn, individual.toIndividual(), QueryOptions.empty(), token); + catalogManager.getIndividualManager().create(organizationId, studyFqn, individual.toIndividual(), QueryOptions.empty(), + token); count++; } else if (overwrite) { @@ -302,7 +308,8 @@ private void createIndividuals(String studyFqn, Path path) throws CatalogExcepti individual.setId(null); logger.info("Update individual '{}'", individual.getId()); - catalogManager.getIndividualManager().update(organizationId, studyFqn, individualId, individual, QueryOptions.empty(), token); + catalogManager.getIndividualManager().update(organizationId, studyFqn, individualId, individual, QueryOptions.empty(), + token); count++; } @@ -329,8 +336,8 @@ private void createIndividuals(String studyFqn, Path path) throws CatalogExcepti .setMother(individual.getMother()); logger.info("Updating individual '{}' parents", individual.getId()); - catalogManager.getIndividualManager().update(organizationId, studyFqn, individual.getId(), updateParams, QueryOptions.empty(), - token); + catalogManager.getIndividualManager().update(organizationId, studyFqn, individual.getId(), updateParams, + QueryOptions.empty(), token); count++; } @@ -423,7 +430,7 @@ private boolean hasParents(IndividualUpdateParams individual) { // } // } - private void createSamples(String studyFqn, Path path) throws CatalogException { + private void createSamples(String organizationId, String studyFqn, Path path) throws CatalogException { // Process/Create samples try (TemplateEntryIterator iterator = new TemplateEntryIterator<>(path, "samples", SampleUpdateParams.class)) { @@ -453,7 +460,7 @@ private void createSamples(String studyFqn, Path path) throws CatalogException { sample.setId(null); logger.info("Update sample '{}'", sample.getId()); - catalogManager.getSampleManager().update(studyFqn, sampleId, sample, QueryOptions.empty(), token); + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, sample, QueryOptions.empty(), token); count++; } @@ -464,7 +471,7 @@ private void createSamples(String studyFqn, Path path) throws CatalogException { } } - private void createCohorts(String studyFqn, Path path) throws CatalogException { + private void createCohorts(String organizationId, String studyFqn, Path path) throws CatalogException { // Process/Create cohorts try (TemplateEntryIterator iterator = new TemplateEntryIterator<>(path, "cohorts", CohortUpdateParams.class)) { @@ -506,7 +513,7 @@ private void createCohorts(String studyFqn, Path path) throws CatalogException { } } - private void createFamilies(String studyFqn, Path path) throws CatalogException { + private void createFamilies(String organizationId, String studyFqn, Path path) throws CatalogException { // Process/Create families try (TemplateEntryIterator iterator = new TemplateEntryIterator<>(path, "families", FamilyUpdateParams.class)) { @@ -532,7 +539,8 @@ private void createFamilies(String studyFqn, Path path) throws CatalogException if (CollectionUtils.isNotEmpty(completeFamily.getMembers())) { List memberIds = completeFamily.getMembers().stream().map(Individual::getId).collect(Collectors.toList()); completeFamily.setMembers(null); - catalogManager.getFamilyManager().create(organizationId, studyFqn, completeFamily, memberIds, QueryOptions.empty(), token); + catalogManager.getFamilyManager().create(organizationId, studyFqn, completeFamily, memberIds, QueryOptions.empty(), + token); } else { catalogManager.getFamilyManager().create(organizationId, studyFqn, family.toFamily(), QueryOptions.empty(), token); } @@ -555,7 +563,7 @@ private void createFamilies(String studyFqn, Path path) throws CatalogException } } - private void createPanels(String studyFqn, Path path) throws CatalogException { + private void createPanels(String organizationId, String studyFqn, Path path) throws CatalogException { // Process/Create panels try (TemplateEntryIterator iterator = new TemplateEntryIterator<>(path, "panels", PanelUpdateParams.class)) { @@ -586,7 +594,7 @@ private void createPanels(String studyFqn, Path path) throws CatalogException { panel.setId(null); logger.info("Update panel '{}'", panel.getId()); - catalogManager.getPanelManager().update(studyFqn, panelId, panel, QueryOptions.empty(), token); + catalogManager.getPanelManager().update(organizationId, studyFqn, panelId, panel, QueryOptions.empty(), token); count++; } @@ -597,7 +605,7 @@ private void createPanels(String studyFqn, Path path) throws CatalogException { } } - private void createClinicalAnalyses(String studyFqn, Path path) throws CatalogException { + private void createClinicalAnalyses(String organizationId, String studyFqn, Path path) throws CatalogException { // Process/Create Clinical Anlyses try (TemplateEntryIterator iterator = new TemplateEntryIterator<>(path, "clinical", ClinicalAnalysisUpdateParams.class)) { @@ -606,7 +614,8 @@ private void createClinicalAnalyses(String studyFqn, Path path) throws CatalogEx ClinicalAnalysisUpdateParams clinical = iterator.next(); Query query = new Query(ClinicalAnalysisDBAdaptor.QueryParams.ID.key(), clinical.getId()); - boolean exists = catalogManager.getClinicalAnalysisManager().count(organizationId, studyFqn, query, token).getNumMatches() > 0; + boolean exists = catalogManager.getClinicalAnalysisManager().count(organizationId, studyFqn, query, token) + .getNumMatches() > 0; if (exists && !resume) { throw new CatalogException("Clinical Analysis '" + clinical.getId() @@ -620,8 +629,8 @@ private void createClinicalAnalyses(String studyFqn, Path path) throws CatalogEx // Create Clinical Analysis logger.info("Create Clinical Analysis '{}'", clinical.getId()); - catalogManager.getClinicalAnalysisManager().create(organizationId, studyFqn, clinical.toClinicalAnalysis(), QueryOptions.empty(), - token); + catalogManager.getClinicalAnalysisManager().create(organizationId, studyFqn, clinical.toClinicalAnalysis(), + QueryOptions.empty(), token); count++; } else if (overwrite) { @@ -630,7 +639,8 @@ private void createClinicalAnalyses(String studyFqn, Path path) throws CatalogEx clinical.setId(null); logger.info("Update Clinical Analysis '{}'", clinical.getId()); - catalogManager.getClinicalAnalysisManager().update(organizationId, studyFqn, clinicalId, clinical, QueryOptions.empty(), token); + catalogManager.getClinicalAnalysisManager().update(organizationId, studyFqn, clinicalId, clinical, QueryOptions.empty(), + token); count++; } @@ -641,7 +651,7 @@ private void createClinicalAnalyses(String studyFqn, Path path) throws CatalogEx } } - private void createFiles(String studyFqn, Path path) throws CatalogException { + private void createFiles(String organizationId, String studyFqn, Path path) throws CatalogException { // Process/Create Files try (TemplateEntryIterator iterator = new TemplateEntryIterator<>(path, "files", TemplateFile.class)) { diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/config/TemplateConfiguration.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/config/TemplateConfiguration.java index 62de832f445..20e7b293eae 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/config/TemplateConfiguration.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/templates/config/TemplateConfiguration.java @@ -21,6 +21,7 @@ public class TemplateConfiguration { private String version; private String baseUrl; private boolean index; + private String organizationId; private String projectId; @Override @@ -29,6 +30,7 @@ public String toString() { sb.append("version='").append(version).append('\''); sb.append(", baseUrl='").append(baseUrl).append('\''); sb.append(", index=").append(index); + sb.append(", organizationId='").append(organizationId).append('\''); sb.append(", projectId='").append(projectId).append('\''); sb.append('}'); return sb.toString(); @@ -58,6 +60,15 @@ public void setIndex(boolean index) { this.index = index; } + public String getOrganizationId() { + return organizationId; + } + + public TemplateConfiguration setOrganizationId(String organizationId) { + this.organizationId = organizationId; + return this; + } + public String getProjectId() { return projectId; } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogDemo.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogDemo.java index 2072a429f00..80cb628a5e8 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogDemo.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogDemo.java @@ -19,6 +19,8 @@ import org.opencb.commons.datastore.core.QueryOptions; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.catalog.managers.CatalogManager; +import org.opencb.opencga.core.models.organizations.OrganizationCreateParams; +import org.opencb.opencga.core.models.organizations.OrganizationUpdateParams; import org.opencb.opencga.core.models.study.Group; import org.opencb.opencga.core.models.study.GroupUpdateParams; import org.opencb.opencga.core.models.study.StudyAclParams; @@ -40,22 +42,33 @@ private CatalogDemo() { * Populates the database with dummy data. * * @param catalogManager Catalog manager instance. - * @param adminPassword Administrator password. - * @param force Used in the case where a database already exists with the same name. When force = true, it will override it. + * @param organizationId Organization id for the demo. + * @param adminPassword Administrator password. + * @param force Used in the case where a database already exists with the same name. When force = true, it will override it. * @throws CatalogException when there is already a database with the same name and force is false. */ - public static void createDemoDatabase(CatalogManager catalogManager, String adminPassword, boolean force) + public static void createDemoDatabase(CatalogManager catalogManager, String organizationId, String adminPassword, boolean force) throws CatalogException { catalogManager.installCatalogDB(catalogManager.getConfiguration().getAdmin().getSecretKey(), adminPassword, "opencga@admin.com", force); + String token = catalogManager.getUserManager().loginAsAdmin(adminPassword).getToken(); try { - populateDatabase(catalogManager); + populateDatabase(catalogManager, organizationId, token); } catch (IOException e) { throw new CatalogException(e.getMessage()); } } - private static void populateDatabase(CatalogManager catalogManager) throws CatalogException, IOException { + private static void populateDatabase(CatalogManager catalogManager, String organizationId, String opencgaToken) + throws CatalogException, IOException { + catalogManager.getOrganizationManager().create(new OrganizationCreateParams().setId(organizationId), QueryOptions.empty(), + opencgaToken); + catalogManager.getUserManager().create(organizationId, "owner", "owner", "owner@mail.com", "owner_pass", organizationId, 2000L, + Account.AccountType.FULL, null); + catalogManager.getOrganizationManager().update(organizationId, new OrganizationUpdateParams().setOwner("owner"), + QueryOptions.empty(), opencgaToken); + String ownerToken = catalogManager.getUserManager().login(organizationId, "owner", "owner_pass").getToken(); + // Create users Map userSessions = new HashMap<>(5); for (int i = 1; i <= 5; i++) { @@ -63,15 +76,17 @@ private static void populateDatabase(CatalogManager catalogManager) throws Catal String name = "User" + i; String password = id + "_pass"; String email = id + "@gmail.com"; - catalogManager.getUserManager().create(id, name, email, password, "organization", 2000L, Account.AccountType.FULL, null); - userSessions.put(id, catalogManager.getUserManager().login(id, password).getToken()); + catalogManager.getUserManager().create(organizationId, id, name, email, password, organizationId, 2000L, + Account.AccountType.FULL, ownerToken); + userSessions.put(id, catalogManager.getUserManager().login(organizationId, id, password).getToken()); } // Create one project per user Map projects = new HashMap<>(5); for (Map.Entry userSession : userSessions.entrySet()) { - projects.put(userSession.getKey(), catalogManager.getProjectManager().create("default", "DefaultProject", "Description", - "Homo sapiens", null, "GrCh38", new QueryOptions(), userSession.getValue()).first().getFqn()); + projects.put(userSession.getKey(), catalogManager.getProjectManager() + .create(organizationId, "default", "DefaultProject", "Description", "Homo sapiens", null, "GrCh38", new QueryOptions(), + userSession.getValue()).first().getFqn()); } // Create two studies per user @@ -82,8 +97,8 @@ private static void populateDatabase(CatalogManager catalogManager) throws Catal for (int i = 1; i <= 2; i++) { String name = "Name of study" + i; String id = "study" + i; - studiesTmp.add(catalogManager.getStudyManager().create(projectId, id, id, name, "Description of " + id, null, - null, null, null, null, userSession.getValue()).first().getFqn()); + studiesTmp.add(catalogManager.getStudyManager().create(organizationId, projectId, id, id, name, "Description of " + id, + null, null, null, null, null, userSession.getValue()).first().getFqn()); } studies.put(userSession.getKey(), studiesTmp); } @@ -98,14 +113,16 @@ private static void populateDatabase(CatalogManager catalogManager) throws Catal catalogManager.getStudyManager().updateGroup(organizationId, studyId, "@admins", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("user5")), userSessions.get("user1")); // user5 will add the rest of users. user2, user3 and user4 go to group "members" - catalogManager.getStudyManager().createGroup(organizationId, studyId, new Group("analyst", Arrays.asList("user2", "user3", "user4")), - sessionId); + catalogManager.getStudyManager().createGroup(organizationId, studyId, new Group("analyst", + Arrays.asList("user2", "user3", "user4")), sessionId); // // @members will have the role "analyst" StudyAclParams aclParams1 = new StudyAclParams("", "analyst"); - catalogManager.getStudyManager().updateAcl(organizationId, Arrays.asList(studyId), "@analyst", aclParams1, ParamUtils.AclAction.ADD, sessionId); + catalogManager.getStudyManager().updateAcl(organizationId, Arrays.asList(studyId), "@analyst", aclParams1, ParamUtils.AclAction.ADD, + sessionId); // // Add anonymous user to the role "denyAll". Later we will give it permissions to see some concrete samples. StudyAclParams aclParams = new StudyAclParams("", "locked"); - catalogManager.getStudyManager().updateAcl(organizationId, Arrays.asList(studyId), "*", aclParams, ParamUtils.AclAction.ADD, sessionId); + catalogManager.getStudyManager().updateAcl(organizationId, Arrays.asList(studyId), "*", aclParams, ParamUtils.AclAction.ADD, + sessionId); } } diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoader.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoader.java index 524ea99b22f..2b51eeb5760 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoader.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoader.java @@ -59,7 +59,8 @@ protected CatalogSampleAnnotationsLoader() { this.catalogManager = null; } - public DataResult loadSampleAnnotations(File pedFile, String variableSetId, String sessionId) throws CatalogException { + public DataResult loadSampleAnnotations(String organizationId, File pedFile, String variableSetId, String sessionId) + throws CatalogException { if (!pedFile.getFormat().equals(File.Format.PED)) { throw new CatalogException(pedFile.getUid() + " is not a pedigree file"); } @@ -76,7 +77,8 @@ public DataResult loadSampleAnnotations(File pedFile, String variableSet //Take or infer the VariableSet VariableSet variableSet; if (variableSetId != null) { - variableSet = catalogManager.getStudyManager().getVariableSet(organizationId, study.getFqn(), variableSetId, null, sessionId).first(); + variableSet = catalogManager.getStudyManager().getVariableSet(organizationId, study.getFqn(), variableSetId, null, sessionId) + .first(); } else { variableSet = getVariableSetFromPedFile(ped); AnnotationUtils.checkVariableSet(variableSet); @@ -105,8 +107,8 @@ public DataResult loadSampleAnnotations(File pedFile, String variableSet List variableList = new ArrayList<>(); variableList.addAll(variableSet.getVariables()); String name = pedFile.getName(); - variableSet = catalogManager.getStudyManager().createVariableSet(organizationId, study.getFqn(), name, name, true, false, "Auto-generated " - + "VariableSet from File = {path: " + pedFile.getPath() + ", name: \"" + pedFile.getName() + "\"}", null, + variableSet = catalogManager.getStudyManager().createVariableSet(organizationId, study.getFqn(), name, name, true, false, + "Auto-generated VariableSet from File = {path: " + pedFile.getPath() + ", name: \"" + pedFile.getName() + "\"}", null, variableList, Collections.singletonList(VariableSet.AnnotableDataModels.SAMPLE), sessionId).getResults().get(0); variableSetId = variableSet.getId(); logger.debug("Added VariableSet = {id: {}} in {}ms", variableSetId, System.currentTimeMillis() - auxTime); @@ -115,7 +117,8 @@ public DataResult loadSampleAnnotations(File pedFile, String variableSet //Add Samples Query samplesQuery = new Query(SampleDBAdaptor.QueryParams.ID.key(), new LinkedList<>(ped.getIndividuals().keySet())); Map loadedSamples = new HashMap<>(); - for (Sample sample : catalogManager.getSampleManager().search(organizationId, study.getFqn(), samplesQuery, null, sessionId).getResults()) { + for (Sample sample : catalogManager.getSampleManager().search(organizationId, study.getFqn(), samplesQuery, null, sessionId) + .getResults()) { loadedSamples.put(sample.getId(), sample); } @@ -130,7 +133,7 @@ public DataResult loadSampleAnnotations(File pedFile, String variableSet sample = loadedSamples.get(individual.getId()); logger.info("Sample " + individual.getId() + " already loaded with id : " + sample.getId()); logger.info("Annotating sample {}", individual.getId()); - catalogManager.getSampleManager().update(study.getFqn(), individual.getId(), new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, study.getFqn(), individual.getId(), new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(annotationSet)), options, sessionId); } else { DataResult sampleDataResult = catalogManager.getSampleManager().create(organizationId, study.getFqn(), diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileMetadataReader.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileMetadataReader.java index 830f5e7aa84..701c7a3c326 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileMetadataReader.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileMetadataReader.java @@ -78,7 +78,7 @@ public void addMetadataInformation(String studyId, File file) throws CatalogExce file.setSize(updateParams.getSize() != null ? updateParams.getSize() : file.getSize()); } - public File updateMetadataInformation(String studyId, File file, String token) throws CatalogException { + public File updateMetadataInformation(String organizationId, String studyId, File file, String token) throws CatalogException { try { FileUpdateParams updateParams = extractMetadataInformation(studyId, file); ObjectMap updateMap = updateParams.getUpdateMap(); @@ -96,7 +96,8 @@ public File updateMetadataInformation(String studyId, File file, String token) t }); if (!missingSamples.isEmpty()) { for (String missingSample : missingSamples) { - catalogManager.getSampleManager().create(organizationId, studyId, new Sample().setId(missingSample), new QueryOptions(), token); + catalogManager.getSampleManager().create(organizationId, studyId, new Sample().setId(missingSample), + new QueryOptions(), token); } } } @@ -123,7 +124,8 @@ public File updateMetadataInformation(String studyId, File file, String token) t progressLogger.increment(samplesBatch.size()); } - catalogManager.getFileManager().update(organizationId, studyId, file.getUuid(), updateParams, QueryOptions.empty(), token); + catalogManager.getFileManager().update(organizationId, studyId, file.getUuid(), updateParams, QueryOptions.empty(), + token); } else { catalogManager.getFileManager().update(organizationId, studyId, file.getUuid(), updateParams, new QueryOptions(Constants.ACTIONS, diff --git a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileScanner.java b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileScanner.java index a8e282c8c6a..e84d8836a8f 100644 --- a/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileScanner.java +++ b/opencga-catalog/src/main/java/org/opencb/opencga/catalog/utils/FileScanner.java @@ -73,23 +73,26 @@ public FileScanner(CatalogManager catalogManager) { * Set file status {@link FileStatus#MISSING} if the file (fileUri) is unreachable * Set file status to {@link FileStatus#READY} if was {@link FileStatus#MISSING} and file (fileUri) is reachable * + * @param organizationId Organization id. * @param study The study to check - * @param sessionId User sessionId * @param calculateChecksum Calculate checksum for "found files" + * @param sessionId User sessionId * @return found and lost files * @throws CatalogException if a Catalog error occurs */ - public List checkStudyFiles(Study study, boolean calculateChecksum, String sessionId) throws CatalogException { + public List checkStudyFiles(String organizationId, Study study, boolean calculateChecksum, String sessionId) + throws CatalogException { Query query = new Query(); query.put(FileDBAdaptor.QueryParams.INTERNAL_STATUS_ID.key(), Arrays.asList( FileStatus.READY, FileStatus.MISSING, FileStatus.TRASHED)); - DBIterator iterator = catalogManager.getFileManager().iterator(organizationId, study.getFqn(), query, new QueryOptions(), sessionId); + DBIterator iterator = catalogManager.getFileManager().iterator(organizationId, study.getFqn(), query, new QueryOptions(), + sessionId); List modifiedFiles = new LinkedList<>(); while (iterator.hasNext()) { File file = iterator.next(); - File checkedFile = catalogFileUtils.checkFile(study.getFqn(), file, calculateChecksum, sessionId); + File checkedFile = catalogFileUtils.checkFile(organizationId, study.getFqn(), file, calculateChecksum, sessionId); if (checkedFile != file) { modifiedFiles.add(checkedFile); } @@ -101,6 +104,7 @@ public List checkStudyFiles(Study study, boolean calculateChecksum, String /** * Scan the study folder, add all untracked files and check tracking. * + * @param organizationId Organization id. * @param study Study to resync * @param calculateChecksum Calculates checksum of all the files in the directory to scan * @param sessionId User sessionId @@ -108,19 +112,20 @@ public List checkStudyFiles(Study study, boolean calculateChecksum, String * @throws CatalogException if a Catalog error occurs * @throws IOException if an I/O error occurs */ - public List reSync(Study study, boolean calculateChecksum, String sessionId) throws CatalogException, IOException { + public List reSync(String organizationId, Study study, boolean calculateChecksum, String sessionId) + throws CatalogException, IOException { Query query = new Query(FileDBAdaptor.QueryParams.TYPE.key(), File.Type.DIRECTORY); DBIterator iterator = catalogManager.getFileManager().iterator(organizationId, study.getFqn(), query, null, sessionId); List scan = new LinkedList<>(); while (iterator.hasNext()) { File folder = iterator.next(); - scan.addAll(scan(folder, catalogManager.getFileManager().getUri(organizationId, folder), FileScannerPolicy.REPLACE, calculateChecksum, - false, sessionId)); + scan.addAll(scan(organizationId, folder, catalogManager.getFileManager().getUri(organizationId, folder), + FileScannerPolicy.REPLACE, calculateChecksum, false, sessionId)); } // TODO: Scan per file - scan.addAll(checkStudyFiles(study, calculateChecksum, sessionId)); + scan.addAll(checkStudyFiles(organizationId, study, calculateChecksum, sessionId)); return scan; } @@ -128,12 +133,13 @@ public List reSync(Study study, boolean calculateChecksum, String sessionI /** * Return all untracked files in a study folder. * - * @param study Study to scan - * @param sessionId User sessionId + * @param organizationId Organization id. + * @param study Study to scan + * @param sessionId User sessionId * @return Untracked files * @throws CatalogException if a Catalog error occurs */ - public Map untrackedFiles(Study study, String sessionId) throws CatalogException { + public Map untrackedFiles(String organizationId, Study study, String sessionId) throws CatalogException { long studyId = study.getUid(); URI studyUri = study.getUri(); @@ -181,6 +187,7 @@ public Map untrackedFiles(Study study, String sessionId) throws Cat /** * Scans the files inside the specified URI and adds to the provided directory. * + * @param organizationId Organization id. * @param directory Directory where add found files * @param directoryToScan Directory to scan * @param policy What to do when there is a file in the target path. See {@link FileScannerPolicy} @@ -191,15 +198,15 @@ public Map untrackedFiles(Study study, String sessionId) throws Cat * @throws IOException if an I/O error occurs * @throws CatalogException if a Catalog error occurs */ - public List scan(File directory, URI directoryToScan, FileScannerPolicy policy, - boolean calculateChecksum, boolean deleteSource, String sessionId) - throws IOException, CatalogException { - return scan(directory, directoryToScan, policy, calculateChecksum, deleteSource, uri -> true, sessionId); + public List scan(String organizationId, File directory, URI directoryToScan, FileScannerPolicy policy, + boolean calculateChecksum, boolean deleteSource, String sessionId) throws IOException, CatalogException { + return scan(organizationId, directory, directoryToScan, policy, calculateChecksum, deleteSource, uri -> true, sessionId); } /** * Scans the files inside the specified URI and adds to the provided directory. * + * @param organizationId Organization id. * @param directory Directory where add found files * @param directoryToScan Directory to scan * @param policy What to do when there is a file in the target path. See {@link FileScannerPolicy} @@ -211,8 +218,8 @@ public List scan(File directory, URI directoryToScan, FileScannerPolicy po * @throws IOException if an I/O error occurs * @throws CatalogException if a Catalog error occurs */ - public List scan(File directory, URI directoryToScan, FileScannerPolicy policy, boolean calculateChecksum, boolean deleteSource, - Predicate filter, String sessionId) throws CatalogException, IOException { + public List scan(String organizationId, File directory, URI directoryToScan, FileScannerPolicy policy, boolean calculateChecksum, + boolean deleteSource, Predicate filter, String sessionId) throws CatalogException, IOException { if (filter == null) { filter = uri -> true; } @@ -248,7 +255,8 @@ public List scan(File directory, URI directoryToScan, FileScannerPolicy po } Query query = new Query(FileDBAdaptor.QueryParams.PATH.key(), filePath); - DataResult searchFile = catalogManager.getFileManager().search(organizationId, study.getFqn(), query, null, sessionId); + DataResult searchFile = catalogManager.getFileManager().search(organizationId, study.getFqn(), query, null, + sessionId); File file = null; boolean overwrite = true; boolean returnFile = false; @@ -263,12 +271,12 @@ public List scan(File directory, URI directoryToScan, FileScannerPolicy po // Set the status of the file to PENDING DELETE FileUpdateParams updateParams = new FileUpdateParams() .setInternal(new SmallFileInternal(new FileStatus(FileStatus.PENDING_DELETE))); - catalogManager.getFileManager().update(organizationId, study.getFqn(), tmpQuery, updateParams, QueryOptions.empty(), - sessionId); + catalogManager.getFileManager().update(organizationId, study.getFqn(), tmpQuery, updateParams, + QueryOptions.empty(), sessionId); // Delete completely the file/folder ! - catalogManager.getFileManager().delete(organizationId, study.getFqn(), tmpQuery, new QueryOptions(Constants.SKIP_TRASH, - true), sessionId); + catalogManager.getFileManager().delete(organizationId, study.getFqn(), tmpQuery, + new QueryOptions(Constants.SKIP_TRASH, true), sessionId); overwrite = false; break; case REPLACE: @@ -287,14 +295,14 @@ public List scan(File directory, URI directoryToScan, FileScannerPolicy po if (file == null) { long start, end; if (uri.getPath().endsWith("/")) { - file = catalogManager.getFileManager().createFolder(organizationId, study.getFqn(), Paths.get(filePath).toString(), true, - null, QueryOptions.empty(), sessionId).first(); + file = catalogManager.getFileManager().createFolder(organizationId, study.getFqn(), + Paths.get(filePath).toString(), true, null, QueryOptions.empty(), sessionId).first(); } else { start = System.currentTimeMillis(); InputStream inputStream = new BufferedInputStream(new FileInputStream(new java.io.File(uri))); - file = catalogManager.getFileManager().upload(organizationId, study.getFqn(), inputStream, new File().setPath(filePath), - overwrite, true, calculateChecksum, sessionId).first(); + file = catalogManager.getFileManager().upload(organizationId, study.getFqn(), inputStream, + new File().setPath(filePath), overwrite, true, calculateChecksum, sessionId).first(); if (deleteSource) { ioManager.deleteFile(uri); } @@ -317,8 +325,8 @@ public List scan(File directory, URI directoryToScan, FileScannerPolicy po long start = System.currentTimeMillis(); InputStream inputStream = new FileInputStream(new java.io.File(uri)); - file = catalogManager.getFileManager().upload(organizationId, study.getFqn(), inputStream, file, overwrite, true, - calculateChecksum, sessionId).first(); + file = catalogManager.getFileManager().upload(organizationId, study.getFqn(), inputStream, file, overwrite, + true, calculateChecksum, sessionId).first(); long end = System.currentTimeMillis(); uploadFilesTime += end - start; diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/auth/authorization/CatalogAuthorizationManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/auth/authorization/CatalogAuthorizationManagerTest.java index 6c505df1c0a..8b61fdf8a78 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/auth/authorization/CatalogAuthorizationManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/auth/authorization/CatalogAuthorizationManagerTest.java @@ -141,11 +141,11 @@ public void before() throws Exception { fileManager = catalogManager.getFileManager(); - catalogManager.getUserManager().create(ownerUser, ownerUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create(studyAdminUser1, studyAdminUser1, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create(studyAdminUser2, studyAdminUser2, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create(memberUser, memberUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create(externalUser, externalUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, ownerUser, ownerUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, studyAdminUser1, studyAdminUser1, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, studyAdminUser2, studyAdminUser2, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, memberUser, memberUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, externalUser, externalUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); ownerSessionId = catalogManager.getUserManager().login(ownerUser, TestParamConstants.PASSWORD).getToken(); studyAdmin1SessionId = catalogManager.getUserManager().login(studyAdminUser1, TestParamConstants.PASSWORD).getToken(); @@ -153,9 +153,9 @@ public void before() throws Exception { memberSessionId = catalogManager.getUserManager().login(memberUser, TestParamConstants.PASSWORD).getToken(); externalSessionId = catalogManager.getUserManager().login(externalUser, TestParamConstants.PASSWORD).getToken(); - p1 = catalogManager.getProjectManager().create("p1", "p1", null, "Homo sapiens", + p1 = catalogManager.getProjectManager().create(organizationId, "p1", "p1", null, "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, ownerSessionId).first().getId(); - Study study = catalogManager.getStudyManager().create(p1, "studyFqn", "studyFqn", "studyFqn", null, null, null, + Study study = catalogManager.getStudyManager().create(organizationId, p1, "studyFqn", "studyFqn", "studyFqn", null, null, null, null, null, INCLUDE_RESULT, ownerSessionId).first(); studyFqn = study.getFqn(); studyUid = study.getUid(); @@ -207,15 +207,15 @@ public void before() throws Exception { catalogManager.getIndividualManager().create(organizationId, studyFqn, new Individual().setId(ind2), Collections.singletonList(smp2.getId()), QueryOptions.empty(), ownerSessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp1.getId()), externalUser, allSamplePermissions, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp1.getId()), externalUser, allSamplePermissions, SET, ownerSessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp3.getId()), externalUser, noSamplePermissions, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp3.getId()), externalUser, noSamplePermissions, SET, ownerSessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp2.getId()), "*", noSamplePermissions, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp2.getId()), "*", noSamplePermissions, SET, ownerSessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp5.getId()), externalUser, noSamplePermissions, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp5.getId()), externalUser, noSamplePermissions, SET, ownerSessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp6.getId()), "@members", allSamplePermissions, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp6.getId()), "@members", allSamplePermissions, SET, ownerSessionId); } @@ -364,7 +364,7 @@ public void removeMemberFromNonBelongingGroup() throws CatalogException { @Test public void addExistingUserToRole() throws CatalogException { String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); StudyAclParams aclParams = new StudyAclParams("", AuthorizationManager.ROLE_ANALYST); catalogManager.getStudyManager().updateAcl(organizationId, Arrays.asList(studyFqn), newUser, aclParams, ParamUtils.AclAction.ADD, ownerSessionId); } @@ -373,7 +373,7 @@ public void addExistingUserToRole() throws CatalogException { @Test public void addExistingUserToRole2() throws CatalogException { String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); thrown.expect(CatalogAuthorizationException.class); thrown.expectMessage("Only owners or administrative users"); StudyAclParams aclParams = new StudyAclParams("", AuthorizationManager.ROLE_ANALYST); @@ -383,7 +383,7 @@ public void addExistingUserToRole2() throws CatalogException { @Test public void addExistingGroupToRole() throws CatalogException { String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "email@ccc.ccc", TestParamConstants.PASSWORD, "ASDF", null, Account.AccountType.FULL, opencgaToken); String group = "@newGroup"; // catalogManager.addUsersToGroup(studyFqn, group, newUser, studyAdmin1SessionId); catalogManager.getStudyManager().createGroup(organizationId, studyFqn, group, Collections.singletonList(newUser), studyAdmin1SessionId); @@ -509,7 +509,7 @@ public void removeGroupFromRole() throws CatalogException { StudyAclParams aclParams = new StudyAclParams(null, null); catalogManager.getStudyManager().updateAcl(organizationId, Arrays.asList(studyFqn), group, aclParams, RESET, ownerSessionId); - String userId = catalogManager.getUserManager().getUserId(ownerSessionId); + String userId = catalogManager.getUserManager().getUserId(organizationId, ownerSessionId); studyAcls = catalogManager.getAuthorizationManager().getStudyAcl(userId, study.getUid(), group); assertEquals(1, studyAcls.getNumResults()); assertEquals(1, studyAcls.first().getAcl().size()); @@ -634,7 +634,7 @@ public void readNonSharedFile() throws CatalogException { @Test public void readFileNoStudyMember() throws CatalogException, IOException { String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); String sessionId = catalogManager.getUserManager().login(newUser, TestParamConstants.PASSWORD).getToken(); thrown.expect(CatalogAuthorizationException.class); catalogManager.getFileManager().get(organizationId, studyFqn, data, null, sessionId); @@ -644,7 +644,7 @@ public void readFileNoStudyMember() throws CatalogException, IOException { public void readFileSharedForGroup() throws CatalogException, IOException { // Add a new user to a new group String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); String sessionId = catalogManager.getUserManager().login(newUser, TestParamConstants.PASSWORD).getToken(); String newGroup = "@external"; // catalogManager.addUsersToGroup(studyFqn, "@external", newUser, ownerSessionId); @@ -674,7 +674,7 @@ public void readFileForbiddenForUser() throws CatalogException { public void readFileForbiddenForGroupSharedWithUser() throws CatalogException, IOException { // Add a new user to a new group String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); String sessionId = catalogManager.getUserManager().login(ownerUser, TestParamConstants.PASSWORD).getToken(); String newGroup = "@external"; // catalogManager.addUsersToGroup(studyFqn, "@external", newUser, ownerSessionId); @@ -734,7 +734,7 @@ public void createNonSharedFile() throws CatalogException { @Test public void createFileNoStudyMember() throws CatalogException, IOException { String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); String sessionId = catalogManager.getUserManager().login(newUser, TestParamConstants.PASSWORD).getToken(); thrown.expect(CatalogAuthorizationException.class); catalogManager.getFileManager().createFolder(organizationId, studyFqn, Paths.get("data/my_folder/").toString(), false, null, @@ -757,7 +757,7 @@ public void readSampleOwnerUser() throws CatalogException { // Owner always have access even if he has been removed all the permissions StudyAclParams aclParams = new StudyAclParams("", null); catalogManager.getStudyManager().updateAcl(organizationId, Collections.singletonList(studyFqn), ownerUser, aclParams, ADD, ownerSessionId); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp1.getId()), ownerUser, noSamplePermissions, SET, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp1.getId()), ownerUser, noSamplePermissions, SET, ownerSessionId); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, smp1.getId(), null, ownerSessionId); @@ -795,7 +795,7 @@ public void readSampleExplicitForbidden() throws CatalogException { @Test public void readSampleExternalUser() throws CatalogException, IOException { String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); String sessionId = catalogManager.getUserManager().login(newUser, TestParamConstants.PASSWORD).getToken(); thrown.expect(CatalogAuthorizationException.class); catalogManager.getSampleManager().get(organizationId, studyFqn, smp2.getId(), null, sessionId); @@ -811,7 +811,7 @@ public void readSampleAdminUser() throws CatalogException { @Test public void readSampleForbiddenForExternalUser() throws CatalogException { - catalogManager.getSampleManager().updateAcl(String.valueOf(studyFqn), Arrays.asList(smp2.getId()), externalUser, + catalogManager.getSampleManager().updateAcl(organizationId, String.valueOf(studyFqn), Arrays.asList(smp2.getId()), externalUser, new SampleAclParams(null, null, null, null, ""), SET, ownerSessionId); thrown.expect(CatalogAuthorizationException.class); catalogManager.getSampleManager().get(organizationId, studyFqn, smp2.getId(), null, externalSessionId); @@ -821,7 +821,7 @@ public void readSampleForbiddenForExternalUser() throws CatalogException { public void readSampleSharedForGroup() throws CatalogException, IOException { // Add a new user to a new group String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); String sessionId = catalogManager.getUserManager().login(ownerUser, TestParamConstants.PASSWORD).getToken(); String newGroup = "@external"; // catalogManager.addUsersToGroup(studyFqn, "@external", newUser, ownerSessionId); @@ -831,7 +831,7 @@ public void readSampleSharedForGroup() throws CatalogException, IOException { catalogManager.getStudyManager().updateAcl(organizationId, Collections.singletonList(studyFqn), newGroup, aclParams, ADD, ownerSessionId); // Share the sample with the group - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp4.getId()), newGroup, allSamplePermissions, SET, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp4.getId()), newGroup, allSamplePermissions, SET, ownerSessionId); DataResult sample = catalogManager.getSampleManager().get(organizationId, studyFqn, smp4.getId(), null, sessionId); @@ -849,7 +849,7 @@ public void readSampleSharedForOthers() throws CatalogException { public void readSampleSharedForOthersNotWithStudyPermissions() throws CatalogException, IOException { // Add a new user to a new group String newUser = "newUser"; - catalogManager.getUserManager().create(newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, newUser, newUser, "asda@mail.com", TestParamConstants.PASSWORD, "org", 1000L, Account.AccountType.FULL, opencgaToken); String sessionId = catalogManager.getUserManager().login(ownerUser, TestParamConstants.PASSWORD).getToken(); catalogManager.getStudyManager().updateGroup(organizationId, studyFqn, "@members", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList(newUser)), ownerSessionId); @@ -860,7 +860,7 @@ public void readSampleSharedForOthersNotWithStudyPermissions() throws CatalogExc @Test public void adminShareSampleWithOtherUser() throws CatalogException { - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList(smp4.getId()), externalUser, allSamplePermissions, + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList(smp4.getId()), externalUser, allSamplePermissions, SET, studyAdmin1SessionId); DataResult sample = catalogManager.getSampleManager().get(organizationId, studyFqn, smp4.getId(), null, externalSessionId); assertEquals(1, sample.getNumResults()); @@ -906,14 +906,14 @@ public void aclQuery() throws CatalogException { sampleManager.create(organizationId, studyFqn, new Sample().setId("s4"), QueryOptions.empty(), ownerSessionId); sampleManager.create(organizationId, studyFqn, new Sample().setId("s5"), QueryOptions.empty(), ownerSessionId); - sampleManager.updateAcl(studyFqn, Collections.singletonList("s1"), memberUser, + sampleManager.updateAcl(organizationId, studyFqn, Collections.singletonList("s1"), memberUser, new SampleAclParams(null, null, null, null, SamplePermissions.DELETE.name()), SET, ownerSessionId); - sampleManager.updateAcl(studyFqn, Collections.singletonList("s2"), memberUser, + sampleManager.updateAcl(organizationId, studyFqn, Collections.singletonList("s2"), memberUser, new SampleAclParams(null, null, null, null, SamplePermissions.VIEW_ANNOTATIONS.name()), SET, ownerSessionId); - sampleManager.updateAcl(studyFqn, Collections.singletonList("s3"), memberUser, new SampleAclParams( + sampleManager.updateAcl(organizationId, studyFqn, Collections.singletonList("s3"), memberUser, new SampleAclParams( null, null, null, null, SamplePermissions.DELETE.name()), SET, ownerSessionId); - sampleManager.updateAcl(studyFqn, Collections.singletonList("s4"), memberUser, new SampleAclParams( + sampleManager.updateAcl(organizationId, studyFqn, Collections.singletonList("s4"), memberUser, new SampleAclParams( null, null, null, null, SamplePermissions.VIEW.name()), SET, ownerSessionId); QueryOptions options = new QueryOptions(QueryOptions.INCLUDE, SampleDBAdaptor.QueryParams.ID.key()); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractClinicalManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractClinicalManagerTest.java index c5958b10c1b..a0814720d02 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractClinicalManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractClinicalManagerTest.java @@ -81,14 +81,14 @@ public void setUp() throws IOException, CatalogException, URISyntaxException { public void setUpCatalogManager() throws IOException, CatalogException, URISyntaxException { ClinicalAnalysis auxClinicalAnalysis; - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, catalogManagerResource.getAdminToken()); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", PASSWORD, "", null, Account.AccountType.FULL, catalogManagerResource.getAdminToken()); token = catalogManager.getUserManager().login("user", PASSWORD).getToken(); - catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", + catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", new QueryOptions(), token); - Study study = catalogManager.getStudyManager().create("1000G", "phase1", null, "Phase 1", "Done", null, null, + Study study = catalogManager.getStudyManager().create(organizationId, "1000G", "phase1", null, "Phase 1", "Done", null, null, null, null, null, token).first(); studyFqn = study.getFqn(); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractManagerTest.java index d0abdbb6011..a3818df4f9f 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/AbstractManagerTest.java @@ -97,9 +97,9 @@ public void setUpCatalogManager(CatalogManager catalogManager) throws IOExceptio catalogManager.getOrganizationManager().create(new OrganizationCreateParams().setId("test_org"), null, opencgaToken); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create("user2", "User2 Name", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create("user3", "User3 Name", "user.2@e.mail", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user2", "User2 Name", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user3", "User3 Name", "user.2@e.mail", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.FULL, opencgaToken); catalogManager.getOrganizationManager().update("test_org", new OrganizationUpdateParams().setOwner("user").setAdmins(Arrays.asList("user2", "user3")), null, opencgaToken); @@ -107,22 +107,22 @@ public void setUpCatalogManager(CatalogManager catalogManager) throws IOExceptio sessionIdUser2 = catalogManager.getUserManager().login("user2", TestParamConstants.PASSWORD).getToken(); sessionIdUser3 = catalogManager.getUserManager().login("user3", TestParamConstants.PASSWORD).getToken(); - project1 = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + project1 = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, token).first().getId(); - project2 = catalogManager.getProjectManager().create("pmp", "Project Management Project", "life art intelligent system", + project2 = catalogManager.getProjectManager().create(organizationId, "pmp", "Project Management Project", "life art intelligent system", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser2).first().getId(); - catalogManager.getProjectManager().create("p1", "project 1", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, + catalogManager.getProjectManager().create(organizationId, "p1", "project 1", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser3).first(); - Study study = catalogManager.getStudyManager().create(project1, "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, token).first(); + Study study = catalogManager.getStudyManager().create(organizationId, project1, "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, token).first(); studyUid = study.getUid(); studyFqn = study.getFqn(); - study = catalogManager.getStudyManager().create(project1, "phase3", null, "Phase 3", "d", null, null, null, null, INCLUDE_RESULT, token).first(); + study = catalogManager.getStudyManager().create(organizationId, project1, "phase3", null, "Phase 3", "d", null, null, null, null, INCLUDE_RESULT, token).first(); studyUid2 = study.getUid(); studyFqn2 = study.getFqn(); - study = catalogManager.getStudyManager().create(project2, "s1", null, "Study 1", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first(); + study = catalogManager.getStudyManager().create(organizationId, project2, "s1", null, "Study 1", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first(); studyFqn3 = study.getFqn(); catalogManager.getFileManager().createFolder(organizationId, studyFqn2, Paths.get("data/test/folder/").toString(), true, diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/CatalogManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/CatalogManagerTest.java index e2766ccc18c..2ae1744b8f0 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/CatalogManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/CatalogManagerTest.java @@ -68,20 +68,20 @@ public class CatalogManagerTest extends AbstractManagerTest { @Test public void createStudyFailMoreThanOneProject() throws CatalogException { catalogManager.getProjectManager().incrementRelease(organizationId, project1, token); - catalogManager.getProjectManager().create("1000G2", "Project about some genomes", "", "Homo sapiens", + catalogManager.getProjectManager().create(organizationId, "1000G2", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", new QueryOptions(), token); // Create a new study without providing the project. It should raise an error because the user owns more than one project thrown.expect(CatalogException.class); thrown.expectMessage("More than one project found"); - catalogManager.getStudyManager().create(null, "phasexx", null, "Phase 1", "Done", null, + catalogManager.getStudyManager().create(organizationId, null, "phasexx", null, "Phase 1", "Done", null, null, null, null, null, token); } @Test public void testAdminUserExists() throws Exception { String token = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - assertEquals("opencga", catalogManager.getUserManager().getUserId(token)); + assertEquals("opencga", catalogManager.getUserManager().getUserId(organizationId, token)); } @Test @@ -91,29 +91,29 @@ public void testGetToken() throws Exception { claims.put("a", "hola"); claims.put("ab", "byw"); // Create a token valid for 1 second - String expiringToken = catalogManager.getUserManager().getToken("opencga", claims, 1L, token); - assertEquals("opencga", catalogManager.getUserManager().getUserId(expiringToken)); + String expiringToken = catalogManager.getUserManager().getToken(organizationId, "opencga", claims, 1L, token); + assertEquals("opencga", catalogManager.getUserManager().getUserId(organizationId, expiringToken)); - String nonExpiringToken = catalogManager.getUserManager().getNonExpiringToken("opencga", claims, token); - assertEquals("opencga", catalogManager.getUserManager().getUserId(nonExpiringToken)); + String nonExpiringToken = catalogManager.getUserManager().getNonExpiringToken(organizationId, "opencga", claims, token); + assertEquals("opencga", catalogManager.getUserManager().getUserId(organizationId, nonExpiringToken)); Thread.sleep(1000); thrown.expect(CatalogAuthenticationException.class); thrown.expectMessage("expired"); - assertEquals("opencga", catalogManager.getUserManager().getUserId(expiringToken)); + assertEquals("opencga", catalogManager.getUserManager().getUserId(organizationId, expiringToken)); } @Test public void testCreateExistingUser() throws Exception { thrown.expect(CatalogException.class); thrown.expectMessage(containsString("already exists")); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); } @Test public void testCreateAnonymousUser() throws Exception { thrown.expect(CatalogParameterException.class); thrown.expectMessage(containsString("reserved")); - catalogManager.getUserManager().create(ParamConstants.ANONYMOUS_USER_ID, "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, + catalogManager.getUserManager().create(organizationId, ParamConstants.ANONYMOUS_USER_ID, "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); } @@ -121,7 +121,7 @@ public void testCreateAnonymousUser() throws Exception { public void testCreateRegisteredUser() throws Exception { thrown.expect(CatalogParameterException.class); thrown.expectMessage(containsString("reserved")); - catalogManager.getUserManager().create(ParamConstants.REGISTERED_USERS, "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, + catalogManager.getUserManager().create(organizationId, ParamConstants.REGISTERED_USERS, "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); } @@ -136,14 +136,14 @@ public void testLogin() throws Exception { @Test public void testGetUserInfo() throws CatalogException { - DataResult user = catalogManager.getUserManager().get("user", new QueryOptions(), token); + DataResult user = catalogManager.getUserManager().get(organizationId, "user", new QueryOptions(), token); System.out.println("user = " + user); - OpenCGAResult result = catalogManager.getUserManager().get("user2", new QueryOptions(), token); + OpenCGAResult result = catalogManager.getUserManager().get(organizationId, "user2", new QueryOptions(), token); assertEquals(Event.Type.ERROR, result.getEvents().get(0).getType()); catalogManager.getStudyManager().updateGroup(organizationId, studyFqn, StudyManager.MEMBERS, ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("user2")), token); - result = catalogManager.getUserManager().get("user2", new QueryOptions(), token); + result = catalogManager.getUserManager().get(organizationId, "user2", new QueryOptions(), token); assertTrue(result.getEvents().isEmpty()); assertTrue(StringUtils.isNotEmpty(result.first().getEmail())); } @@ -152,7 +152,7 @@ public void testGetUserInfo() throws CatalogException { public void testUserInfoProjections() throws CatalogException { QueryOptions options = new QueryOptions() .append(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.PROJECTS_ID.key()); - DataResult user = catalogManager.getUserManager().get("user", options, token); + DataResult user = catalogManager.getUserManager().get(organizationId, "user", options, token); assertNotNull(user.first().getProjects()); assertTrue(StringUtils.isNotEmpty(user.first().getProjects().get(0).getId())); assertTrue(StringUtils.isEmpty(user.first().getProjects().get(0).getName())); @@ -161,7 +161,7 @@ public void testUserInfoProjections() throws CatalogException { options = new QueryOptions() .append(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.PROJECTS.key() + ".studies." + StudyDBAdaptor.QueryParams.FQN.key()); - user = catalogManager.getUserManager().get("user", options, token); + user = catalogManager.getUserManager().get(organizationId, "user", options, token); assertNotNull(user.first().getProjects()); assertEquals(2, user.first().getProjects().get(0).getStudies().size()); assertTrue(StringUtils.isNotEmpty(user.first().getProjects().get(0).getStudies().get(0).getFqn())); @@ -170,7 +170,7 @@ public void testUserInfoProjections() throws CatalogException { options = new QueryOptions() .append(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.SHARED_PROJECTS.key() + ".studies." + StudyDBAdaptor.QueryParams.FQN.key()); - user = catalogManager.getUserManager().get("user2", options, sessionIdUser2); + user = catalogManager.getUserManager().get(organizationId, "user2", options, sessionIdUser2); assertEquals(0, user.first().getSharedProjects().size()); // Grant permissions to user2 to access study of user1 @@ -180,7 +180,7 @@ public void testUserInfoProjections() throws CatalogException { options = new QueryOptions() .append(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.SHARED_PROJECTS.key() + ".studies." + StudyDBAdaptor.QueryParams.FQN.key()); - user = catalogManager.getUserManager().get("user2", options, sessionIdUser2); + user = catalogManager.getUserManager().get(organizationId, "user2", options, sessionIdUser2); assertEquals(1, user.first().getSharedProjects().size()); assertEquals(studyFqn, user.first().getSharedProjects().get(0).getStudies().get(0).getFqn()); assertNull(user.first().getSharedProjects().get(0).getStudies().get(0).getId()); @@ -188,7 +188,7 @@ public void testUserInfoProjections() throws CatalogException { options = new QueryOptions() .append(QueryOptions.INCLUDE, UserDBAdaptor.QueryParams.SHARED_PROJECTS.key() + ".studies." + StudyDBAdaptor.QueryParams.ID.key()); - user = catalogManager.getUserManager().get("user2", options, sessionIdUser2); + user = catalogManager.getUserManager().get(organizationId, "user2", options, sessionIdUser2); assertEquals(1, user.first().getSharedProjects().size()); assertEquals(studyFqn, user.first().getSharedProjects().get(0).getStudies().get(0).getFqn()); assertNotNull(user.first().getSharedProjects().get(0).getStudies().get(0).getId()); @@ -209,11 +209,11 @@ public void testModifyUser() throws CatalogException, InterruptedException, IOEx Thread.sleep(10); - catalogManager.getUserManager().update("user", params, null, token); - catalogManager.getUserManager().update("user", new ObjectMap("email", newEmail), null, token); - catalogManager.getUserManager().changePassword("user", TestParamConstants.PASSWORD, newPassword); + catalogManager.getUserManager().update(organizationId, "user", params, null, token); + catalogManager.getUserManager().update(organizationId, "user", new ObjectMap("email", newEmail), null, token); + catalogManager.getUserManager().changePassword(organizationId, "user", TestParamConstants.PASSWORD, newPassword); - List userList = catalogManager.getUserManager().get("user", new QueryOptions(QueryOptions + List userList = catalogManager.getUserManager().get(organizationId, "user", new QueryOptions(QueryOptions .INCLUDE, Arrays.asList(UserDBAdaptor.QueryParams.NAME.key(), UserDBAdaptor.QueryParams.EMAIL.key(), UserDBAdaptor.QueryParams.ATTRIBUTES.key())), token).getResults(); User userPost = userList.get(0); @@ -226,20 +226,20 @@ public void testModifyUser() throws CatalogException, InterruptedException, IOEx assertEquals(userPost.getAttributes().get(entry.getKey()), entry.getValue()); } - catalogManager.getUserManager().changePassword("user", newPassword, TestParamConstants.PASSWORD); + catalogManager.getUserManager().changePassword(organizationId, "user", newPassword, TestParamConstants.PASSWORD); catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD); try { params = new ObjectMap(); params.put("password", "1234321"); - catalogManager.getUserManager().update("user", params, null, token); + catalogManager.getUserManager().update(organizationId, "user", params, null, token); fail("Expected exception"); } catch (CatalogDBException e) { System.out.println(e); } try { - catalogManager.getUserManager().update("user", params, null, sessionIdUser2); + catalogManager.getUserManager().update(organizationId, "user", params, null, sessionIdUser2); fail("Expected exception"); } catch (CatalogException e) { System.out.println(e); @@ -251,25 +251,25 @@ public void testUpdateUserConfig() throws CatalogException { Map map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); - catalogManager.getUserManager().setConfig("user", "a", map, token); + catalogManager.getUserManager().setConfig(organizationId, "user", "a", map, token); - Map config = (Map) catalogManager.getUserManager().getConfig("user", "a", token).first(); + Map config = (Map) catalogManager.getUserManager().getConfig(organizationId, "user", "a", token).first(); assertEquals(2, config.size()); assertEquals("value1", config.get("key1")); assertEquals("value2", config.get("key2")); map = new HashMap<>(); map.put("key2", "value3"); - catalogManager.getUserManager().setConfig("user", "a", map, token); - config = (Map) catalogManager.getUserManager().getConfig("user", "a", token).first(); + catalogManager.getUserManager().setConfig(organizationId, "user", "a", map, token); + config = (Map) catalogManager.getUserManager().getConfig(organizationId, "user", "a", token).first(); assertEquals(1, config.size()); assertEquals("value3", config.get("key2")); - catalogManager.getUserManager().deleteConfig("user", "a", token); + catalogManager.getUserManager().deleteConfig(organizationId, "user", "a", token); thrown.expect(CatalogException.class); thrown.expectMessage("not found"); - catalogManager.getUserManager().getConfig("user", "a", token); + catalogManager.getUserManager().getConfig(organizationId, "user", "a", token); } private String getAdminToken() throws CatalogException, IOException { @@ -307,7 +307,7 @@ public void getGroupsTest() throws CatalogException { @Test public void importLdapUsers() throws CatalogException, NamingException, IOException { // Action only for admins - catalogManager.getUserManager().importRemoteEntities("ldap", Arrays.asList("pfurio", "imedina"), false, null, null, + catalogManager.getUserManager().importRemoteEntities(organizationId, "ldap", Arrays.asList("pfurio", "imedina"), false, null, null, getAdminToken()); // TODO: Validate the users have been imported } @@ -338,13 +338,13 @@ public void syncUsers() throws CatalogException { // Action only for admins String token = catalogManager.getUserManager().loginAsAdmin("admin").getToken(); - catalogManager.getUserManager().importRemoteGroupOfUsers("ldap", "bio", "bio", studyFqn, true, token); + catalogManager.getUserManager().importRemoteGroupOfUsers(organizationId, "ldap", "bio", "bio", studyFqn, true, token); DataResult bio = catalogManager.getStudyManager().getGroup(organizationId, studyFqn, "bio", this.token); assertEquals(1, bio.getNumResults()); assertEquals(0, bio.first().getUserIds().size()); - catalogManager.getUserManager().syncAllUsersOfExternalGroup(studyFqn, "ldap", token); + catalogManager.getUserManager().syncAllUsersOfExternalGroup(organizationId, studyFqn, "ldap", token); bio = catalogManager.getStudyManager().getGroup(organizationId, studyFqn, "bio", this.token); assertEquals(1, bio.getNumResults()); @@ -358,7 +358,7 @@ public void importLdapGroups() throws CatalogException, IOException { String remoteGroup = "bio"; String internalGroup = "test"; String study = "user@1000G:phase1"; - catalogManager.getUserManager().importRemoteGroupOfUsers("ldap", remoteGroup, internalGroup, study, true, getAdminToken()); + catalogManager.getUserManager().importRemoteGroupOfUsers(organizationId, "ldap", remoteGroup, internalGroup, study, true, getAdminToken()); DataResult test = catalogManager.getStudyManager().getGroup(organizationId, "user@1000G:phase1", "test", token); assertEquals(1, test.getNumResults()); @@ -377,12 +377,12 @@ public void importLdapGroups() throws CatalogException, IOException { internalGroup = "test2"; thrown.expect(CatalogException.class); thrown.expectMessage("not found"); - catalogManager.getUserManager().importRemoteGroupOfUsers("ldap", remoteGroup, internalGroup, study, true, getAdminToken()); + catalogManager.getUserManager().importRemoteGroupOfUsers(organizationId, "ldap", remoteGroup, internalGroup, study, true, getAdminToken()); } @Test public void createEmptyGroup() throws CatalogException { - catalogManager.getUserManager().create("test", "test", "test@mail.com", TestParamConstants.PASSWORD, null, 100L, Account.AccountType.GUEST, opencgaToken); + catalogManager.getUserManager().create(organizationId, "test", "test", "test@mail.com", TestParamConstants.PASSWORD, null, 100L, Account.AccountType.GUEST, opencgaToken); catalogManager.getStudyManager().createGroup(organizationId, "user@1000G:phase1", "group_cancer_some_thing_else", null, token); catalogManager.getStudyManager().updateGroup(organizationId, "user@1000G:phase1", "group_cancer_some_thing_else", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("test")), token); @@ -390,7 +390,7 @@ public void createEmptyGroup() throws CatalogException { @Test public void testAssignPermissions() throws CatalogException { - catalogManager.getUserManager().create("test", "test", "test@mail.com", TestParamConstants.PASSWORD, null, 100L, Account.AccountType.GUEST, opencgaToken); + catalogManager.getUserManager().create(organizationId, "test", "test", "test@mail.com", TestParamConstants.PASSWORD, null, 100L, Account.AccountType.GUEST, opencgaToken); catalogManager.getStudyManager().createGroup(organizationId, "user@1000G:phase1", "group_cancer_some_thing_else", Collections.singletonList("test"), token); @@ -434,19 +434,19 @@ public void testCreateProject() throws Exception { String projectAlias = "projectAlias_ASDFASDF"; - catalogManager.getProjectManager().create(projectAlias, "Project", "", "Homo sapiens", null, "GRCh38", new + catalogManager.getProjectManager().create(organizationId, projectAlias, "Project", "", "Homo sapiens", null, "GRCh38", new QueryOptions(), token); thrown.expect(CatalogDBException.class); thrown.expectMessage(containsString("already exists")); - catalogManager.getProjectManager().create(projectAlias, "Project", "", "Homo sapiens", + catalogManager.getProjectManager().create(organizationId, projectAlias, "Project", "", "Homo sapiens", null, "GRCh38", new QueryOptions(), token); } @Test public void testModifyProject() throws CatalogException { String newProjectName = "ProjectName " + RandomStringUtils.randomAlphanumeric(10); - String projectId = catalogManager.getUserManager().get("user", new QueryOptions(), token).first().getProjects().get(0) + String projectId = catalogManager.getUserManager().get(organizationId, "user", new QueryOptions(), token).first().getProjects().get(0) .getId(); ObjectMap options = new ObjectMap(); @@ -542,11 +542,11 @@ public void testGetAllStudies() throws CatalogException { , null, token).first(); assertEquals("20150101120000", study_1.getCreationDate()); - catalogManager.getStudyManager().create(projectId, "study_2", null, "study_2", "description", null, null, null, null, null, token); + catalogManager.getStudyManager().create(organizationId, projectId, "study_2", null, "study_2", "description", null, null, null, null, null, token); - catalogManager.getStudyManager().create(projectId, "study_3", null, "study_3", "description", null, null, null, null, null, token); + catalogManager.getStudyManager().create(organizationId, projectId, "study_3", null, "study_3", "description", null, null, null, null, null, token); - String study_4 = catalogManager.getStudyManager().create(projectId, "study_4", null, "study_4", "description", null, null, null, + String study_4 = catalogManager.getStudyManager().create(organizationId, projectId, "study_4", null, "study_4", "description", null, null, null, null, null, token).first().getId(); assertEquals(new HashSet<>(Collections.emptyList()), catalogManager.getStudyManager().search(organizationId, new Query(StudyDBAdaptor.QueryParams @@ -577,9 +577,9 @@ public void testGetAllStudies() throws CatalogException { @Test public void testGetId() throws CatalogException { // Create another study with alias phase3 - catalogManager.getStudyManager().create(project2, "phase3", null, "Phase 3", "d", null, null, null, null, null, sessionIdUser2); + catalogManager.getStudyManager().create(organizationId, project2, "phase3", null, "Phase 3", "d", null, null, null, null, null, sessionIdUser2); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); List uids = catalogManager.getStudyManager().resolveIds(organizationId, Arrays.asList("*"), userId) .stream() .map(Study::getUid) @@ -650,7 +650,7 @@ public void testGetOnlyStudyUserAnonymousCanSee() throws CatalogException { } // Create another study with alias phase3 - DataResult study = catalogManager.getStudyManager().create(String.valueOf(project2), "phase3", null, "Phase 3", "d", null, + DataResult study = catalogManager.getStudyManager().create(organizationId, String.valueOf(project2), "phase3", null, "Phase 3", "d", null, null, null, null, null, sessionIdUser2); try { studyManager.resolveIds(organizationId, Collections.emptyList(), "*"); @@ -677,7 +677,7 @@ public void testGetSelectedStudyUserAnonymousCanSee() throws CatalogException { } // Create another study with alias phase3 - DataResult study = catalogManager.getStudyManager().create(project2, "phase3", null, "Phase 3", "d", null, null, null, + DataResult study = catalogManager.getStudyManager().create(organizationId, project2, "phase3", null, "Phase 3", "d", null, null, null, null, null, sessionIdUser2); catalogManager.getStudyManager().updateGroup(organizationId, "phase3", "@members", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("*")), sessionIdUser2); @@ -755,7 +755,7 @@ public void removeAllPermissionsToMember() throws CatalogException { List sampleIds = sampleDataResult.getResults().stream() .map(Sample::getId) .collect(Collectors.toList()); - DataResult> sampleAclResult = catalogManager.getSampleManager().updateAcl(studyFqn, + DataResult> sampleAclResult = catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, sampleIds, "user2,user3", sampleAclParams, ParamUtils.AclAction.SET, token); assertEquals(sampleIds.size(), sampleAclResult.getNumResults()); for (AclEntryList result : sampleAclResult.getResults()) { @@ -812,7 +812,7 @@ public void removeUsersFromStudies() throws CatalogException { SamplePermissions.VIEW.name() + "," + SamplePermissions.WRITE.name()); List sampleIds = sampleDataResult.getResults().stream().map(Sample::getId).collect(Collectors.toList()); - OpenCGAResult> sampleAclResult = catalogManager.getSampleManager().updateAcl(studyFqn, + OpenCGAResult> sampleAclResult = catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, sampleIds, "user2,user3", sampleAclParams, ParamUtils.AclAction.SET, token); assertEquals(sampleIds.size(), sampleAclResult.getNumResults()); for (AclEntryList result : sampleAclResult.getResults()) { @@ -828,7 +828,7 @@ public void removeUsersFromStudies() throws CatalogException { catalogManager.getStudyManager().updateGroup(organizationId, studyFqn, "@members", ParamUtils.BasicUpdateAction.REMOVE, new GroupUpdateParams(Arrays.asList("user2", "user3")), token); - String userId1 = catalogManager.getUserManager().getUserId(token); + String userId1 = catalogManager.getUserManager().getUserId(organizationId, token); Study study3 = catalogManager.getStudyManager().resolveId(organizationId, studyFqn, userId1); OpenCGAResult> studyAcl = catalogManager.getAuthorizationManager() @@ -837,7 +837,7 @@ public void removeUsersFromStudies() throws CatalogException { assertEquals(1, studyAcl.first().getAcl().size()); assertEquals("user2", studyAcl.first().getAcl().get(0).getMember()); assertNull(studyAcl.first().getAcl().get(0).getPermissions()); - String userId = catalogManager.getUserManager().getUserId(token); + String userId = catalogManager.getUserManager().getUserId(organizationId, token); Study study1 = catalogManager.getStudyManager().resolveId(organizationId, studyFqn, userId); studyAcl = catalogManager.getAuthorizationManager().getStudyAcl(userId, study1.getUid(), "user3"); assertEquals(1, studyAcl.getNumResults()); @@ -909,9 +909,9 @@ public void testCreateJobAndReuse() throws CatalogException { Query query = new Query(StudyDBAdaptor.QueryParams.OWNER.key(), "user"); - String project1 = catalogManager.getProjectManager().create("testCreateJobAndReuse_project1", "", "", "Homo sapiens", + String project1 = catalogManager.getProjectManager().create(organizationId, "testCreateJobAndReuse_project1", "", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, token).first().getId(); - String project2 = catalogManager.getProjectManager().create("testCreateJobAndReuse_project2", "", "", "Homo sapiens", + String project2 = catalogManager.getProjectManager().create(organizationId, "testCreateJobAndReuse_project2", "", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, token).first().getId(); String study1 = catalogManager.getStudyManager().create(organizationId, project1, new Study() @@ -1275,7 +1275,7 @@ public void testDeleteVariableSetInUse() throws CatalogException { Map annotations = new HashMap<>(); annotations.put("NAME", "LINUS"); - catalogManager.getSampleManager().update(studyFqn, sampleId1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotationId", vs1.getId(), annotations))), QueryOptions.empty(), token); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManagerTest.java index 27793db727b..1625b981a20 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ClinicalAnalysisManagerTest.java @@ -109,15 +109,15 @@ public void setUp() throws IOException, CatalogException { public void setUpCatalogManager(CatalogManager catalogManager) throws IOException, CatalogException { opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); - catalogManager.getUserManager().create("user2", "User Name2", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, + catalogManager.getUserManager().create(organizationId, "user2", "User Name2", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, opencgaToken); - String projectId = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first().getId(); - catalogManager.getStudyManager().create(projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); + catalogManager.getStudyManager().create(organizationId, projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); } @After @@ -270,7 +270,7 @@ public void createMultipleCasesSameFamily() throws CatalogException { catalogManager.getClinicalAnalysisManager().update(organizationId, STUDY, case1.getId(), new ClinicalAnalysisUpdateParams().setLocked(true), QueryOptions.empty(), sessionIdUser); // Update proband's sample - catalogManager.getSampleManager().update(STUDY, case1.getProband().getSamples().get(0).getId(), + catalogManager.getSampleManager().update(organizationId, STUDY, case1.getProband().getSamples().get(0).getId(), new SampleUpdateParams().setDescription("new description"), QueryOptions.empty(), sessionIdUser); OpenCGAResult search = catalogManager.getClinicalAnalysisManager().search(organizationId, STUDY, new Query(), new QueryOptions(), @@ -1154,7 +1154,7 @@ public void updateInterpretationComments() throws CatalogException { @Test public void assignPermissions() throws CatalogException { ClinicalAnalysis clinicalAnalysis = createDummyEnvironment(true, false).first(); - catalogManager.getUserManager().create("external", "User Name", "external@mail.com", TestParamConstants.PASSWORD, "", null, + catalogManager.getUserManager().create(organizationId, "external", "User Name", "external@mail.com", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, opencgaToken); OpenCGAResult> aclResult = @@ -1179,7 +1179,7 @@ public void assignPermissions() throws CatalogException { assertEquals("external", iAclResult.first().getAcl().get(0).getMember()); assertNull(iAclResult.first().getAcl().get(0).getPermissions()); - OpenCGAResult> sAclResult = catalogManager.getSampleManager().getAcls(STUDY, + OpenCGAResult> sAclResult = catalogManager.getSampleManager().getAcls(organizationId, STUDY, Collections.singletonList(clinicalAnalysis.getProband().getSamples().get(0).getId()), "external", false, sessionIdUser); assertEquals(1, sAclResult.getNumResults()); assertEquals(1, sAclResult.first().getAcl().size()); @@ -1209,7 +1209,7 @@ public void assignPermissions() throws CatalogException { assertEquals("external", iAclResult.first().getAcl().get(0).getMember()); assertNull(iAclResult.first().getAcl().get(0).getPermissions()); - sAclResult = catalogManager.getSampleManager().getAcls(STUDY, + sAclResult = catalogManager.getSampleManager().getAcls(organizationId, STUDY, Collections.singletonList(clinicalAnalysis.getProband().getSamples().get(0).getId()), "external", false, sessionIdUser); assertEquals(1, sAclResult.getNumResults()); assertEquals(1, sAclResult.first().getAcl().size()); @@ -1236,7 +1236,7 @@ public void assignPermissions() throws CatalogException { assertEquals(1, iAclResult.getNumResults()); assertEquals(2, iAclResult.first().getAcl().get(0).getPermissions().size()); - sAclResult = catalogManager.getSampleManager().getAcls(STUDY, + sAclResult = catalogManager.getSampleManager().getAcls(organizationId, STUDY, Collections.singletonList(clinicalAnalysis.getProband().getSamples().get(0).getId()), "external", false, sessionIdUser); assertEquals(1, sAclResult.getNumResults()); assertEquals(2, sAclResult.first().getAcl().get(0).getPermissions().size()); @@ -2525,7 +2525,7 @@ public void checkFamilyMembersOrder() throws CatalogException { @Test public void createClinicalAnalysisWithPanels() throws CatalogException { - catalogManager.getPanelManager().importFromSource(STUDY, "gene-census", "", sessionIdUser); + catalogManager.getPanelManager().importFromSource(organizationId, STUDY, "gene-census", "", sessionIdUser); Panel panel = catalogManager.getPanelManager().search(organizationId, STUDY, new Query(), QueryOptions.empty(), sessionIdUser).first(); DataResult dummyFamily = createDummyFamily(); @@ -2561,7 +2561,7 @@ public void createClinicalAnalysisWithPanels() throws CatalogException { @Test public void createInterpretationWithPanels() throws CatalogException { - catalogManager.getPanelManager().importFromSource(STUDY, "gene-census", "", sessionIdUser); + catalogManager.getPanelManager().importFromSource(organizationId, STUDY, "gene-census", "", sessionIdUser); Panel panel = catalogManager.getPanelManager().search(organizationId, STUDY, new Query(), QueryOptions.empty(), sessionIdUser).first(); ClinicalAnalysis ca = createDummyEnvironment(true, false).first(); @@ -2580,7 +2580,7 @@ public void createInterpretationWithPanels() throws CatalogException { @Test public void updatePanelsInClinicalAnalysis() throws CatalogException { - catalogManager.getPanelManager().importFromSource(STUDY, "gene-census", "", sessionIdUser); + catalogManager.getPanelManager().importFromSource(organizationId, STUDY, "gene-census", "", sessionIdUser); Panel panel = catalogManager.getPanelManager().search(organizationId, STUDY, new Query(), QueryOptions.empty(), sessionIdUser).first(); DataResult dummyFamily = createDummyFamily(); @@ -2697,7 +2697,7 @@ public void testQueriesInCancerCase() throws CatalogException { catalogManager.getClinicalAnalysisManager().create(organizationId, STUDY, clinicalAnalysis, QueryOptions.empty(), sessionIdUser); // Update to force a version increment and therefore, an update over the case - catalogManager.getSampleManager().update(STUDY, sample.getId(), new SampleUpdateParams().setDescription("descr"), + catalogManager.getSampleManager().update(organizationId, STUDY, sample.getId(), new SampleUpdateParams().setDescription("descr"), QueryOptions.empty(), sessionIdUser); QueryOptions includeClinicalIds = ClinicalAnalysisManager.INCLUDE_CLINICAL_IDS; diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FamilyManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FamilyManagerTest.java index 61462ae73d8..2d63cda1865 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FamilyManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FamilyManagerTest.java @@ -94,13 +94,13 @@ public void setUp() throws IOException, CatalogException { public void setUpCatalogManager(CatalogManager catalogManager) throws CatalogException { opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); - String projectId = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first().getId(); - catalogManager.getStudyManager().create(projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); + catalogManager.getStudyManager().create(organizationId, projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); } @After @@ -621,7 +621,7 @@ public void testRoles() throws CatalogException { public void testPropagateFamilyPermission() throws CatalogException { createDummyFamily("Martinez-Martinez", true); - catalogManager.getUserManager().create("user2", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, + catalogManager.getUserManager().create(organizationId, "user2", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, opencgaToken); String token = catalogManager.getUserManager().login("user2", TestParamConstants.PASSWORD).getToken(); @@ -653,7 +653,7 @@ public void testPropagateFamilyPermission() throws CatalogException { } assertEquals(3, sampleList.size()); - OpenCGAResult> acls = catalogManager.getSampleManager().getAcls(STUDY, + OpenCGAResult> acls = catalogManager.getSampleManager().getAcls(organizationId, STUDY, sampleList.stream().map(Sample::getId).collect(Collectors.toList()), "user2", false, sessionIdUser); for (AclEntryList result : acls.getResults()) { assertTrue(result.getAcl().get(0).getPermissions().contains(SamplePermissions.VIEW)); @@ -671,7 +671,7 @@ public void testPropagateFamilyPermission() throws CatalogException { } assertEquals(3, sampleList.size()); - acls = catalogManager.getSampleManager().getAcls(STUDY, sampleList.stream().map(Sample::getId).collect(Collectors.toList()), + acls = catalogManager.getSampleManager().getAcls(organizationId, STUDY, sampleList.stream().map(Sample::getId).collect(Collectors.toList()), "user2", false, sessionIdUser); for (AclEntryList result : acls.getResults()) { assertTrue(result.getAcl().get(0).getPermissions().contains(SamplePermissions.VIEW)); @@ -683,7 +683,7 @@ public void testPropagateFamilyPermission() throws CatalogException { public void getFamilyWithOnlyAllowedMembers2() throws CatalogException, IOException { createDummyFamily("Martinez-Martinez", true); - catalogManager.getUserManager().create("user2", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, + catalogManager.getUserManager().create(organizationId, "user2", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, opencgaToken); String token = catalogManager.getUserManager().login("user2", TestParamConstants.PASSWORD).getToken(); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FileManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FileManagerTest.java index 0f7990541b2..b898cd50286 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FileManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/FileManagerTest.java @@ -152,7 +152,7 @@ public void testLinkCram() throws CatalogException { @Test public void testLinkAnalystUser() throws CatalogException { - catalogManager.getUserManager().create("analyst", "analyst", "a@mail.com", TestParamConstants.PASSWORD, "", 200000L, Account.AccountType.GUEST, opencgaToken); + catalogManager.getUserManager().create(organizationId, "analyst", "analyst", "a@mail.com", TestParamConstants.PASSWORD, "", 200000L, Account.AccountType.GUEST, opencgaToken); catalogManager.getStudyManager().updateAcl(organizationId, studyFqn, "analyst", new StudyAclParams("", "analyst"), ParamUtils.AclAction.SET, token); String analystToken = catalogManager.getUserManager().login("analyst", TestParamConstants.PASSWORD).getToken(); @@ -164,7 +164,7 @@ public void testLinkAnalystUser() throws CatalogException { @Test public void testLinkUserWithNoWritePermissions() throws CatalogException { - catalogManager.getUserManager().create("view_user", "view_user", "a@mail.com", TestParamConstants.PASSWORD, "", 200000L, Account.AccountType.GUEST, opencgaToken); + catalogManager.getUserManager().create(organizationId, "view_user", "view_user", "a@mail.com", TestParamConstants.PASSWORD, "", 200000L, Account.AccountType.GUEST, opencgaToken); catalogManager.getStudyManager().updateAcl(organizationId, studyFqn, "view_user", new StudyAclParams("", "view_only"), ParamUtils.AclAction.SET, token); String analystToken = catalogManager.getUserManager().login("view_user", TestParamConstants.PASSWORD).getToken(); @@ -958,7 +958,7 @@ public void testCreateFolder() throws Exception { sessionIdUser2); Path myStudy = Files.createDirectory(catalogManagerResource.getOpencgaHome().resolve("myStudy")); - String newStudy = catalogManager.getStudyManager().create(project2, "alias", null, "name", "", null, null, null, null, null, sessionIdUser2).first().getFqn(); + String newStudy = catalogManager.getStudyManager().create(organizationId, project2, "alias", null, "name", "", null, null, null, null, null, sessionIdUser2).first().getFqn(); folder = fileManager.createFolder(organizationId, newStudy, Paths.get("WOLOLO").toString(), true, null, QueryOptions.empty(), sessionIdUser2).first(); @@ -1345,7 +1345,7 @@ public void testGetTreeViewMoreThanOneFile() throws CatalogException { // Create a new study so more than one file will be found under the root /. However, it should be able to consider the study given // properly - catalogManager.getStudyManager().create(project1, "phase2", null, "Phase 2", "Done", null, null, null, null, null, token).first().getUid(); + catalogManager.getStudyManager().create(organizationId, project1, "phase2", null, "Phase 2", "Done", null, null, null, null, null, token).first().getUid(); DataResult fileTree = fileManager.getTree(organizationId, studyFqn, "/", 5, new QueryOptions(), token); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/IndividualManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/IndividualManagerTest.java index 873a9a8f3cb..0bf528751db 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/IndividualManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/IndividualManagerTest.java @@ -285,7 +285,7 @@ public void testUpdateIndividualSamples() throws CatalogException { .filter(s -> Arrays.asList(sample.getId(), sample2.getId()).contains(s)).count()); // Increase sample2 version - catalogManager.getSampleManager().update(studyFqn, sample2.getId(), new SampleUpdateParams().setDescription("new description"), + catalogManager.getSampleManager().update(organizationId, studyFqn, sample2.getId(), new SampleUpdateParams().setDescription("new description"), new QueryOptions(), token); // Add sample2 (with new version) and sample3 diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/InterpretationManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/InterpretationManagerTest.java index 17e07fdb85d..d4753db1336 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/InterpretationManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/InterpretationManagerTest.java @@ -60,15 +60,15 @@ public void setUp() throws IOException, CatalogException { public void setUpCatalogManager(CatalogManager catalogManager) throws IOException, CatalogException { opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); - catalogManager.getUserManager().create("user2", "User Name2", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, + catalogManager.getUserManager().create(organizationId, "user2", "User Name2", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, opencgaToken); - String projectId = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first().getId(); - catalogManager.getStudyManager().create(projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); + catalogManager.getStudyManager().create(organizationId, projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); } @After diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/PanelManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/PanelManagerTest.java index 28c7bc5b90b..614a6342fb0 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/PanelManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/PanelManagerTest.java @@ -80,12 +80,12 @@ public void setUp() throws IOException, CatalogException { private void setUpCatalogManager(CatalogManager catalogManager) throws IOException, CatalogException { opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); - String projectId = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first().getId(); - catalogManager.getStudyManager().create(projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); + catalogManager.getStudyManager().create(organizationId, projectId, "phase1", null, "Phase 1", "Done", null, null, null, null, null, sessionIdUser); } @Test @@ -100,10 +100,10 @@ public void createTest() throws IOException, CatalogException { @Test public void importFromSource() throws CatalogException { - OpenCGAResult cancer = panelManager.importFromSource(studyFqn, "gene-census", null, sessionIdUser); + OpenCGAResult cancer = panelManager.importFromSource(organizationId, studyFqn, "gene-census", null, sessionIdUser); assertEquals(1, cancer.getNumInserted()); - OpenCGAResult panelApp = panelManager.importFromSource(studyFqn, "panelapp", "Thoracic_aortic_aneurysm_and_dissection-PanelAppId-700,VACTERL-like_phenotypes-PanelAppId-101", sessionIdUser); + OpenCGAResult panelApp = panelManager.importFromSource(organizationId, studyFqn, "panelapp", "Thoracic_aortic_aneurysm_and_dissection-PanelAppId-700,VACTERL-like_phenotypes-PanelAppId-101", sessionIdUser); assertEquals(2, panelApp.getNumInserted()); } @@ -111,19 +111,19 @@ public void importFromSource() throws CatalogException { public void importFromSourceInvalidId() throws CatalogException { thrown.expect(CatalogException.class); thrown.expectMessage("Unknown panel"); - panelManager.importFromSource(studyFqn, "gene-census", "ZSR222", sessionIdUser); + panelManager.importFromSource(organizationId, studyFqn, "gene-census", "ZSR222", sessionIdUser); } @Test public void importFromInvalidSource() throws CatalogException { thrown.expect(CatalogException.class); thrown.expectMessage("Unknown source"); - panelManager.importFromSource(studyFqn, "gene-census-wrong", null, sessionIdUser); + panelManager.importFromSource(organizationId, studyFqn, "gene-census-wrong", null, sessionIdUser); } @Test public void updateTest() throws CatalogException { - panelManager.importFromSource(studyFqn, "gene-census", null, sessionIdUser); + panelManager.importFromSource(organizationId, studyFqn, "gene-census", null, sessionIdUser); Panel panel = panelManager.get(organizationId, studyFqn, "gene-census", QueryOptions.empty(), sessionIdUser).first(); assertEquals(1, panel.getVersion()); assertEquals((int) panel.getStats().get("numberOfRegions"), panel.getVariants().size()); @@ -146,7 +146,7 @@ public void updateTest() throws CatalogException { .setVariants(Collections.singletonList(variantPanel)) .setGenes(Collections.singletonList(genePanel)); - DataResult updateResult = panelManager.update(studyFqn, "gene-census", updateParams, null, sessionIdUser); + DataResult updateResult = panelManager.update(organizationId, studyFqn, "gene-census", updateParams, null, sessionIdUser); assertEquals(1, updateResult.getNumUpdated()); Panel updatedPanel = panelManager.get(organizationId, studyFqn, "gene-census", QueryOptions.empty(), sessionIdUser).first(); @@ -174,7 +174,7 @@ public void updateTest() throws CatalogException { @Test public void deletePanelTest() throws CatalogException { - panelManager.importFromSource(studyFqn, "gene-census", null, sessionIdUser); + panelManager.importFromSource(organizationId, studyFqn, "gene-census", null, sessionIdUser); Panel panel = panelManager.get(organizationId, studyFqn, "gene-census", QueryOptions.empty(), sessionIdUser).first(); assertEquals(1, panel.getVersion()); @@ -192,14 +192,14 @@ public void deletePanelTest() throws CatalogException { @Test public void deletePanelWithVersionsTest() throws CatalogException { - panelManager.importFromSource(studyFqn, "gene-census", null, sessionIdUser); + panelManager.importFromSource(organizationId, studyFqn, "gene-census", null, sessionIdUser); Panel panel = panelManager.get(organizationId, studyFqn, "gene-census", QueryOptions.empty(), sessionIdUser).first(); assertEquals(1, panel.getVersion()); PanelUpdateParams updateParams = new PanelUpdateParams() .setSource(new DiseasePanel.SourcePanel().setAuthor("author")) .setDisorders(Collections.singletonList(new OntologyTerm().setId("ontologyTerm"))); - DataResult updateResult = panelManager.update(studyFqn, "gene-census", updateParams, null, sessionIdUser); + DataResult updateResult = panelManager.update(organizationId, studyFqn, "gene-census", updateParams, null, sessionIdUser); assertEquals(1, updateResult.getNumUpdated()); OpenCGAResult result = panelManager.delete(organizationId, studyFqn, Collections.singletonList("gene-census"), QueryOptions.empty(), sessionIdUser); @@ -294,7 +294,7 @@ public void panelIncrementVersionWithCasesAndInterpretations() throws CatalogExc QueryOptions.empty(), sessionIdUser); // Update panel1 ... - panelManager.update(studyFqn, panel1.getId(), new PanelUpdateParams().setName("name"), QueryOptions.empty(), sessionIdUser); + panelManager.update(organizationId, studyFqn, panel1.getId(), new PanelUpdateParams().setName("name"), QueryOptions.empty(), sessionIdUser); OpenCGAResult resultPanel = panelManager.get(organizationId, studyFqn, panel1.getId(), QueryOptions.empty(), sessionIdUser); assertEquals(2, resultPanel.first().getVersion()); assertEquals("name", resultPanel.first().getName()); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ProjectManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ProjectManagerTest.java index 548f8d8ac7f..0d5fa4d41c7 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ProjectManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/ProjectManagerTest.java @@ -82,25 +82,25 @@ public void setUp() throws IOException, CatalogException { public void setUpCatalogManager(CatalogManager catalogManager) throws IOException, CatalogException { opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create("user2", "User2 Name", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); - catalogManager.getUserManager().create("user3", "User3 Name", "user.2@e.mail", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user2", "User2 Name", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user3", "User3 Name", "user.2@e.mail", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); sessionIdUser2 = catalogManager.getUserManager().login("user2", TestParamConstants.PASSWORD).getToken(); sessionIdUser3 = catalogManager.getUserManager().login("user3", TestParamConstants.PASSWORD).getToken(); - project1 = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + project1 = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first().getId(); - project2 = catalogManager.getProjectManager().create("pmp", "Project Management Project", "life art intelligent system", + project2 = catalogManager.getProjectManager().create(organizationId, "pmp", "Project Management Project", "life art intelligent system", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser2).first().getId(); - project3 = catalogManager.getProjectManager().create("p1", "project 1", "", "Homo sapiens", + project3 = catalogManager.getProjectManager().create(organizationId, "p1", "project 1", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser3).first().getId(); - studyId = catalogManager.getStudyManager().create(project1, "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first().getFqn(); - studyId2 = catalogManager.getStudyManager().create(project1, "phase3", null, "Phase 3", "d", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first().getFqn(); + studyId = catalogManager.getStudyManager().create(organizationId, project1, "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first().getFqn(); + studyId2 = catalogManager.getStudyManager().create(organizationId, project1, "phase3", null, "Phase 3", "d", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first().getFqn(); - studyId3 = catalogManager.getStudyManager().create(project2, "s1", null, "Study 1", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first().getFqn(); + studyId3 = catalogManager.getStudyManager().create(organizationId, project2, "s1", null, "Study 1", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first().getFqn(); } @Test @@ -134,14 +134,14 @@ public void searchSampleNoPermissions() throws CatalogException { @Test public void searchProjects() throws CatalogException { - catalogManager.getUserManager().create("userid", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "userid", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); String token = catalogManager.getUserManager().login("userid", TestParamConstants.PASSWORD).getToken(); OpenCGAResult projectOpenCGAResult = catalogManager.getProjectManager().search(organizationId, new Query(), QueryOptions.empty(), token); assertTrue(projectOpenCGAResult.getResults().isEmpty()); assertEquals(0, projectOpenCGAResult.getEvents().size()); String otherUser = "user_tmp"; - catalogManager.getUserManager().create(otherUser, "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, otherUser, "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); String otherUsertoken = catalogManager.getUserManager().login(otherUser, TestParamConstants.PASSWORD).getToken(); OpenCGAResult result = catalogManager.getProjectManager() .search(organizationId, new Query(), QueryOptions.empty(), otherUsertoken); @@ -149,7 +149,7 @@ public void searchProjects() throws CatalogException { assertEquals(0, result.getEvents().size()); // Create a new study in project2 with some dummy permissions for user - String s2 = catalogManager.getStudyManager().create(project2, "s2", null, "Study 2", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first().getId(); + String s2 = catalogManager.getStudyManager().create(organizationId, project2, "s2", null, "Study 2", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first().getId(); catalogManager.getStudyManager().updateGroup(organizationId, s2, "@members", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList(otherUser)), sessionIdUser2); @@ -170,7 +170,7 @@ public void getSharedProjects() throws CatalogException { } // Create a new study in project2 with some dummy permissions for user - String s2 = catalogManager.getStudyManager().create(project2, "s2", null, "Study 2", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first().getId(); + String s2 = catalogManager.getStudyManager().create(organizationId, project2, "s2", null, "Study 2", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser2).first().getId(); catalogManager.getStudyManager().updateGroup(organizationId, s2, "@members", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("user")), sessionIdUser2); @@ -188,7 +188,7 @@ public void getSharedProjects() throws CatalogException { assertEquals("user2@pmp", queryResult.first().getFqn()); // Add permissions to user in a study of user3 - String s3 = catalogManager.getStudyManager().create(project3, "s3", null, "StudyProject3", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser3).first().getId(); + String s3 = catalogManager.getStudyManager().create(organizationId, project3, "s3", null, "StudyProject3", "", null, null, null, null, INCLUDE_RESULT, sessionIdUser3).first().getId(); catalogManager.getStudyManager().updateGroup(organizationId, String.valueOf(s3), "@members", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("user")), sessionIdUser3); @@ -205,7 +205,7 @@ public void getSharedProjects() throws CatalogException { @Test public void updateOrganismInProject() throws CatalogException { - Project pr = catalogManager.getProjectManager().create("project2", "Project about some genomes", "", "Homo sapiens", + Project pr = catalogManager.getProjectManager().create(organizationId, "project2", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first(); assertEquals("Homo sapiens", pr.getOrganism().getScientificName()); @@ -281,7 +281,7 @@ public void createProjectWrongCellbase() throws CatalogException, JsonProcessing @Test public void updateCellbaseInProject() throws CatalogException, JsonProcessingException { - Project pr = catalogManager.getProjectManager().create("project2", "Project about some genomes", "", "Homo sapiens", + Project pr = catalogManager.getProjectManager().create(organizationId, "project2", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first(); assertNotNull(pr.getCellbase()); assertEquals("https://ws.zettagenomics.com/cellbase", pr.getCellbase().getUrl()); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/SampleManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/SampleManagerTest.java index 106f3a6769f..3d37e60d1d7 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/SampleManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/SampleManagerTest.java @@ -91,9 +91,9 @@ public void testSampleVersioning() throws CatalogException { catalogManager.getSampleManager().create(organizationId, studyFqn, new Sample().setId("testSample").setDescription("description"), null, token); - catalogManager.getSampleManager().update(studyFqn, "testSample", new SampleUpdateParams().setDescription(descriptions.get(0)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setDescription(descriptions.get(0)), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, "testSample", new SampleUpdateParams().setDescription(descriptions.get(1)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setDescription(descriptions.get(1)), new QueryOptions(), token); catalogManager.getProjectManager().incrementRelease(organizationId, projectId, token); @@ -101,10 +101,10 @@ public void testSampleVersioning() throws CatalogException { catalogManager.getSampleManager().create(organizationId, studyFqn, new Sample().setId("dummy"), null, token); catalogManager.getProjectManager().incrementRelease(organizationId, projectId, token); - catalogManager.getSampleManager().update(studyFqn, "testSample", new SampleUpdateParams().setDescription(descriptions.get(2)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setDescription(descriptions.get(2)), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, "testSample", + catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setDescription("new description"), null, token); // We want the whole history of the sample @@ -185,7 +185,7 @@ public void testCustomCreationDate() throws CatalogException { assertEquals(1, search.getNumResults()); assertEquals("s1", search.first().getId()); - catalogManager.getSampleManager().update(studyFqn, "s1", new SampleUpdateParams().setCreationDate("20160101120000"), + catalogManager.getSampleManager().update(organizationId, studyFqn, "s1", new SampleUpdateParams().setCreationDate("20160101120000"), QueryOptions.empty(), token); search = catalogManager.getSampleManager().search(organizationId, studyFqn, new Query(SampleDBAdaptor.QueryParams.CREATION_DATE.key(), "<2015"), QueryOptions.empty(), token); @@ -212,7 +212,7 @@ public void testCustomModificationDate() throws CatalogException { assertEquals(1, search.getNumResults()); assertEquals("s1", search.first().getId()); - catalogManager.getSampleManager().update(studyFqn, "s1", new SampleUpdateParams().setModificationDate("20160101120000"), + catalogManager.getSampleManager().update(organizationId, studyFqn, "s1", new SampleUpdateParams().setModificationDate("20160101120000"), QueryOptions.empty(), token); search = catalogManager.getSampleManager().search(organizationId, studyFqn, new Query(SampleDBAdaptor.QueryParams.MODIFICATION_DATE.key(), "<2015"), QueryOptions.empty(), token); @@ -239,9 +239,9 @@ public void testSampleVersioningWithWeirdId() throws CatalogException { catalogManager.getSampleManager().create(organizationId, studyFqn, new Sample().setId(sampleId).setDescription("description"), null, token); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams().setDescription(descriptions.get(0)), + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams().setDescription(descriptions.get(0)), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams().setDescription(descriptions.get(1)), + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams().setDescription(descriptions.get(1)), new QueryOptions(), token); catalogManager.getProjectManager().incrementRelease(organizationId, projectId, token); @@ -249,10 +249,10 @@ public void testSampleVersioningWithWeirdId() throws CatalogException { catalogManager.getSampleManager().create(organizationId, studyFqn, new Sample().setId("du--m---m..y"), null, token); catalogManager.getProjectManager().incrementRelease(organizationId, projectId, token); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams().setDescription(descriptions.get(2)), + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams().setDescription(descriptions.get(2)), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, sampleId, + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams().setDescription("new description"), null, token); // We want the whole history of the sample @@ -392,7 +392,7 @@ public void searchByInternalAnnotationSetTest() throws CatalogException { // Update sample annotation to be exactly the same as sample2 ObjectMap action = new ObjectMap(SampleDBAdaptor.QueryParams.ANNOTATION_SETS.key(), ParamUtils.BasicUpdateAction.SET); QueryOptions options = new QueryOptions(Constants.ACTIONS, action); - catalogManager.getSampleManager().update(studyFqn, sample.getId(), + catalogManager.getSampleManager().update(organizationId, studyFqn, sample.getId(), new SampleUpdateParams().setAnnotationSets(Arrays.asList(annotationSet, annotationSet2)), options, token); query = new Query(Constants.ANNOTATION, "myInternalVset:a=hello"); @@ -417,7 +417,7 @@ public void searchByInternalAnnotationSetTest() throws CatalogException { @Test public void testMultipleUpdate() throws CatalogException { - catalogManager.getSampleManager().update(studyFqn, Arrays.asList("s_1", "s_2", "s_3"), + catalogManager.getSampleManager().update(organizationId, studyFqn, Arrays.asList("s_1", "s_2", "s_3"), new SampleUpdateParams() .setSomatic(true) .setQualityControl(new SampleQualityControl()), @@ -452,7 +452,7 @@ public void updateQualityControlTest1() throws CatalogException { SampleVariantQualityControlMetrics metrics = new SampleVariantQualityControlMetrics(sampleQcVariantStats, null, null, null, null); SampleQualityControl qualityControl = new SampleQualityControl(null, null, metrics); - OpenCGAResult result = catalogManager.getSampleManager().update(studyFqn, "sample", + OpenCGAResult result = catalogManager.getSampleManager().update(organizationId, studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), QueryOptions.empty(), token); assertEquals(1, result.getNumUpdated()); @@ -496,7 +496,7 @@ public void updateQualityControlTest1() throws CatalogException { qualityControl = new SampleQualityControl(null, null, metrics); // And update sample - result = catalogManager.getSampleManager().update(studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), + result = catalogManager.getSampleManager().update(organizationId, studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), QueryOptions.empty(), token); assertEquals(1, result.getNumUpdated()); @@ -532,7 +532,7 @@ public void updateQualityControlTest1() throws CatalogException { assertEquals(1, catalogManager.getSampleManager().count(organizationId, studyFqn, query, token).getNumMatches()); // Update any other sample field to validate it doesn't affect quality control - result = catalogManager.getSampleManager().update(studyFqn, "sample", new SampleUpdateParams().setDescription("my description"), + result = catalogManager.getSampleManager().update(organizationId, studyFqn, "sample", new SampleUpdateParams().setDescription("my description"), QueryOptions.empty(), token); assertEquals(1, result.getNumUpdated()); @@ -571,7 +571,7 @@ public void updateQualityControlTest1() throws CatalogException { qualityControl = new SampleQualityControl(Arrays.asList("file1", "file2"), null, null); // And update sample - result = catalogManager.getSampleManager().update(studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), + result = catalogManager.getSampleManager().update(organizationId, studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), QueryOptions.empty(), token); assertEquals(1, result.getNumUpdated()); @@ -626,7 +626,7 @@ public void updateQualityControlTest2() throws CatalogException { SampleVariantQualityControlMetrics metrics = new SampleVariantQualityControlMetrics(sampleQcVariantStats, null, null, null, null); SampleQualityControl qualityControl = new SampleQualityControl(null, null, metrics); - OpenCGAResult result = catalogManager.getSampleManager().update(studyFqn, "sample", + OpenCGAResult result = catalogManager.getSampleManager().update(organizationId, studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), QueryOptions.empty(), token); assertEquals(1, result.getNumUpdated()); @@ -661,7 +661,7 @@ public void updateQualityControlTest2() throws CatalogException { qualityControl = new SampleQualityControl(null, null, metrics); // And update sample - result = catalogManager.getSampleManager().update(studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), + result = catalogManager.getSampleManager().update(organizationId, studyFqn, "sample", new SampleUpdateParams().setQualityControl(qualityControl), QueryOptions.empty(), token); assertEquals(1, result.getNumUpdated()); @@ -716,14 +716,14 @@ public void updateAndReturnResultTest() throws CatalogException { SampleProcessing processing = new SampleProcessing(null, "preparationMethod", "extractionMethod", "labSampleId", "quantity", "date", Collections.emptyMap()); - OpenCGAResult result = catalogManager.getSampleManager().update(studyFqn, "testSample", + OpenCGAResult result = catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setProcessing(processing), new QueryOptions(), token); assertEquals(1, result.getNumUpdated()); assertEquals(1, result.getNumMatches()); assertEquals(0, result.getNumResults()); assertEquals(0, result.getResults().size()); - result = catalogManager.getSampleManager().update(studyFqn, "testSample", + result = catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setDescription("my new description"), new QueryOptions() .append(ParamConstants.INCLUDE_RESULT_PARAM, true) , token); @@ -742,7 +742,7 @@ public void updateProcessingField() throws CatalogException { SampleProcessing processing = new SampleProcessing(new OntologyTermAnnotation().setId("product"), "preparationMethod", "extractionMethod", "labSampleId", "quantity", "date", Collections.emptyMap()); - catalogManager.getSampleManager().update(studyFqn, "testSample", + catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setProcessing(processing), new QueryOptions(), token); DataResult testSample = catalogManager.getSampleManager().get(organizationId, studyFqn, "testSample", new QueryOptions(), token); @@ -763,7 +763,7 @@ public void updateCollectionField() throws CatalogException { SampleCollection collection = new SampleCollection(Collections.singletonList(new OntologyTermAnnotation("id", "name", "desc", "source", "", Collections.emptyMap())), "type", "quantity", "method", "date", Collections.emptyMap()); StatusParams statusParams = new StatusParams("status1", "status1", "my description"); - catalogManager.getSampleManager().update(studyFqn, "testSample", + catalogManager.getSampleManager().update(organizationId, studyFqn, "testSample", new SampleUpdateParams().setCollection(collection).setStatus(statusParams), new QueryOptions(), token); @@ -861,7 +861,7 @@ public void testUpdateWithLockedClinicalAnalysis() throws CatalogException { catalogManager.getClinicalAnalysisManager().create(organizationId, studyFqn, clinicalAnalysis, new QueryOptions(), token); // Update sample1 from proband not used in Clinical Analysis - catalogManager.getSampleManager().update(studyFqn, "sample1", new SampleUpdateParams().setDescription("a"), new QueryOptions(), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample1", new SampleUpdateParams().setDescription("a"), new QueryOptions(), token); Sample sampleResult = catalogManager.getSampleManager().get(organizationId, studyFqn, "sample1", QueryOptions.empty(), token).first(); @@ -895,7 +895,7 @@ public void testUpdateWithLockedClinicalAnalysis() throws CatalogException { assertEquals(2, clinicalResult.getFamily().getMembers().get(1).getVersion()); // father version // Update sample used in Clinical Analysis from father - catalogManager.getSampleManager().update(studyFqn, "sample3", new SampleUpdateParams().setDescription("asd"), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample3", new SampleUpdateParams().setDescription("asd"), new QueryOptions(), token); sampleResult = catalogManager.getSampleManager().get(organizationId, studyFqn, "sample3", QueryOptions.empty(), token).first(); @@ -930,7 +930,7 @@ public void testUpdateWithLockedClinicalAnalysis() throws CatalogException { assertEquals(3, clinicalResult.getFamily().getMembers().get(1).getSamples().get(0).getVersion()); // father sample3 version catalogManager.getSampleManager().updateSampleInternalVariantSecondarySampleIndex( - catalogManager.getSampleManager().get(organizationId, studyFqn, "sample3", null, token).first(), + organizationId, catalogManager.getSampleManager().get(organizationId, studyFqn, "sample3", null, token).first(), new SampleInternalVariantSecondarySampleIndex( new IndexStatus(IndexStatus.READY, "This should be doable!"), new IndexStatus(IndexStatus.READY, "This should be doable!"), @@ -938,7 +938,7 @@ public void testUpdateWithLockedClinicalAnalysis() throws CatalogException { ), token); // Update sample 2 from proband - catalogManager.getSampleManager().update(studyFqn, "sample2", new SampleUpdateParams().setDescription("asda"), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample2", new SampleUpdateParams().setDescription("asda"), new QueryOptions(), token); sampleResult = catalogManager.getSampleManager().get(organizationId, studyFqn, "sample2", QueryOptions.empty(), token).first(); @@ -1002,7 +1002,7 @@ public void testAnnotate() throws CatalogException { annotations.put("HEIGHT", 180); annotations.put("MAP", new ObjectMap("unknownKey1", "value1").append("unknownKey2", 42)); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); @@ -1058,7 +1058,7 @@ public void testDynamicAnnotationsCreation() throws CatalogException, IOExceptio ObjectMapper objectMapper = new ObjectMapper(); ObjectMap annotations = objectMapper.readValue(inputStream, ObjectMap.class); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); @@ -1075,7 +1075,7 @@ public void testDynamicAnnotationsCreation() throws CatalogException, IOExceptio thrown.expect(CatalogException.class); thrown.expectMessage("Missing required variable"); - catalogManager.getSampleManager().update(studyFqn, s_2, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_2, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); } @@ -1095,7 +1095,7 @@ public void testWrongAnnotation() throws CatalogException { .append("b", "my_string"); try { - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotation))), QueryOptions.empty(), token); fail("Annotation '5' should not be valid for variable MAP_INTEGER"); @@ -1105,7 +1105,7 @@ public void testWrongAnnotation() throws CatalogException { annotation.put("a", new ObjectMap("b", "test")); try { - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotation))), QueryOptions.empty(), token); fail("Annotation 'a.b' should not be INTEGER instead of STRING"); @@ -1115,7 +1115,7 @@ public void testWrongAnnotation() throws CatalogException { annotation.put("a", new ObjectMap("b", "46")); try { - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotation))), QueryOptions.empty(), token); fail("Annotation 'a.b' should not be INTEGER instead of STRING"); @@ -1124,7 +1124,7 @@ public void testWrongAnnotation() throws CatalogException { } annotation.put("a", new ObjectMap("b", 46)); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotation))), QueryOptions.empty(), token); } @@ -1164,7 +1164,7 @@ public void testVariableAllowedKeys() throws CatalogException, IOException { ObjectMapper objectMapper = new ObjectMapper(); ObjectMap annotations = objectMapper.readValue(inputStream, ObjectMap.class); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); @@ -1202,7 +1202,7 @@ public void testVariableAllowedKeys() throws CatalogException, IOException { thrown.expect(CatalogException.class); thrown.expectMessage("not an accepted key"); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation2", vs2.getId(), annotations))), QueryOptions.empty(), token); } @@ -1252,7 +1252,7 @@ public void testDynamicAnnotationsSearch() throws CatalogException, IOException .append(".asd", 4) ); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); @@ -1287,7 +1287,7 @@ public void searchSamples() throws CatalogException { catalogManager.getStudyManager().updateAcl(organizationId, Arrays.asList(studyFqn), "@myGroup", new StudyAclParams("", null), SET, token); - catalogManager.getSampleManager().updateAcl(studyFqn, Arrays.asList("s_1"), "@myGroup", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Arrays.asList("s_1"), "@myGroup", new SampleAclParams(null, null, null, null, "VIEW"), SET, token); DataResult search = catalogManager.getSampleManager().search(organizationId, studyFqn, new Query(), new QueryOptions(), @@ -1314,16 +1314,16 @@ public void testDeleteAnnotationset() throws CatalogException, JsonProcessingExc AnnotationSet annotationSet = new AnnotationSet("annotation1", vs1.getId(), annotations); AnnotationSet annotationSet1 = new AnnotationSet("annotation2", vs1.getId(), annotations); - DataResult update = catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + DataResult update = catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Arrays.asList(annotationSet, annotationSet1)), QueryOptions.empty(), token); assertEquals(1, update.getNumUpdated()); Sample sample = catalogManager.getSampleManager().get(organizationId, studyFqn, s_1, QueryOptions.empty(), token).first(); assertEquals(3, sample.getAnnotationSets().size()); - catalogManager.getSampleManager().removeAnnotationSet(studyFqn, s_1, "annotation1", QueryOptions.empty(), token); + catalogManager.getSampleManager().removeAnnotationSet(organizationId, studyFqn, s_1, "annotation1", QueryOptions.empty(), token); update = catalogManager.getSampleManager() - .removeAnnotationSet(studyFqn, s_1, "annotation2", QueryOptions.empty(), token); + .removeAnnotationSet(organizationId, studyFqn, s_1, "annotation2", QueryOptions.empty(), token); assertEquals(1, update.getNumUpdated()); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, s_1, QueryOptions.empty(), token).first(); @@ -1331,7 +1331,7 @@ public void testDeleteAnnotationset() throws CatalogException, JsonProcessingExc thrown.expect(CatalogDBException.class); thrown.expectMessage("not found"); - catalogManager.getSampleManager().removeAnnotationSet(studyFqn, s_1, "non_existing", QueryOptions.empty(), token); + catalogManager.getSampleManager().removeAnnotationSet(organizationId, studyFqn, s_1, "non_existing", QueryOptions.empty(), token); } @Test @@ -1354,7 +1354,7 @@ public void testSearchAnnotation() throws CatalogException, JsonProcessingExcept .append("HEIGHT", 180); AnnotationSet annotationSet = new AnnotationSet("annotation1", vs1.getId(), annotations); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(annotationSet)), QueryOptions.empty(), token); Query query = new Query(Constants.ANNOTATION, "var_name=Joe;" + vs1.getId() + ":AGE=25"); @@ -1434,7 +1434,7 @@ public void testAnnotateMulti() throws CatalogException { HashMap annotations = new HashMap<>(); annotations.put("NAME", "Luke"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); DataResult sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1443,7 +1443,7 @@ public void testAnnotateMulti() throws CatalogException { annotations = new HashMap<>(); annotations.put("NAME", "Lucas"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation2", vs1.getId(), annotations))), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1469,7 +1469,7 @@ public void testAnnotateUnique() throws CatalogException { HashMap annotations = new HashMap<>(); annotations.put("NAME", "Luke"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); DataResult sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1479,7 +1479,7 @@ public void testAnnotateUnique() throws CatalogException { annotations.put("NAME", "Lucas"); thrown.expect(CatalogException.class); thrown.expectMessage("unique"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation2", vs1.getId(), annotations))), QueryOptions.empty(), token); } @@ -1527,7 +1527,7 @@ public void testAnnotateIncorrectType() throws CatalogException { HashMap annotations = new HashMap<>(); annotations.put("NUM", "5"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); DataResult sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1535,7 +1535,7 @@ public void testAnnotateIncorrectType() throws CatalogException { assertEquals(1, sampleDataResult.first().getAnnotationSets().size()); annotations.put("NUM", "6.8"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation2", vs1.getId(), annotations))), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1544,7 +1544,7 @@ public void testAnnotateIncorrectType() throws CatalogException { annotations.put("NUM", "five polong five"); thrown.expect(CatalogException.class); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation3", vs1.getId(), annotations))), QueryOptions.empty(), token); } @@ -1562,7 +1562,7 @@ public void testAnnotateRange() throws CatalogException { HashMap annotations = new HashMap<>(); annotations.put("RANGE_NUM", "1"); // 1:14 - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); DataResult sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1570,7 +1570,7 @@ public void testAnnotateRange() throws CatalogException { assertEquals(1, sampleDataResult.first().getAnnotationSets().size()); annotations.put("RANGE_NUM", "14"); // 1:14 - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation2", vs1.getId(), annotations))), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1578,7 +1578,7 @@ public void testAnnotateRange() throws CatalogException { assertEquals(2, sampleDataResult.first().getAnnotationSets().size()); annotations.put("RANGE_NUM", "20"); // 16:20 - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation3", vs1.getId(), annotations))), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1586,7 +1586,7 @@ public void testAnnotateRange() throws CatalogException { assertEquals(3, sampleDataResult.first().getAnnotationSets().size()); annotations.put("RANGE_NUM", "100000"); // 50: - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation4", vs1.getId(), annotations))), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1595,7 +1595,7 @@ public void testAnnotateRange() throws CatalogException { annotations.put("RANGE_NUM", "14.1"); thrown.expect(CatalogException.class); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation5", vs1.getId(), annotations))), QueryOptions.empty(), token); } @@ -1617,7 +1617,7 @@ public void testAnnotateCategorical() throws CatalogException { HashMap annotations = new HashMap<>(); annotations.put("COOL_NAME", "LUKE"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), options, token); DataResult sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1625,7 +1625,7 @@ public void testAnnotateCategorical() throws CatalogException { assertEquals(1, sampleDataResult.first().getAnnotationSets().size()); annotations.put("COOL_NAME", "LEIA"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation2", vs1.getId(), annotations))), options, token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1633,7 +1633,7 @@ public void testAnnotateCategorical() throws CatalogException { assertEquals(2, sampleDataResult.first().getAnnotationSets().size()); annotations.put("COOL_NAME", "VADER"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation3", vs1.getId(), annotations))), options, token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1641,7 +1641,7 @@ public void testAnnotateCategorical() throws CatalogException { assertEquals(3, sampleDataResult.first().getAnnotationSets().size()); annotations.put("COOL_NAME", "YODA"); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation4", vs1.getId(), annotations))), options, token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId, @@ -1650,7 +1650,7 @@ public void testAnnotateCategorical() throws CatalogException { annotations.put("COOL_NAME", "SPOCK"); thrown.expect(CatalogException.class); - catalogManager.getSampleManager().update(studyFqn, sampleId, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation5", vs1.getId(), annotations))), options, token); } @@ -1672,7 +1672,7 @@ public void testAnnotateNested() throws CatalogException { .append("object", new ObjectMap() .append("string", "my value") .append("numberList", Arrays.asList(2, 3, 4)))); - catalogManager.getSampleManager().update(studyFqn, sampleId1, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId1, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); DataResult sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId1, @@ -1684,7 +1684,7 @@ public void testAnnotateNested() throws CatalogException { .append("object", new ObjectMap() .append("string", "stringValue") .append("numberList", Arrays.asList(3, 4, 5)))); - catalogManager.getSampleManager().update(studyFqn, sampleId2, new SampleUpdateParams() + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId2, new SampleUpdateParams() .setAnnotationSets(Collections.singletonList(new AnnotationSet("annotation1", vs1.getId(), annotations))), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId2, @@ -1857,7 +1857,7 @@ public void testQuerySamples() throws CatalogException { public void testUpdateSampleId() throws CatalogException { thrown.expect(CatalogException.class); thrown.expectMessage("valid id"); - catalogManager.getSampleManager().update(studyFqn, s_1, new SampleUpdateParams().setId(""), QueryOptions.empty(), token); + catalogManager.getSampleManager().update(organizationId, studyFqn, s_1, new SampleUpdateParams().setId(""), QueryOptions.empty(), token); } @Test @@ -1881,7 +1881,7 @@ public void testUpdateAnnotation() throws CatalogException { catalogManager.getIndividualManager().updateAnnotations(organizationId, studyFqn, ind.getId(), annotationSet.getId(), annotationSet.getAnnotations(), ParamUtils.CompleteUpdateAction.SET, new QueryOptions(), token); - catalogManager.getSampleManager().updateAnnotations(studyFqn, s_1, annotationSet.getId(), annotationSet.getAnnotations(), + catalogManager.getSampleManager().updateAnnotations(organizationId, studyFqn, s_1, annotationSet.getId(), annotationSet.getAnnotations(), ParamUtils.CompleteUpdateAction.SET, new QueryOptions(), token); Consumer check = as -> { @@ -1911,7 +1911,7 @@ public void testUpdateAnnotation() throws CatalogException { catalogManager.getIndividualManager().updateAnnotations(organizationId, studyFqn, ind.getId(), annotationSet.getId(), annotationSet.getAnnotations(), ParamUtils.CompleteUpdateAction.SET, new QueryOptions(), token); - catalogManager.getSampleManager().updateAnnotations(studyFqn, s_1, annotationSet.getId(), annotationSet.getAnnotations(), + catalogManager.getSampleManager().updateAnnotations(organizationId, studyFqn, s_1, annotationSet.getId(), annotationSet.getAnnotations(), ParamUtils.CompleteUpdateAction.SET, new QueryOptions(), token); check = as -> { @@ -1932,7 +1932,7 @@ public void testUpdateAnnotation() throws CatalogException { catalogManager.getIndividualManager().updateAnnotations(organizationId, studyFqn, ind.getId(), annotationSet.getId(), annotationSet.getAnnotations(), ParamUtils.CompleteUpdateAction.SET, new QueryOptions(), token); - catalogManager.getSampleManager().updateAnnotations(studyFqn, s_1, annotationSet.getId(), annotationSet.getAnnotations(), + catalogManager.getSampleManager().updateAnnotations(organizationId, studyFqn, s_1, annotationSet.getId(), annotationSet.getAnnotations(), ParamUtils.CompleteUpdateAction.SET, new QueryOptions(), token); check = as -> { @@ -1953,7 +1953,7 @@ public void testUpdateAnnotation() throws CatalogException { // Action now is ADD, we only want to change that annotation catalogManager.getIndividualManager().updateAnnotations(organizationId, studyFqn, ind.getId(), annotationSet.getId(), annotationUpdate, ParamUtils.CompleteUpdateAction.ADD, new QueryOptions(), token); - catalogManager.getSampleManager().updateAnnotations(studyFqn, s_1, annotationSet.getId(), annotationUpdate, + catalogManager.getSampleManager().updateAnnotations(organizationId, studyFqn, s_1, annotationSet.getId(), annotationUpdate, ParamUtils.CompleteUpdateAction.ADD, new QueryOptions(), token); check = as -> { @@ -1986,7 +1986,7 @@ public void testUpdatePhenotypes() throws CatalogException { ); SampleUpdateParams updateParams = new SampleUpdateParams().setPhenotypes(phenotypeList); - catalogManager.getSampleManager().update(studyFqn, sample.getId(), updateParams, QueryOptions.empty(), token); + catalogManager.getSampleManager().update(organizationId, studyFqn, sample.getId(), updateParams, QueryOptions.empty(), token); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, sample.getId(), QueryOptions.empty(), token).first(); assertEquals(3, sample.getPhenotypes().size()); for (int i = 0; i < sample.getPhenotypes().size(); i++) { @@ -1999,7 +1999,7 @@ public void testUpdatePhenotypes() throws CatalogException { QueryOptions options = new QueryOptions(Constants.ACTIONS, actionMap); updateParams = new SampleUpdateParams().setPhenotypes(Arrays.asList( new Phenotype("phenotype0", "phenotypeName0", "SOURCE"), new Phenotype("phenotype2", "phenotypeName2", "SOURCE"))); - catalogManager.getSampleManager().update(studyFqn, sample.getId(), updateParams, options, token); + catalogManager.getSampleManager().update(organizationId, studyFqn, sample.getId(), updateParams, options, token); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, sample.getId(), QueryOptions.empty(), token).first(); assertEquals(1, sample.getPhenotypes().size()); assertEquals("phenotype1", sample.getPhenotypes().get(0).getId()); @@ -2009,7 +2009,7 @@ public void testUpdatePhenotypes() throws CatalogException { options = new QueryOptions(Constants.ACTIONS, actionMap); updateParams = new SampleUpdateParams().setPhenotypes(Arrays.asList( new Phenotype("phenotype1", "phenotypeName1", "SOURCE"), new Phenotype("phenotype2", "phenotypeName2", "SOURCE"))); - catalogManager.getSampleManager().update(studyFqn, sample.getId(), updateParams, options, token); + catalogManager.getSampleManager().update(organizationId, studyFqn, sample.getId(), updateParams, options, token); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, sample.getId(), QueryOptions.empty(), token).first(); assertEquals(2, sample.getPhenotypes().size()); for (int i = 0; i < sample.getPhenotypes().size(); i++) { @@ -2024,7 +2024,7 @@ public void testUpdatePhenotypes() throws CatalogException { new Phenotype("phenotype3", "phenotypeName3", "SOURCE") ); updateParams = new SampleUpdateParams().setPhenotypes(phenotypeList); - catalogManager.getSampleManager().update(studyFqn, sample.getId(), updateParams, options, token); + catalogManager.getSampleManager().update(organizationId, studyFqn, sample.getId(), updateParams, options, token); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, sample.getId(), QueryOptions.empty(), token).first(); assertEquals(2, sample.getPhenotypes().size()); for (int i = 0; i < sample.getPhenotypes().size(); i++) { @@ -2039,7 +2039,7 @@ public void testUpdateAnnotationFail() throws CatalogException { thrown.expect(CatalogException.class); //Can not delete required fields thrown.expectMessage("required variable"); - catalogManager.getSampleManager().removeAnnotations(studyFqn, s_1, annotationSet.getId(), Collections.singletonList("NAME"), + catalogManager.getSampleManager().removeAnnotations(organizationId, studyFqn, s_1, annotationSet.getId(), Collections.singletonList("NAME"), QueryOptions.empty(), token); } @@ -2048,7 +2048,7 @@ public void testDeleteAnnotation() throws CatalogException { // We add one of the non mandatory annotations // First update - catalogManager.getSampleManager().updateAnnotations(studyFqn, s_1, "annot1", new ObjectMap("EXTRA", "extra"), + catalogManager.getSampleManager().updateAnnotations(organizationId, studyFqn, s_1, "annot1", new ObjectMap("EXTRA", "extra"), ParamUtils.CompleteUpdateAction.ADD, QueryOptions.empty(), token); Sample sample = catalogManager.getSampleManager().get(organizationId, studyFqn, s_1, null, token).first(); @@ -2056,7 +2056,7 @@ public void testDeleteAnnotation() throws CatalogException { assertEquals("extra", annotationSet.getAnnotations().get("EXTRA")); // Now we remove that non mandatory annotation - catalogManager.getSampleManager().removeAnnotations(studyFqn, s_1, annotationSet.getId(), Collections.singletonList("EXTRA"), + catalogManager.getSampleManager().removeAnnotations(organizationId, studyFqn, s_1, annotationSet.getId(), Collections.singletonList("EXTRA"), QueryOptions.empty(), token); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, s_1, null, token).first(); @@ -2066,13 +2066,13 @@ public void testDeleteAnnotation() throws CatalogException { // Now we attempt to remove one mandatory annotation thrown.expect(CatalogException.class); //Can not delete required fields thrown.expectMessage("required variable"); - catalogManager.getSampleManager().removeAnnotations(studyFqn, s_1, annotationSet.getId(), Collections.singletonList("AGE"), + catalogManager.getSampleManager().removeAnnotations(organizationId, studyFqn, s_1, annotationSet.getId(), Collections.singletonList("AGE"), QueryOptions.empty(), token); } @Test public void testDeleteAnnotationSet() throws CatalogException { - catalogManager.getSampleManager().removeAnnotationSet(studyFqn, s_1, "annot1", QueryOptions.empty(), token); + catalogManager.getSampleManager().removeAnnotationSet(organizationId, studyFqn, s_1, "annot1", QueryOptions.empty(), token); DataResult sampleDataResult = catalogManager.getSampleManager().get(organizationId, studyFqn, s_1, new QueryOptions(QueryOptions.INCLUDE, SampleDBAdaptor.QueryParams.ANNOTATION_SETS.key()), token); @@ -2128,7 +2128,7 @@ public void testModifySample() throws CatalogException { INCLUDE_RESULT, token).first().getId(); DataResult updateResult = catalogManager.getSampleManager() - .update(studyFqn, sampleId1, new SampleUpdateParams().setIndividualId(individualId), null, token); + .update(organizationId, studyFqn, sampleId1, new SampleUpdateParams().setIndividualId(individualId), null, token); assertEquals(1, updateResult.getNumUpdated()); Sample sample = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId1, QueryOptions.empty(), token).first(); @@ -2153,7 +2153,7 @@ public void associateSameSampleAndIndividualInDifferentStudies() throws CatalogE catalogManager.getSampleManager().create(organizationId, studyId, new Sample().setId(id), QueryOptions.empty(), token); catalogManager.getIndividualManager().create(organizationId, studyId, new Individual().setId(id), QueryOptions.empty(), token); - catalogManager.getSampleManager().update(studyId, id, new SampleUpdateParams().setIndividualId(id), QueryOptions.empty(), + catalogManager.getSampleManager().update(organizationId, studyId, id, new SampleUpdateParams().setIndividualId(id), QueryOptions.empty(), token); OpenCGAResult sampleResult = catalogManager.getSampleManager().get(organizationId, studyId, id, QueryOptions.empty(), token); @@ -2180,13 +2180,13 @@ public void testGetSampleAndIndividualWithPermissionsChecked() throws CatalogExc INCLUDE_RESULT, token).first().getId(); DataResult updateResult = catalogManager.getSampleManager() - .update(studyFqn, sampleId1, new SampleUpdateParams().setIndividualId(individualId), null, token); + .update(organizationId, studyFqn, sampleId1, new SampleUpdateParams().setIndividualId(individualId), null, token); assertEquals(1, updateResult.getNumUpdated()); Sample sample = catalogManager.getSampleManager().get(organizationId, studyFqn, sampleId1, QueryOptions.empty(), token).first(); assertEquals(individualId, sample.getIndividualId()); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList("SAMPLE_1"), "user2", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList("SAMPLE_1"), "user2", new SampleAclParams(null, null, null, null, SamplePermissions.VIEW.name()), SET, token); sample = catalogManager.getSampleManager().get(organizationId, studyFqn, "SAMPLE_1", new QueryOptions(SAMPLE_INCLUDE_INDIVIDUAL_PARAM, true), @@ -2254,21 +2254,21 @@ public void searchSamplesDifferentVersions() throws CatalogException { catalogManager.getSampleManager().create(organizationId, studyFqn, new Sample().setId("sample3"), QueryOptions.empty(), token); // Generate 4 versions of sample1 - catalogManager.getSampleManager().update(studyFqn, "sample1", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample1", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, "sample1", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample1", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, "sample1", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample1", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), new QueryOptions(), token); // Generate 3 versions of sample2 - catalogManager.getSampleManager().update(studyFqn, "sample2", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample2", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, "sample2", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample2", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), new QueryOptions(), token); // Generate 1 versions of sample3 - catalogManager.getSampleManager().update(studyFqn, "sample3", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), + catalogManager.getSampleManager().update(organizationId, studyFqn, "sample3", new SampleUpdateParams().setDescription(RandomStringUtils.random(5)), new QueryOptions(), token); Query query = new Query() @@ -2310,14 +2310,14 @@ public void updateIndividualFromSample() throws CatalogException { catalogManager.getIndividualManager().create(organizationId, studyFqn, new Individual().setId("Individual1"), new QueryOptions(), token); catalogManager.getIndividualManager().create(organizationId, studyFqn, new Individual().setId("Individual2"), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, "s_1", new SampleUpdateParams().setIndividualId("Individual1"), + catalogManager.getSampleManager().update(organizationId, studyFqn, "s_1", new SampleUpdateParams().setIndividualId("Individual1"), QueryOptions.empty(), token); DataResult sampleDataResult = catalogManager.getSampleManager().search(organizationId, studyFqn, new Query(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), "Individual1"), QueryOptions.empty(), token); assertEquals(1, sampleDataResult.getNumResults()); assertEquals("s_1", sampleDataResult.first().getId()); - catalogManager.getSampleManager().update(studyFqn, "s_1", new SampleUpdateParams().setIndividualId("Individual2"), + catalogManager.getSampleManager().update(organizationId, studyFqn, "s_1", new SampleUpdateParams().setIndividualId("Individual2"), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().search(organizationId, studyFqn, new Query(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), "Individual1"), QueryOptions.empty(), token); @@ -2332,7 +2332,7 @@ public void updateIndividualFromSample() throws CatalogException { catalogManager.getIndividualManager().create(organizationId, studyFqn, new Individual().setId("Individual1"), new QueryOptions(), token); catalogManager.getIndividualManager().create(organizationId, studyFqn, new Individual().setId("Individual2"), new QueryOptions(), token); - catalogManager.getSampleManager().update(studyFqn, "s_1", new SampleUpdateParams().setIndividualId("Individual2"), + catalogManager.getSampleManager().update(organizationId, studyFqn, "s_1", new SampleUpdateParams().setIndividualId("Individual2"), QueryOptions.empty(), token); sampleDataResult = catalogManager.getSampleManager().search(organizationId, studyFqn, new Query(SampleDBAdaptor.QueryParams.INDIVIDUAL_ID.key(), "Individual2"), QueryOptions.empty(), token); @@ -2342,7 +2342,7 @@ public void updateIndividualFromSample() throws CatalogException { @Test public void getSharedProject() throws CatalogException, IOException { - catalogManager.getUserManager().create("dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, + catalogManager.getUserManager().create(organizationId, "dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, Account.AccountType.GUEST, opencgaToken); catalogManager.getStudyManager().updateGroup(organizationId, studyFqn, "@members", ParamUtils.BasicUpdateAction.ADD, new GroupUpdateParams(Collections.singletonList("dummy")), token); @@ -2367,7 +2367,7 @@ public void smartResolutorStudyAliasFromAnonymousUser() throws CatalogException @Test public void checkRegisteredUserPermissions() throws CatalogException { - catalogManager.getUserManager().create("dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, + catalogManager.getUserManager().create(organizationId, "dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, Account.AccountType.GUEST, opencgaToken); String token = catalogManager.getUserManager().login("dummy", TestParamConstants.PASSWORD).getToken(); @@ -2381,7 +2381,7 @@ public void checkRegisteredUserPermissions() throws CatalogException { @Test public void checkRegisteredUserPermissions2() throws CatalogException { - catalogManager.getUserManager().create("dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, + catalogManager.getUserManager().create(organizationId, "dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, Account.AccountType.GUEST, opencgaToken); String token = catalogManager.getUserManager().login("dummy", TestParamConstants.PASSWORD).getToken(); @@ -2430,7 +2430,7 @@ public void checkAnonymousUserPermissions2() throws CatalogException { assertTrue(catalogManager.getSampleManager().search(organizationId, studyFqn, new Query(), new QueryOptions(), "").getNumResults() > 0); assertTrue(catalogManager.getFileManager().search(organizationId, studyFqn, new Query(), new QueryOptions(), "").getNumResults() > 0); - catalogManager.getUserManager().create("dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, + catalogManager.getUserManager().create(organizationId, "dummy", "dummy", "asd@asd.asd", TestParamConstants.PASSWORD, "", 50000L, Account.AccountType.GUEST, opencgaToken); String token = catalogManager.getUserManager().login("dummy", TestParamConstants.PASSWORD).getToken(); studyResult = catalogManager.getStudyManager().get(organizationId, studyFqn, QueryOptions.empty(), token); @@ -2472,7 +2472,7 @@ public void testModifySampleBadIndividual() throws CatalogException { thrown.expect(CatalogException.class); thrown.expectMessage("not found"); - catalogManager.getSampleManager().update(studyFqn, sampleId1, new SampleUpdateParams().setIndividualId("ind"), null, token); + catalogManager.getSampleManager().update(organizationId, studyFqn, sampleId1, new SampleUpdateParams().setIndividualId("ind"), null, token); } @Test @@ -2509,7 +2509,7 @@ public void testAssignPermissions() throws CatalogException { Sample sample = new Sample().setId("sample"); catalogManager.getSampleManager().create(organizationId, studyFqn, sample, QueryOptions.empty(), token); - OpenCGAResult> dataResult = catalogManager.getSampleManager().updateAcl(studyFqn, + OpenCGAResult> dataResult = catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList("sample"), "user2", new SampleAclParams(null, null, null, null, "VIEW"), SET, token); assertEquals(1, dataResult.getNumResults()); assertEquals(1, dataResult.first().getAcl().size()); @@ -2541,7 +2541,7 @@ public void testAssignPermissionsByFamily() throws CatalogException { catalogManager.getFamilyManager().create(organizationId, studyFqn, family2, Collections.singletonList(individual2.getId()), QueryOptions.empty(), token); - OpenCGAResult> permissions = catalogManager.getSampleManager().getAcls(studyFqn, + OpenCGAResult> permissions = catalogManager.getSampleManager().getAcls(organizationId, studyFqn, Arrays.asList(sample.getId(), sample2.getId()), "user2", false, token); assertEquals(2, permissions.getNumResults()); for (AclEntryList result : permissions.getResults()) { @@ -2551,12 +2551,12 @@ public void testAssignPermissionsByFamily() throws CatalogException { } // Assign permissions to both families - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.emptyList(), "user2", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.emptyList(), "user2", new SampleAclParams() .setFamily(family.getId() + "," + family2.getId()) .setPermissions(SamplePermissions.VIEW.name()), ADD, token); - permissions = catalogManager.getSampleManager().getAcls(studyFqn, + permissions = catalogManager.getSampleManager().getAcls(organizationId, studyFqn, Arrays.asList(sample.getId(), sample2.getId()), "user2", false, token); assertEquals(2, permissions.getNumResults()); for (AclEntryList result : permissions.getResults()) { @@ -2582,7 +2582,7 @@ public void incrementVersionTest() throws CatalogException { assertEquals(1, dummySample1.getVersion()); assertEquals(1, dummySample2.getVersion()); - dummySample1 = catalogManager.getSampleManager().update(studyFqn, dummySample1.getId(), + dummySample1 = catalogManager.getSampleManager().update(organizationId, studyFqn, dummySample1.getId(), new SampleUpdateParams().setDescription("name"), options, token).first(); assertEquals(2, dummySample1.getVersion()); assertEquals("name", dummySample1.getDescription()); @@ -2642,7 +2642,7 @@ public void memberReferenceTest() throws CatalogException { assertEquals(2, family.getMembers().stream().map(Individual::getVersion).filter(v -> v == 2).count()); // Update sample1 - sample1 = catalogManager.getSampleManager().update(studyFqn, sample1.getId(), new SampleUpdateParams().setDescription("blabla"), + sample1 = catalogManager.getSampleManager().update(organizationId, studyFqn, sample1.getId(), new SampleUpdateParams().setDescription("blabla"), options, token).first(); individual1 = catalogManager.getIndividualManager().get(organizationId, studyFqn, individualId1, QueryOptions.empty(), token).first(); @@ -2702,7 +2702,7 @@ public void updateInUseInCATest() throws CatalogException { String sampleProbandId = case3.getProband().getSamples().get(0).getId(); // Update proband sample information - Sample sample = catalogManager.getSampleManager().update(studyFqn, sampleProbandId, + Sample sample = catalogManager.getSampleManager().update(organizationId, studyFqn, sampleProbandId, new SampleUpdateParams().setDescription("blabla"), options, token).first(); assertEquals(2, sample.getVersion()); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/StudyManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/StudyManagerTest.java index 884bef86394..1082c5ebda4 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/StudyManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/StudyManagerTest.java @@ -51,7 +51,7 @@ public class StudyManagerTest extends AbstractManagerTest { @Test public void testDefaultVariableSets() throws Exception { - String fqn = catalogManager.getStudyManager().create(project1, "newStudy", "newStudy", "newStudy", null, null, + String fqn = catalogManager.getStudyManager().create(organizationId, project1, "newStudy", "newStudy", "newStudy", null, null, null, null, null, new QueryOptions(), token).first().getFqn(); Study study = catalogManager.getStudyManager().get(organizationId, fqn, null, token).first(); @@ -120,7 +120,7 @@ public void testCreateDuplicatedVariableSets() throws Exception { @Test public void internalVariableSetTest() throws CatalogException { - Study study = catalogManager.getStudyManager().create(project1, "newStudy", "newStudy", "newStudy", null, null, + Study study = catalogManager.getStudyManager().create(organizationId, project1, "newStudy", "newStudy", "newStudy", null, null, null, null, null, new QueryOptions(), token).first(); Set variables = new HashSet<>(); @@ -148,7 +148,7 @@ public void internalVariableSetTest() throws CatalogException { @Test public void updateInternalRecessiveGene() throws CatalogException { - Study study = catalogManager.getStudyManager().create(project1, "newStudy", "newStudy", "newStudy", null, null, + Study study = catalogManager.getStudyManager().create(organizationId, project1, "newStudy", "newStudy", "newStudy", null, null, null, null, null, new QueryOptions(), token).first(); assertEquals(RecessiveGeneSummaryIndex.Status.NOT_INDEXED, study.getInternal().getIndex().getRecessiveGene().getStatus()); @@ -171,7 +171,7 @@ public void updateInternalRecessiveGene() throws CatalogException { @Test public void updateClinicalConfiguration() throws CatalogException { - Study study = catalogManager.getStudyManager().create(project1, "newStudy", "newStudy", "newStudy", null, null, + Study study = catalogManager.getStudyManager().create(organizationId, project1, "newStudy", "newStudy", "newStudy", null, null, null, null, null, new QueryOptions(), token).first(); assertNotNull(study.getInternal().getConfiguration()); assertNotNull(study.getInternal().getConfiguration().getClinical()); @@ -263,7 +263,7 @@ public void emptyGroupTest() throws CatalogException { Group first = catalogManager.getStudyManager().getGroup(organizationId, studyFqn, "@test", token).first(); assertNotNull(first.getUserIds()); - catalogManager.getUserManager().create("dummy", "dummy", "dummy@mail.com", TestParamConstants.PASSWORD, "", 0L, Account.AccountType.GUEST, opencgaToken); + catalogManager.getUserManager().create(organizationId, "dummy", "dummy", "dummy@mail.com", TestParamConstants.PASSWORD, "", 0L, Account.AccountType.GUEST, opencgaToken); catalogManager.getStudyManager().createGroup(organizationId, studyFqn, "@test2", Collections.singletonList("dummy"), token); catalogManager.getStudyManager().updateAcl(organizationId, studyFqn, "@test2", new StudyAclParams("", "view_only"), ParamUtils.AclAction.ADD, token); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/migration/MigrationManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/migration/MigrationManagerTest.java index 6c6ab31f8b5..d6cc7c6062e 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/migration/MigrationManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/migration/MigrationManagerTest.java @@ -148,22 +148,22 @@ public void testMigration() throws Exception { MigrationManager migrationManager = catalogManager.getMigrationManager(); String token = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - List> pendingMigrations = migrationManager.getPendingMigrations("0.0.1", token); + List> pendingMigrations = migrationManager.getPendingMigrations(organizationId, "0.0.1", token); assertEquals(0, pendingMigrations.size()); - pendingMigrations = migrationManager.getPendingMigrations("0.1.0", token); + pendingMigrations = migrationManager.getPendingMigrations(organizationId, "0.1.0", token); assertEquals(2, pendingMigrations.size()); for (Class pendingMigration : pendingMigrations) { Migration annotation = pendingMigration.getAnnotation(Migration.class); assertTrue(Arrays.asList("test-1", "test-2").contains(annotation.id())); } // Run migrations up to 0.0.1 - migrationManager.runMigration("0.0.1", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); + migrationManager.runMigration(organizationId, "0.0.1", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); - pendingMigrations = migrationManager.getPendingMigrations("0.1.0", token); + pendingMigrations = migrationManager.getPendingMigrations(organizationId, "0.1.0", token); assertEquals(0, pendingMigrations.size()); - pendingMigrations = migrationManager.getPendingMigrations("0.2.0", token); + pendingMigrations = migrationManager.getPendingMigrations(organizationId, "0.2.0", token); assertEquals(2, pendingMigrations.size()); for (int i = 0; i < pendingMigrations.size(); i++) { Class pendingMigration = pendingMigrations.get(i); @@ -171,7 +171,7 @@ public void testMigration() throws Exception { assertTrue(Arrays.asList("test2-1", "test2-2").contains(annotation.id())); } - pendingMigrations = migrationManager.getPendingMigrations("0.2.1", token); + pendingMigrations = migrationManager.getPendingMigrations(organizationId, "0.2.1", token); assertEquals(4, pendingMigrations.size()); for (int i = 0; i < pendingMigrations.size(); i++) { Class pendingMigration = pendingMigrations.get(i); @@ -191,9 +191,9 @@ public void testMigration() throws Exception { fail(); } } - migrationManager.runMigration("0.2.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); + migrationManager.runMigration(organizationId, "0.2.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); - pendingMigrations = migrationManager.getPendingMigrations("0.2.3", token); + pendingMigrations = migrationManager.getPendingMigrations(organizationId, "0.2.3", token); assertEquals(2, pendingMigrations.size()); for (int i = 0; i < pendingMigrations.size(); i++) { Class pendingMigration = pendingMigrations.get(i); @@ -212,17 +212,17 @@ public void testMigration() throws Exception { thrown.expectMessage("manual"); thrown.expect(MigrationException.class); - migrationManager.runMigration("0.2.2", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); + migrationManager.runMigration(organizationId, "0.2.2", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); } @Test public void testManualMigrations() throws CatalogException, IOException { String token = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - MigrationRun migrationRun = catalogManager.getMigrationManager().runManualMigration("0.2.1", "test4-1-manual", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "OtherValue"), token); + MigrationRun migrationRun = catalogManager.getMigrationManager().runManualMigration(organizationId, "0.2.1", "test4-1-manual", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "OtherValue"), token); assertEquals(MigrationRun.MigrationStatus.ERROR, migrationRun.getStatus()); - migrationRun = catalogManager.getMigrationManager().runManualMigration("0.2.1", "test4-1-manual", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); + migrationRun = catalogManager.getMigrationManager().runManualMigration(organizationId, "0.2.1", "test4-1-manual", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); assertEquals(MigrationRun.MigrationStatus.DONE, migrationRun.getStatus()); } @@ -230,19 +230,19 @@ public void testManualMigrations() throws CatalogException, IOException { public void testMigrationsWithJobs() throws CatalogException, IOException { String token = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getMigrationManager().runManualMigration("0.2.1", "test4-1-manual", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); + catalogManager.getMigrationManager().runManualMigration(organizationId, "0.2.1", "test4-1-manual", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); // RUN. New status ON_HOLD - catalogManager.getMigrationManager().runMigration("1.0.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); + catalogManager.getMigrationManager().runMigration(organizationId, "1.0.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); - MigrationRun migrationRun = catalogManager.getMigrationManager().getMigrationRuns(token).stream().filter(p1 -> p1.getKey().id().equals("test-with-jobs")).findFirst().get().getValue(); + MigrationRun migrationRun = catalogManager.getMigrationManager().getMigrationRuns(organizationId, token).stream().filter(p1 -> p1.getKey().id().equals("test-with-jobs")).findFirst().get().getValue(); assertEquals(MigrationRun.MigrationStatus.ON_HOLD, migrationRun.getStatus()); Date start = migrationRun.getStart(); JobReferenceParam j = migrationRun.getJobs().get(0); // RUN. Migration run does not get triggered - catalogManager.getMigrationManager().runMigration("1.0.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); - migrationRun = catalogManager.getMigrationManager().getMigrationRuns(token).stream().filter(p -> p.getKey().id().equals("test-with-jobs")).findFirst().get().getValue(); + catalogManager.getMigrationManager().runMigration(organizationId, "1.0.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); + migrationRun = catalogManager.getMigrationManager().getMigrationRuns(organizationId, token).stream().filter(p -> p.getKey().id().equals("test-with-jobs")).findFirst().get().getValue(); assertEquals(MigrationRun.MigrationStatus.ON_HOLD, migrationRun.getStatus()); assertEquals(start, migrationRun.getStart()); assertEquals(j, migrationRun.getJobs().get(0)); @@ -253,13 +253,13 @@ public void testMigrationsWithJobs() throws CatalogException, IOException { catalogManager.getJobManager().update(organizationId, job.getStudy().getId(), job.getId(), new ObjectMap(JobDBAdaptor.QueryParams.INTERNAL_STATUS.key(), status), new QueryOptions(), token); - migrationRun = catalogManager.getMigrationManager().getMigrationRuns(token) + migrationRun = catalogManager.getMigrationManager().getMigrationRuns(organizationId, token) .stream().filter(p -> p.getKey().id().equals("test-with-jobs")).findFirst().get().getValue(); assertEquals(MigrationRun.MigrationStatus.ERROR, migrationRun.getStatus()); // RUN. Migration run triggered. Status: ON_HOLD - catalogManager.getMigrationManager().runMigration("1.0.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); - migrationRun = catalogManager.getMigrationManager().getMigrationRuns(token) + catalogManager.getMigrationManager().runMigration(organizationId, "1.0.0", Collections.emptySet(), Collections.emptySet(), false, catalogManagerResource.getOpencgaHome().toString(), token); + migrationRun = catalogManager.getMigrationManager().getMigrationRuns(organizationId, token) .stream().filter(p -> p.getKey().id().equals("test-with-jobs")).findFirst().get().getValue(); assertEquals(MigrationRun.MigrationStatus.ON_HOLD, migrationRun.getStatus()); @@ -270,7 +270,7 @@ public void testMigrationsWithJobs() throws CatalogException, IOException { catalogManager.getJobManager().update(organizationId, job.getStudy().getId(), job.getId(), new ObjectMap(JobDBAdaptor.QueryParams.INTERNAL_STATUS.key(), status), new QueryOptions(), token); - migrationRun = catalogManager.getMigrationManager().getMigrationRuns(token) + migrationRun = catalogManager.getMigrationManager().getMigrationRuns(organizationId, token) .stream().filter(p -> p.getKey().id().equals("test-with-jobs")).findFirst().get().getValue(); assertEquals(MigrationRun.MigrationStatus.DONE, migrationRun.getStatus()); } @@ -282,13 +282,13 @@ public void testMigrationWithStorageReadOnly() throws Exception { try (OutputStream os = new FileOutputStream(catalogManagerResource.getOpencgaHome().resolve("conf").resolve("storage-configuration.yml").toFile())) { new StorageConfiguration().setMode(StorageConfiguration.Mode.READ_ONLY).serialize(os); } - MigrationRun migrationRun = catalogManager.getMigrationManager().runManualMigration("0.2.2", "test4-2", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); + MigrationRun migrationRun = catalogManager.getMigrationManager().runManualMigration(organizationId, "0.2.2", "test4-2", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); assertEquals(MigrationRun.MigrationStatus.PENDING, migrationRun.getStatus()); try (OutputStream os = new FileOutputStream(catalogManagerResource.getOpencgaHome().resolve("conf").resolve("storage-configuration.yml").toFile())) { new StorageConfiguration().setMode(StorageConfiguration.Mode.READ_WRITE).serialize(os); } - migrationRun = catalogManager.getMigrationManager().runManualMigration("0.2.2", "test4-2", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); + migrationRun = catalogManager.getMigrationManager().runManualMigration(organizationId, "0.2.2", "test4-2", catalogManagerResource.getOpencgaHome(), new ObjectMap("key", "value"), token); assertEquals(MigrationRun.MigrationStatus.DONE, migrationRun.getStatus()); } diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/stats/solr/AbstractSolrManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/stats/solr/AbstractSolrManagerTest.java index 18dd32470cb..530199133e8 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/stats/solr/AbstractSolrManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/stats/solr/AbstractSolrManagerTest.java @@ -84,11 +84,11 @@ public void after() throws CatalogException { public void setUpCatalogManager(CatalogManager catalogManager) throws IOException, CatalogException { - catalogManager.getUserManager().create("owner", "Owner", "owner@mail.com", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, null); - catalogManager.getUserManager().create("admin1", "Admin", "admin@mail.com", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, null); - catalogManager.getUserManager().create("user1", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, null); - catalogManager.getUserManager().create("user2", "User2 Name", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, null); - catalogManager.getUserManager().create("user3", "User3 Name", "user.2@e.mail", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.GUEST, null); + catalogManager.getUserManager().create(organizationId, "owner", "Owner", "owner@mail.com", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, null); + catalogManager.getUserManager().create(organizationId, "admin1", "Admin", "admin@mail.com", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, null); + catalogManager.getUserManager().create(organizationId, "user1", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, null); + catalogManager.getUserManager().create(organizationId, "user2", "User2 Name", "mail2@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.GUEST, null); + catalogManager.getUserManager().create(organizationId, "user3", "User3 Name", "user.2@e.mail", TestParamConstants.PASSWORD, "ACME", null, Account.AccountType.GUEST, null); sessionIdOwner = catalogManager.getUserManager().login("owner", TestParamConstants.PASSWORD).getToken(); sessionIdAdmin = catalogManager.getUserManager().login("admin1", TestParamConstants.PASSWORD).getToken(); @@ -96,9 +96,9 @@ public void setUpCatalogManager(CatalogManager catalogManager) throws IOExceptio sessionIdUser2 = catalogManager.getUserManager().login("user2", TestParamConstants.PASSWORD).getToken(); sessionIdUser3 = catalogManager.getUserManager().login("user3", TestParamConstants.PASSWORD).getToken(); - Project project = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + Project project = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdOwner).first(); - studyFqn = catalogManager.getStudyManager().create(project.getFqn(), "phase1", null, "Phase 1", "Done", null, + studyFqn = catalogManager.getStudyManager().create(organizationId, project.getFqn(), "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, sessionIdOwner).first().getFqn(); catalogManager.getStudyManager().updateGroup(organizationId, studyFqn, "@admins", ParamUtils.BasicUpdateAction.ADD, @@ -119,9 +119,9 @@ public void setUpCatalogManager(CatalogManager catalogManager) throws IOExceptio Sample sample3 = catalogManager.getSampleManager().create(organizationId, studyFqn, new Sample().setId("sample3"), INCLUDE_RESULT, sessionIdAdmin).first(); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList("sample1"), "@study_deny,user3", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList("sample1"), "@study_deny,user3", new SampleAclParams(null, null, null, null, "VIEW,VIEW_ANNOTATIONS"), ParamUtils.AclAction.ADD, sessionIdAdmin); - catalogManager.getSampleManager().updateAcl(studyFqn, Collections.singletonList("sample2"), "@study_allow", + catalogManager.getSampleManager().updateAcl(organizationId, studyFqn, Collections.singletonList("sample2"), "@study_allow", new SampleAclParams(null, null, null, null, ""), ParamUtils.AclAction.SET, sessionIdAdmin); // Cohorts diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogFileUtilsTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogFileUtilsTest.java index ec72af01983..cf129b7abd6 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogFileUtilsTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogFileUtilsTest.java @@ -80,12 +80,12 @@ public void before() throws CatalogException, IOException, URISyntaxException { String opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); //Create USER - catalogManager.getUserManager().create("user", "name", "mi@mail.com", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "name", "mi@mail.com", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); userSessionId = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); // adminSessionId = catalogManager.login("admin", "admin", "--").getResults().get(0).getString("sessionId"); - String projectId = catalogManager.getProjectManager().create("proj", "proj", "", "Homo sapiens", + String projectId = catalogManager.getProjectManager().create(organizationId, "proj", "proj", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, userSessionId).getResults().get(0).getId(); - Study study = catalogManager.getStudyManager().create(projectId, "std", "std", "std", "", null, null, null, null, INCLUDE_RESULT, + Study study = catalogManager.getStudyManager().create(organizationId, projectId, "std", "std", "std", "", null, null, null, null, INCLUDE_RESULT, userSessionId).getResults().get(0); studyUid = study.getUid(); studyFqn = study.getFqn(); @@ -107,7 +107,7 @@ public void checkFileTest() throws CatalogException, IOException { .setDescription("file at root") .setContent(RandomStringUtils.randomAlphanumeric(100)), true, userSessionId).first(); - returnedFile = catalogFileUtils.checkFile(studyFqn, file, true, userSessionId); + returnedFile = catalogFileUtils.checkFile(organizationId, studyFqn, file, true, userSessionId); assertSame("Should not modify the status, so should return the same file.", file, returnedFile); assertEquals(InternalStatus.READY, file.getInternal().getStatus().getId()); @@ -123,14 +123,14 @@ public void checkFileTest() throws CatalogException, IOException { /** Check READY and missing file **/ assertTrue(new java.io.File(file.getUri()).delete()); - returnedFile = catalogFileUtils.checkFile(studyFqn, file, true, userSessionId); + returnedFile = catalogFileUtils.checkFile(organizationId, studyFqn, file, true, userSessionId); assertNotSame(file, returnedFile); assertEquals(FileStatus.MISSING, returnedFile.getInternal().getStatus().getId()); /** Check MISSING file still missing **/ file = catalogManager.getFileManager().get(organizationId, studyFqn, file.getPath(), null, userSessionId).first(); - returnedFile = catalogFileUtils.checkFile(studyFqn, file, true, userSessionId); + returnedFile = catalogFileUtils.checkFile(organizationId, studyFqn, file, true, userSessionId); assertEquals("Should not modify the still MISSING file, so should return the same file.", file.getInternal().getStatus().getId(), returnedFile.getInternal().getStatus().getId()); @@ -141,7 +141,7 @@ public void checkFileTest() throws CatalogException, IOException { os.write(RandomStringUtils.randomAlphanumeric(1000).getBytes()); os.write('\n'); os.close(); - returnedFile = catalogFileUtils.checkFile(studyFqn, file, true, userSessionId); + returnedFile = catalogFileUtils.checkFile(organizationId, studyFqn, file, true, userSessionId); assertNotSame(file, returnedFile); assertEquals(FileStatus.READY, returnedFile.getInternal().getStatus().getId()); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoaderTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoaderTest.java index e2d6cda9e70..5ec805833b8 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoaderTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/CatalogSampleAnnotationsLoaderTest.java @@ -78,11 +78,11 @@ public void setUpCatalogManager(CatalogManager catalogManager) throws IOExceptio pedigree = loader.readPedigree(pedFileURL.getPath()); userId = "user1"; - catalogManager.getUserManager().create(userId, userId, "asdasd@asd.asd", TestParamConstants.PASSWORD, "", -1L, Account.AccountType.FULL, catalogManagerResource.getAdminToken()); + catalogManager.getUserManager().create(organizationId, userId, userId, "asdasd@asd.asd", TestParamConstants.PASSWORD, "", -1L, Account.AccountType.FULL, catalogManagerResource.getAdminToken()); sessionId = catalogManager.getUserManager().login(userId, TestParamConstants.PASSWORD).getToken(); - Project project = catalogManager.getProjectManager().create("def", "default", "", "Homo sapiens", + Project project = catalogManager.getProjectManager().create(organizationId, "def", "default", "", "Homo sapiens", null, "GRCh38", new QueryOptions(ParamConstants.INCLUDE_RESULT_PARAM, true), sessionId).getResults().get(0); - Study study = catalogManager.getStudyManager().create(project.getFqn(), "def", null, "default", "", null, null, null, null, + Study study = catalogManager.getStudyManager().create(organizationId, project.getFqn(), "def", null, "default", "", null, null, null, null, new QueryOptions(ParamConstants.INCLUDE_RESULT_PARAM, true), sessionId).getResults().get(0); studyId = study.getFqn(); pedFile = catalogManager.getFileManager().upload(organizationId, studyId, new FileInputStream(new java.io.File(pedFileURL.toURI())), @@ -121,7 +121,7 @@ public void testLoadPedigree_GivenVariableSet() throws Exception { @Test public void testLoadPedigreeCatalog() throws Exception { - DataResult sampleDataResult = loader.loadSampleAnnotations(pedFile, null, sessionId); + DataResult sampleDataResult = loader.loadSampleAnnotations(organizationId, pedFile, null, sessionId); String variableSetId = sampleDataResult.getResults().get(0).getAnnotationSets().get(0).getVariableSetId(); Query query = new Query(Constants.ANNOTATION, variableSetId + ":family=GB84"); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileMetadataReaderTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileMetadataReaderTest.java index b4b55b6a8c5..993dd4ef54b 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileMetadataReaderTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileMetadataReaderTest.java @@ -77,11 +77,11 @@ public void setUp() throws IOException, CatalogException, URISyntaxException { String opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); - project = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + project = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first(); - study = catalogManager.getStudyManager().create(project.getId(), "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first(); + study = catalogManager.getStudyManager().create(organizationId, project.getId(), "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first(); folder = catalogManager.getFileManager().createFolder(organizationId, study.getId(), Paths.get("data/vcf/").toString(), true, null, QueryOptions.empty(), sessionIdUser).first(); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileScannerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileScannerTest.java index 223e7966dff..bdc052fd629 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileScannerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/catalog/utils/FileScannerTest.java @@ -77,11 +77,11 @@ public void setUp() throws IOException, CatalogException { String opencgaToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create("user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); + catalogManager.getUserManager().create(organizationId, "user", "User Name", "mail@ebi.ac.uk", TestParamConstants.PASSWORD, "", null, Account.AccountType.FULL, opencgaToken); sessionIdUser = catalogManager.getUserManager().login("user", TestParamConstants.PASSWORD).getToken(); - project = catalogManager.getProjectManager().create("1000G", "Project about some genomes", "", "Homo sapiens", + project = catalogManager.getProjectManager().create(organizationId, "1000G", "Project about some genomes", "", "Homo sapiens", null, "GRCh38", INCLUDE_RESULT, sessionIdUser).first(); - study = catalogManager.getStudyManager().create(project.getId(), "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first(); + study = catalogManager.getStudyManager().create(organizationId, project.getId(), "phase1", null, "Phase 1", "Done", null, null, null, null, INCLUDE_RESULT, sessionIdUser).first(); folder = catalogManager.getFileManager().createFolder(organizationId, study.getId(), Paths.get("data/test/folder/").toString(), true, null, QueryOptions.empty(), sessionIdUser).first(); @@ -108,7 +108,7 @@ public void testScan() throws IOException, CatalogException { CatalogManagerTest.createDebugFile(directory.resolve("subfolder/subsubfolder/file3.txt").toString()); FileScanner fileScanner = new FileScanner(catalogManager); - List files = fileScanner.scan(folder, directory.toUri(), FileScanner.FileScannerPolicy.DELETE, true, true, sessionIdUser); + List files = fileScanner.scan(organizationId, folder, directory.toUri(), FileScanner.FileScannerPolicy.DELETE, true, true, sessionIdUser); assertEquals(9, files.size()); files.forEach((File file) -> assertTrue(StringUtils.isNotEmpty(file.getChecksum()))); @@ -125,7 +125,7 @@ public void testDeleteExisting() throws IOException, CatalogException { File file = queryResult.first(); CatalogManagerTest.createDebugFile(directory.resolve("file1.txt").toString()); - List files = new FileScanner(catalogManager).scan(folder, directory.toUri(), FileScanner.FileScannerPolicy.DELETE, false, + List files = new FileScanner(catalogManager).scan(organizationId, folder, directory.toUri(), FileScanner.FileScannerPolicy.DELETE, false, true, sessionIdUser); files.forEach((File f) -> assertFalse(f.getAttributes().containsKey("checksum"))); @@ -158,7 +158,7 @@ public void testReplaceExisting() throws IOException, CatalogException { CatalogManagerTest.createDebugFile(directory.resolve("s/file2.txt").toString()); FileScanner fileScanner = new FileScanner(catalogManager); - fileScanner.scan(folder, directory.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); + fileScanner.scan(organizationId, folder, directory.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); File replacedFile = catalogManager.getFileManager().get(organizationId, study.getFqn(), file.getPath(), null, sessionIdUser).first(); assertEquals(FileStatus.READY, replacedFile.getInternal().getStatus().getId()); @@ -185,7 +185,7 @@ public void testRegisterFiles() throws IOException, CatalogException { FileScanner fileScanner = new FileScanner(catalogManager); // List files = fileScanner.registerFiles(this.folder, filePaths, FileScanner.FileScannerPolicy.DELETE, true, false, sessionIdUser); Predicate uriPredicate = uri -> uri.getPath().endsWith("file1.txt") || uri.getPath().endsWith("file2.txt"); - List files = fileScanner.scan(this.folder, directory.toUri(), FileScanner.FileScannerPolicy.DELETE, true, false, uriPredicate, sessionIdUser); + List files = fileScanner.scan(organizationId, this.folder, directory.toUri(), FileScanner.FileScannerPolicy.DELETE, true, false, uriPredicate, sessionIdUser); assertEquals(2, files.size()); for (File file : files) { @@ -204,13 +204,13 @@ public void testScanStudyURI() throws IOException, CatalogException { CatalogManagerTest.createDebugFile(directory.resolve("file1.txt").toString()); FileScanner fileScanner = new FileScanner(catalogManager); - List files = fileScanner.scan(folder, directory.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); + List files = fileScanner.scan(organizationId, folder, directory.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); assertEquals(1, files.size()); Path studyUriPath = Paths.get(study.getUri()); CatalogManagerTest.createDebugFile(studyUriPath.resolve("data/test/folder/").resolve("file2.txt").toString()); File root = catalogManager.getFileManager().search(organizationId, study.getFqn(), new Query("name", "."), null, sessionIdUser).first(); - files = fileScanner.scan(root, studyUriPath.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); + files = fileScanner.scan(organizationId, root, studyUriPath.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); assertEquals(1, files.size()); files.forEach((f) -> assertTrue(f.getSize() > 0)); @@ -225,7 +225,7 @@ public void testResyncStudy() throws IOException, CatalogException { //ReSync study folder. Will detect any difference. FileScanner fileScanner = new FileScanner(catalogManager); List files; - files = fileScanner.reSync(study, true, sessionIdUser); + files = fileScanner.reSync(organizationId, study, true, sessionIdUser); assertEquals(0, files.size()); //Add one extra file. ReSync study folder. @@ -234,7 +234,7 @@ public void testResyncStudy() throws IOException, CatalogException { catalogManager.getIoManagerFactory().getDefault().createDirectory(studyUriPath.resolve("data/test/folder/").toUri(), true); Path filePath = CatalogManagerTest .createDebugFile(studyUriPath.resolve("data/test/folder/").resolve("file_scanner_test_file.txt").toString()).toPath(); - files = fileScanner.reSync(study, true, sessionIdUser); + files = fileScanner.reSync(organizationId, study, true, sessionIdUser); assertEquals(1, files.size()); File file = files.get(0); @@ -244,7 +244,7 @@ public void testResyncStudy() throws IOException, CatalogException { //Delete file. CheckStudyFiles. Will detect one File.Status.MISSING file Files.delete(filePath); - files = fileScanner.checkStudyFiles(study, true, sessionIdUser); + files = fileScanner.checkStudyFiles(organizationId, study, true, sessionIdUser); assertEquals(1, files.size()); assertEquals(FileStatus.MISSING, files.get(0).getInternal().getStatus().getId()); @@ -252,7 +252,7 @@ public void testResyncStudy() throws IOException, CatalogException { //Restore file. CheckStudyFiles. Will detect one re-tracked file. Checksum must be different. CatalogManagerTest.createDebugFile(filePath.toString()); - files = fileScanner.checkStudyFiles(study, true, sessionIdUser); + files = fileScanner.checkStudyFiles(organizationId, study, true, sessionIdUser); assertEquals(1, files.size()); assertEquals(FileStatus.READY, files.get(0).getInternal().getStatus().getId()); @@ -261,7 +261,7 @@ public void testResyncStudy() throws IOException, CatalogException { //Delete file. ReSync. Will detect one File.Status.MISSING file (like checkFile) Files.delete(filePath); - files = fileScanner.reSync(study, true, sessionIdUser); + files = fileScanner.reSync(organizationId, study, true, sessionIdUser); assertEquals(1, files.size()); assertEquals(FileStatus.MISSING, files.get(0).getInternal().getStatus().getId()); @@ -269,7 +269,7 @@ public void testResyncStudy() throws IOException, CatalogException { //Restore file. CheckStudyFiles. Will detect one found file. Checksum must be different. CatalogManagerTest.createDebugFile(filePath.toString()); - files = fileScanner.reSync(study, true, sessionIdUser); + files = fileScanner.reSync(organizationId, study, true, sessionIdUser); assertEquals(1, files.size()); assertEquals(FileStatus.READY, files.get(0).getInternal().getStatus().getId()); @@ -292,7 +292,7 @@ public void testComplexAdd() throws IOException, CatalogException, URISyntaxExce CatalogManagerTest.createDebugFile(directory.resolve("file2.sam.gz").toString()); FileScanner fileScanner = new FileScanner(catalogManager); - List files = fileScanner.scan(folder, directory.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); + List files = fileScanner.scan(organizationId, folder, directory.toUri(), FileScanner.FileScannerPolicy.REPLACE, true, true, sessionIdUser); Map map = files.stream().collect(Collectors.toMap(File::getName, (f) -> f)); diff --git a/opencga-catalog/src/test/java/org/opencb/opencga/templates/TemplateManagerTest.java b/opencga-catalog/src/test/java/org/opencb/opencga/templates/TemplateManagerTest.java index 165cae66267..34aeecedc88 100644 --- a/opencga-catalog/src/test/java/org/opencb/opencga/templates/TemplateManagerTest.java +++ b/opencga-catalog/src/test/java/org/opencb/opencga/templates/TemplateManagerTest.java @@ -42,14 +42,14 @@ public void test() throws Exception { CatalogManager catalogManager = catalogManagerResource.getCatalogManager(); String adminToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create(new User().setId("user1").setName("User 1").setAccount(new Account().setType(Account.AccountType.FULL)), + catalogManager.getUserManager().create(organizationId, new User().setId("user1").setName("User 1").setAccount(new Account().setType(Account.AccountType.FULL)), TestParamConstants.PASSWORD, adminToken); - catalogManager.getUserManager().create(new User().setId("user2").setName("User 2").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); - catalogManager.getUserManager().create(new User().setId("user3").setName("User 3").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); - catalogManager.getUserManager().create(new User().setId("user4").setName("User 4").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); + catalogManager.getUserManager().create(organizationId, new User().setId("user2").setName("User 2").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); + catalogManager.getUserManager().create(organizationId, new User().setId("user3").setName("User 3").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); + catalogManager.getUserManager().create(organizationId, new User().setId("user4").setName("User 4").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); String token = catalogManager.getUserManager().login("user1", TestParamConstants.PASSWORD).getToken(); - catalogManager.getProjectManager().create("project", "Project", "", "hsapiens", "common", "GRCh38", QueryOptions.empty(), token); + catalogManager.getProjectManager().create(organizationId, "project", "Project", "", "hsapiens", "common", "GRCh38", QueryOptions.empty(), token); catalogManager.getStudyManager().create(organizationId, "project", new Study().setId("study"), QueryOptions.empty(), token); URI resource = catalogManagerResource.getResourceUri("templates/manifest.yml"); @@ -73,14 +73,14 @@ public void test_yaml() throws Exception { CatalogManager catalogManager = catalogManagerResource.getCatalogManager(); String adminToken = catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - catalogManager.getUserManager().create(new User().setId("user1").setName("User 1").setAccount(new Account().setType(Account.AccountType.FULL)), + catalogManager.getUserManager().create(organizationId, new User().setId("user1").setName("User 1").setAccount(new Account().setType(Account.AccountType.FULL)), TestParamConstants.PASSWORD, adminToken); - catalogManager.getUserManager().create(new User().setId("user2").setName("User 2").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); - catalogManager.getUserManager().create(new User().setId("user3").setName("User 3").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); - catalogManager.getUserManager().create(new User().setId("user4").setName("User 4").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); + catalogManager.getUserManager().create(organizationId, new User().setId("user2").setName("User 2").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); + catalogManager.getUserManager().create(organizationId, new User().setId("user3").setName("User 3").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); + catalogManager.getUserManager().create(organizationId, new User().setId("user4").setName("User 4").setAccount(new Account().setType(Account.AccountType.GUEST)), TestParamConstants.PASSWORD, adminToken); String token = catalogManager.getUserManager().login("user1", TestParamConstants.PASSWORD).getToken(); - catalogManager.getProjectManager().create("project", "Project", "", "hsapiens", "common", "GRCh38", QueryOptions.empty(), token); + catalogManager.getProjectManager().create(organizationId, "project", "Project", "", "hsapiens", "common", "GRCh38", QueryOptions.empty(), token); catalogManager.getStudyManager().create(organizationId, "project", new Study().setId("study"), QueryOptions.empty(), token); URI resource = catalogManagerResource.getResourceUri("templates_yaml/manifest.yml"); diff --git a/opencga-client/src/test/java/org/opencb/opencga/client/rest/WorkEnvironmentTest.java b/opencga-client/src/test/java/org/opencb/opencga/client/rest/WorkEnvironmentTest.java index ea2124d51cb..b9604bb46af 100644 --- a/opencga-client/src/test/java/org/opencb/opencga/client/rest/WorkEnvironmentTest.java +++ b/opencga-client/src/test/java/org/opencb/opencga/client/rest/WorkEnvironmentTest.java @@ -42,6 +42,7 @@ @Category(ShortTests.class) public class WorkEnvironmentTest extends ExternalResource { + protected String organizationId = "test"; protected OpenCGAClient openCGAClient; protected Path opencgaHome; protected CatalogManager catalogManager; @@ -90,7 +91,7 @@ private void isolateOpenCGA() throws Exception { catalogManager = new CatalogManager(configuration); - CatalogDemo.createDemoDatabase(catalogManager, TestParamConstants.ADMIN_PASSWORD, true); + CatalogDemo.createDemoDatabase(catalogManager, organizationId, TestParamConstants.ADMIN_PASSWORD, true); restServer = new RestServer(opencgaHome); restServer.start(); diff --git a/opencga-master/src/main/java/org/opencb/opencga/master/monitor/MonitorService.java b/opencga-master/src/main/java/org/opencb/opencga/master/monitor/MonitorService.java index 5b63b01078a..4070f53aba1 100644 --- a/opencga-master/src/main/java/org/opencb/opencga/master/monitor/MonitorService.java +++ b/opencga-master/src/main/java/org/opencb/opencga/master/monitor/MonitorService.java @@ -95,7 +95,7 @@ private void init(String token) throws CatalogException { logger = LoggerFactory.getLogger(this.getClass()); this.catalogManager = new CatalogManager(this.configuration); - String nonExpiringToken = this.catalogManager.getUserManager().getNonExpiringToken(OPENCGA, Collections.emptyMap(), token); + String nonExpiringToken = this.catalogManager.getUserManager().getNonExpiringToken(organizationId, OPENCGA, Collections.emptyMap(), token); executionDaemon = new ExecutionDaemon( configuration.getMonitor().getExecutionDaemonInterval(), diff --git a/opencga-master/src/main/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemon.java b/opencga-master/src/main/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemon.java index 854f347f73d..ee68c254566 100644 --- a/opencga-master/src/main/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemon.java +++ b/opencga-master/src/main/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemon.java @@ -518,7 +518,7 @@ protected int checkPendingJob(Job job) { String userToken; try { - userToken = catalogManager.getUserManager().getNonExpiringToken(job.getUserId(), Collections.emptyMap(), token); + userToken = catalogManager.getUserManager().getNonExpiringToken(organizationId, job.getUserId(), Collections.emptyMap(), token); } catch (CatalogException e) { return abortJob(job, "Internal error. Could not obtain token for user '" + job.getUserId() + "'", e); } diff --git a/opencga-master/src/test/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemonTest.java b/opencga-master/src/test/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemonTest.java index 80acd8a7525..8a4b8763023 100644 --- a/opencga-master/src/test/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemonTest.java +++ b/opencga-master/src/test/java/org/opencb/opencga/master/monitor/daemons/ExecutionDaemonTest.java @@ -77,7 +77,7 @@ public void setUp() throws Exception { super.setUp(); String expiringToken = this.catalogManager.getUserManager().loginAsAdmin(TestParamConstants.ADMIN_PASSWORD).getToken(); - String nonExpiringToken = this.catalogManager.getUserManager().getNonExpiringToken("opencga", Collections.emptyMap(), expiringToken); + String nonExpiringToken = this.catalogManager.getUserManager().getNonExpiringToken(organizationId, "opencga", Collections.emptyMap(), expiringToken); catalogManager.getConfiguration().getAnalysis().getExecution().getMaxConcurrentJobs().put(VariantIndexOperationTool.ID, 1); daemon = new ExecutionDaemon(1000, nonExpiringToken, catalogManager, diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/CohortWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/CohortWSServer.java index abfcad7b85f..08d9db1cfd9 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/CohortWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/CohortWSServer.java @@ -315,7 +315,7 @@ public Response loadTsvAnnotations( .append("parents", parents) .append("annotationSetId", annotationSetId); - return createOkResponse(catalogManager.getCohortManager().loadTsvAnnotations(studyStr, variableSetId, path, params, + return createOkResponse(catalogManager.getCohortManager().loadTsvAnnotations(organizationId, studyStr, variableSetId, path, params, additionalParams, CohortTsvAnnotationLoader.ID, token)); } catch (Exception e) { return createErrorResponse(e); diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/FamilyWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/FamilyWSServer.java index 76a165693b3..5817853b92e 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/FamilyWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/FamilyWSServer.java @@ -269,7 +269,7 @@ public Response loadTsvAnnotations( .append("parents", parents) .append("annotationSetId", annotationSetId); - return createOkResponse(catalogManager.getFamilyManager().loadTsvAnnotations(studyStr, variableSetId, path, params, + return createOkResponse(catalogManager.getFamilyManager().loadTsvAnnotations(organizationId, studyStr, variableSetId, path, params, additionalParams, FamilyTsvAnnotationLoader.ID, token)); } catch (Exception e) { return createErrorResponse(e); diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/FileWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/FileWSServer.java index 350d4b8b0db..7ba012440c1 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/FileWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/FileWSServer.java @@ -597,7 +597,7 @@ public Response loadTsvAnnotations( .append("parents", parents) .append("annotationSetId", annotationSetId); - return createOkResponse(catalogManager.getFileManager().loadTsvAnnotations(studyStr, variableSetId, path, params, + return createOkResponse(catalogManager.getFileManager().loadTsvAnnotations(organizationId, studyStr, variableSetId, path, params, additionalParams, FileTsvAnnotationLoader.ID, token)); } catch (Exception e) { return createErrorResponse(e); @@ -852,8 +852,8 @@ public Response refresh( FileUtils catalogFileUtils = new FileUtils(catalogManager); FileMetadataReader fileMetadataReader = FileMetadataReader.get(catalogManager); if (file.getType() == File.Type.FILE) { - File file1 = catalogFileUtils.checkFile(studyStr, file, false, token); - file1 = fileMetadataReader.updateMetadataInformation(studyStr, file1, token); + File file1 = catalogFileUtils.checkFile(organizationId, studyStr, file, false, token); + file1 = fileMetadataReader.updateMetadataInformation(organizationId, studyStr, file1, token); if (file == file1) { //If the file is the same, it was not modified. Only return modified files. files = Collections.emptyList(); } else { @@ -863,7 +863,7 @@ public Response refresh( List result = catalogManager.getFileManager().getFilesFromFolder(organizationId, studyStr, fileIdStr, null, token).getResults(); files = new ArrayList<>(result.size()); for (File f : result) { - File file1 = fileMetadataReader.updateMetadataInformation(studyStr, f, token); + File file1 = fileMetadataReader.updateMetadataInformation(organizationId, studyStr, f, token); if (f != file1) { //Add only modified files. files.add(file1); } diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/IndividualWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/IndividualWSServer.java index b5955f9a411..4645d5e6ba1 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/IndividualWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/IndividualWSServer.java @@ -350,7 +350,7 @@ public Response loadTsvAnnotations( .append("parents", parents) .append("annotationSetId", annotationSetId); - return createOkResponse(catalogManager.getIndividualManager().loadTsvAnnotations(studyStr, variableSetId, path, params, + return createOkResponse(catalogManager.getIndividualManager().loadTsvAnnotations(organizationId, studyStr, variableSetId, path, params, additionalParams, IndividualTsvAnnotationLoader.ID, token)); } catch (Exception e) { return createErrorResponse(e); diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/OpenCGAWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/OpenCGAWSServer.java index 83ce03b4b6d..8016ea995fb 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/OpenCGAWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/OpenCGAWSServer.java @@ -295,7 +295,7 @@ private static void initOpenCGAObjects() { storageEngineFactory = StorageEngineFactory.get(storageConfiguration); variantManager = new VariantStorageManager(catalogManager, storageEngineFactory); - MigrationSummary migrationSummary = catalogManager.getMigrationManager().getMigrationSummary(); + MigrationSummary migrationSummary = catalogManager.getMigrationManager().getMigrationSummary(organizationId); if (migrationSummary.getMigrationsToBeApplied() > 0) { logger.info("| * Pending migrations: {}", migrationSummary.getMigrationsToBeApplied()); for (Map.Entry entry : migrationSummary.getStatusCount().entrySet()) { @@ -857,7 +857,7 @@ public Response submitJob(String toolId, String study, ToolParams bodyParams, St public Response submitJobAdmin(String toolId, ToolParams bodyParams, String jobId, String jobDescription, String jobDependsOnStr, String jobTagsStr) { return run(() -> { - if (!catalogManager.getUserManager().getUserId(token).equals(ParamConstants.OPENCGA_USER_ID)) { + if (!catalogManager.getUserManager().getUserId(organizationId, token).equals(ParamConstants.OPENCGA_USER_ID)) { throw new CatalogAuthenticationException("Only user '" + ParamConstants.OPENCGA_USER_ID + "' can run this operation!"); } return submitJobRaw(toolId, null, ADMIN_STUDY_FQN, bodyParams, jobId, jobDescription, jobDependsOnStr, jobTagsStr); diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/PanelWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/PanelWSServer.java index eab640e9b26..b1d188c2217 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/PanelWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/PanelWSServer.java @@ -132,7 +132,7 @@ public Response updatePanel( @ApiParam(value = ParamConstants.INCLUDE_RESULT_DESCRIPTION, defaultValue = "false") @QueryParam(ParamConstants.INCLUDE_RESULT_PARAM) boolean includeResult, @ApiParam(name = "body", value = "Panel parameters") PanelUpdateParams panelParams) { try { - return createOkResponse(panelManager.update(studyStr, getIdList(panels), panelParams, true, queryOptions, token)); + return createOkResponse(panelManager.update(organizationId, studyStr, getIdList(panels), panelParams, true, queryOptions, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -245,7 +245,7 @@ public Response deleteList( @ApiParam(value = ParamConstants.STUDY_DESCRIPTION) @QueryParam(ParamConstants.STUDY_PARAM) String studyStr, @ApiParam(value = "Comma separated list of panel ids") @PathParam("panels") String panels) { try { - return createOkResponse(panelManager.delete(studyStr, getIdList(panels), queryOptions, true, token)); + return createOkResponse(panelManager.delete(organizationId, studyStr, getIdList(panels), queryOptions, true, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -264,7 +264,7 @@ public Response getAcls( @QueryParam(Constants.SILENT) boolean silent) { try { List idList = getIdList(sampleIdsStr); - return createOkResponse(panelManager.getAcls(studyStr, idList, member, silent, token)); + return createOkResponse(panelManager.getAcls(organizationId, studyStr, idList, member, silent, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -282,7 +282,7 @@ public Response updateAcl( params = ObjectUtils.defaultIfNull(params, new PanelAclUpdateParams()); AclParams panelAclParams = new AclParams(params.getPermissions()); List idList = getIdList(params.getPanel(), false); - return createOkResponse(panelManager.updateAcl(studyStr, idList, memberId, panelAclParams, action, token)); + return createOkResponse(panelManager.updateAcl(organizationId, studyStr, idList, memberId, panelAclParams, action, token)); } catch (Exception e) { return createErrorResponse(e); } diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/SampleWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/SampleWSServer.java index 9202b22a048..6e1ec5d5f98 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/SampleWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/SampleWSServer.java @@ -123,7 +123,7 @@ public Response loadSamples( try { File pedigreeFile = catalogManager.getFileManager().get(organizationId, studyStr, fileStr, null, token).first(); CatalogSampleAnnotationsLoader loader = new CatalogSampleAnnotationsLoader(catalogManager); - DataResult sampleQueryResult = loader.loadSampleAnnotations(pedigreeFile, variableSet, token); + DataResult sampleQueryResult = loader.loadSampleAnnotations(organizationId, pedigreeFile, variableSet, token); return createOkResponse(sampleQueryResult); } catch (Exception e) { return createErrorResponse(e); @@ -326,7 +326,7 @@ public Response updateByPost( actionMap.put(SampleDBAdaptor.QueryParams.PHENOTYPES.key(), phenotypesAction); queryOptions.put(Constants.ACTIONS, actionMap); - return createOkResponse(sampleManager.update(studyStr, getIdList(sampleStr), parameters, true, queryOptions, token), "Sample update success"); + return createOkResponse(sampleManager.update(organizationId, studyStr, getIdList(sampleStr), parameters, true, queryOptions, token), "Sample update success"); } catch (Exception e) { return createErrorResponse(e); } @@ -351,7 +351,7 @@ public Response loadTsvAnnotations( .append("parents", parents) .append("annotationSetId", annotationSetId); - return createOkResponse(catalogManager.getSampleManager().loadTsvAnnotations(studyStr, variableSetId, path, params, + return createOkResponse(catalogManager.getSampleManager().loadTsvAnnotations(organizationId, studyStr, variableSetId, path, params, additionalParams, SampleTsvAnnotationLoader.ID, token)); } catch (Exception e) { return createErrorResponse(e); @@ -374,7 +374,7 @@ public Response updateAnnotations( if (action == null) { action = ParamUtils.CompleteUpdateAction.ADD; } - return createOkResponse(catalogManager.getSampleManager().updateAnnotations(studyStr, sampleStr, annotationSetId, + return createOkResponse(catalogManager.getSampleManager().updateAnnotations(organizationId, studyStr, sampleStr, annotationSetId, updateParams, action, queryOptions, token)); } catch (Exception e) { return createErrorResponse(e); @@ -399,7 +399,7 @@ public Response delete( queryOptions.put(Constants.EMPTY_FILES_ACTION, query.getString(Constants.EMPTY_FILES_ACTION, "NONE")); queryOptions.put(Constants.DELETE_EMPTY_COHORTS, query.getBoolean(Constants.DELETE_EMPTY_COHORTS, false)); - return createOkResponse(sampleManager.delete(studyStr, getIdList(samples), queryOptions, true, token)); + return createOkResponse(sampleManager.delete(organizationId, studyStr, getIdList(samples), queryOptions, true, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -415,7 +415,7 @@ public Response getAcls(@ApiParam(value = ParamConstants.SAMPLES_DESCRIPTION, re @ApiParam(value = ParamConstants.SILENT_DESCRIPTION, defaultValue = "false") @QueryParam(Constants.SILENT) boolean silent) { try { List idList = getIdList(sampleIdsStr); - return createOkResponse(sampleManager.getAcls(studyStr, idList, member, silent, token)); + return createOkResponse(sampleManager.getAcls(organizationId, studyStr, idList, member, silent, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -436,7 +436,7 @@ public Response updateAcl( SampleAclParams sampleAclParams = new SampleAclParams( params.getIndividual(), params.getFamily(), params.getFile(), params.getCohort(), params.getPermissions()); List idList = StringUtils.isEmpty(params.getSample()) ? Collections.emptyList() : getIdList(params.getSample(), false); - return createOkResponse(sampleManager.updateAcl(studyStr, idList, memberId, sampleAclParams, action, token)); + return createOkResponse(sampleManager.updateAcl(organizationId, studyStr, idList, memberId, sampleAclParams, action, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -470,7 +470,7 @@ public Response getAggregationStats( queryOptions.put(QueryOptions.FACET, facet); - DataResult queryResult = catalogManager.getSampleManager().facet(studyStr, query, queryOptions, defaultStats, + DataResult queryResult = catalogManager.getSampleManager().facet(organizationId, studyStr, query, queryOptions, defaultStats, token); return createOkResponse(queryResult); } catch (Exception e) { diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/UserWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/UserWSServer.java index b330d115a98..1f3ccb19546 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/UserWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/UserWSServer.java @@ -61,7 +61,7 @@ public UserWSServer(@Context UriInfo uriInfo, @Context HttpServletRequest httpSe public Response getInfo(@ApiParam(value = ParamConstants.USERS_DESCRIPTION, required = true) @PathParam("users") String userIds) { try { List userList = getIdList(userIds); - OpenCGAResult result = catalogManager.getUserManager().get(userList, queryOptions, token); + OpenCGAResult result = catalogManager.getUserManager().get(organizationId, userList, queryOptions, token); return createOkResponse(result); } catch (Exception e) { return createErrorResponse(e); @@ -125,7 +125,7 @@ public Response login( if (StringUtils.isNotEmpty(login.getPassword()) || StringUtils.isNotEmpty(login.getUser())) { throw new Exception("Only 'user' and 'password' fields or 'refreshToken' field are allowed at the same time"); } - authenticationResponse = catalogManager.getUserManager().refreshToken(login.getRefreshToken()); + authenticationResponse = catalogManager.getUserManager().refreshToken(organizationId, login.getRefreshToken()); } else { throw new Exception("Neither 'user' and 'password' for login nor 'refreshToken' for refreshing token were provided."); } @@ -165,7 +165,7 @@ public Response login( public Response changePassword( @ApiParam(value = "JSON containing the change of password parameters", required = true) PasswordChangeParams params) { try { - catalogManager.getUserManager().changePassword(params.getUser(), params.getPassword(), params.getNewPassword()); + catalogManager.getUserManager().changePassword(organizationId, params.getUser(), params.getPassword(), params.getNewPassword()); return createOkResponse(DataResult.empty()); } catch (Exception e) { return createErrorResponse(e); @@ -178,7 +178,7 @@ public Response changePassword( notes = "Reset the user's password and send a new random one to the e-mail stored in catalog.", response = User.class) public Response resetPassword(@ApiParam(value = ParamConstants.USER_DESCRIPTION, required = true) @PathParam("user") String userId) { try { - OpenCGAResult result = catalogManager.getUserManager().resetPassword(userId, token); + OpenCGAResult result = catalogManager.getUserManager().resetPassword(organizationId, userId, token); return createOkResponse(result, "The new password has been sent to the user's email."); } catch (Exception e) { return createErrorResponse(e); @@ -228,7 +228,7 @@ public Response updateByPost( ObjectUtils.defaultIfNull(parameters, new UserUpdateParams()); ObjectMap params = new ObjectMap(getUpdateObjectMapper().writeValueAsString(parameters)); - OpenCGAResult result = catalogManager.getUserManager().update(userId, params, queryOptions, token); + OpenCGAResult result = catalogManager.getUserManager().update(organizationId, userId, params, queryOptions, token); return createOkResponse(result); } catch (Exception e) { return createErrorResponse(e); @@ -251,10 +251,10 @@ public Response updateConfiguration( action = ParamUtils.AddRemoveAction.ADD; } if (action == ParamUtils.AddRemoveAction.ADD) { - return createOkResponse(catalogManager.getUserManager().setConfig(userId, params.getId(), params.getConfiguration(), + return createOkResponse(catalogManager.getUserManager().setConfig(organizationId, userId, params.getId(), params.getConfiguration(), token)); } else { - return createOkResponse(catalogManager.getUserManager().deleteConfig(userId, params.getId(), token)); + return createOkResponse(catalogManager.getUserManager().deleteConfig(organizationId, userId, params.getId(), token)); } } catch (Exception e) { return createErrorResponse(e); @@ -269,7 +269,7 @@ public Response getConfigurations( @ApiParam(value = "Unique name (typically the name of the application).") @QueryParam("name") String name) { try { ParamUtils.checkIsSingleID(userId); - return createOkResponse(catalogManager.getUserManager().getConfig(userId, name, token)); + return createOkResponse(catalogManager.getUserManager().getConfig(organizationId, userId, name, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -290,10 +290,10 @@ public Response updateFilters( action = ParamUtils.AddRemoveAction.ADD; } if (action == ParamUtils.AddRemoveAction.ADD) { - return createOkResponse(catalogManager.getUserManager().addFilter(userId, params.getId(), params.getDescription(), + return createOkResponse(catalogManager.getUserManager().addFilter(organizationId, userId, params.getId(), params.getDescription(), params.getResource(), params.getQuery(), params.getOptions(), token)); } else { - return createOkResponse(catalogManager.getUserManager().deleteFilter(userId, params.getId(), token)); + return createOkResponse(catalogManager.getUserManager().deleteFilter(organizationId, userId, params.getId(), token)); } } catch (Exception e) { return createErrorResponse(e); @@ -308,7 +308,7 @@ public Response updateFilterPOST( @ApiParam(value = "Filter id", required = true) @PathParam("filterId") String id, @ApiParam(value = "Filter parameters", required = true) FilterUpdateParams params) { try { - return createOkResponse(catalogManager.getUserManager().updateFilter(userId, id, + return createOkResponse(catalogManager.getUserManager().updateFilter(organizationId, userId, id, new ObjectMap(getUpdateObjectMapper().writeValueAsString(params)), token)); } catch (Exception e) { return createErrorResponse(e); @@ -324,9 +324,9 @@ public Response getFilterConfig( try { ParamUtils.checkIsSingleID(userId); if (StringUtils.isNotEmpty(id)) { - return createOkResponse(catalogManager.getUserManager().getFilter(userId, id, token)); + return createOkResponse(catalogManager.getUserManager().getFilter(organizationId, userId, id, token)); } else { - return createOkResponse(catalogManager.getUserManager().getAllFilters(userId, token)); + return createOkResponse(catalogManager.getUserManager().getAllFilters(organizationId, userId, token)); } } catch (Exception e) { return createErrorResponse(e); diff --git a/opencga-server/src/main/java/org/opencb/opencga/server/rest/admin/AdminWSServer.java b/opencga-server/src/main/java/org/opencb/opencga/server/rest/admin/AdminWSServer.java index 91ffe30c636..106b43cfa6e 100644 --- a/opencga-server/src/main/java/org/opencb/opencga/server/rest/admin/AdminWSServer.java +++ b/opencga-server/src/main/java/org/opencb/opencga/server/rest/admin/AdminWSServer.java @@ -83,7 +83,7 @@ public Response userSearch( @ApiParam(value = ParamConstants.USER_ACCOUNT_TYPE_DESCRIPTION) @QueryParam(ParamConstants.USER_ACCOUNT_TYPE) String account, @ApiParam(value = ParamConstants.USER_AUTHENTICATION_ORIGIN_DESCRIPTION) @QueryParam(ParamConstants.USER_AUTHENTICATION_ORIGIN) String authentication) { try { - return createOkResponse(catalogManager.getAdminManager().userSearch(query, queryOptions, token)); + return createOkResponse(catalogManager.getAdminManager().userSearch(organizationId, query, queryOptions, token)); } catch (CatalogException e) { return createErrorResponse(e); } @@ -105,7 +105,7 @@ public Response create(@ApiParam(value = "JSON containing the parameters", requi } OpenCGAResult queryResult = catalogManager.getUserManager() - .create(user.getId(), user.getName(), user.getEmail(), user.getPassword(), user.getOrganization(), null, user.getType(), token); + .create(organizationId, user.getId(), user.getName(), user.getEmail(), user.getPassword(), user.getOrganization(), null, user.getType(), token); return createOkResponse(queryResult); } catch (Exception e) { @@ -135,14 +135,14 @@ public Response remoteImport(@ApiParam(value = "JSON containing the parameters", } if (remoteParams.getResourceType() == USER || remoteParams.getResourceType() == APPLICATION) { - catalogManager.getUserManager().importRemoteEntities(remoteParams.getAuthenticationOriginId(), remoteParams.getId(), + catalogManager.getUserManager().importRemoteEntities(organizationId, remoteParams.getAuthenticationOriginId(), remoteParams.getId(), remoteParams.getResourceType() == APPLICATION, remoteParams.getStudyGroup(), remoteParams.getStudy(), token); } else if (remoteParams.getResourceType() == GROUP) { if (remoteParams.getId().size() > 1) { throw new CatalogException("More than one group found in 'id'. Only one group is accepted at a time"); } - catalogManager.getUserManager().importRemoteGroupOfUsers(remoteParams.getAuthenticationOriginId(), remoteParams.getId().get(0), + catalogManager.getUserManager().importRemoteGroupOfUsers(organizationId, remoteParams.getAuthenticationOriginId(), remoteParams.getId().get(0), remoteParams.getStudyGroup(), remoteParams.getStudy(), false, token); } else { throw new CatalogException("Unknown resourceType '" + remoteParams.getResourceType() + "'"); @@ -164,7 +164,7 @@ public Response updateGroups( defaultValue = "ADD") @QueryParam("action") ParamUtils.AddRemoveAction action, @ApiParam(value = "JSON containing the parameters", required = true) UserUpdateGroup updateParams) { try { - return createOkResponse(catalogManager.getAdminManager().updateGroups(user, updateParams.getStudyIds(), updateParams.getGroupIds(), action, token)); + return createOkResponse(catalogManager.getAdminManager().updateGroups(organizationId, user, updateParams.getStudyIds(), updateParams.getGroupIds(), action, token)); } catch (Exception e) { return createErrorResponse(e); } @@ -191,9 +191,9 @@ public Response externalSync(@ApiParam(value = "JSON containing the parameters", try { // TODO: These two methods should return an OpenCGAResult containing at least the number of changes if (syncParams.isSyncAll()) { - catalogManager.getUserManager().syncAllUsersOfExternalGroup(syncParams.getStudy(), syncParams.getAuthenticationOriginId(), token); + catalogManager.getUserManager().syncAllUsersOfExternalGroup(organizationId, syncParams.getStudy(), syncParams.getAuthenticationOriginId(), token); } else { - catalogManager.getUserManager().importRemoteGroupOfUsers(syncParams.getAuthenticationOriginId(), syncParams.getFrom(), + catalogManager.getUserManager().importRemoteGroupOfUsers(organizationId, syncParams.getAuthenticationOriginId(), syncParams.getFrom(), syncParams.getTo(), syncParams.getStudy(), true, token); } return createOkResponse(OpenCGAResult.empty(Group.class)); @@ -345,7 +345,7 @@ public Response jwt(@ApiParam(value = "JSON containing the parameters", required ObjectMap params = new ObjectMap(); params.putIfNotNull(MetaDBAdaptor.SECRET_KEY, jwtParams.getSecretKey()); try { - catalogManager.updateJWTParameters(params, token); + catalogManager.updateJWTParameters(organizationId, params, token); return createOkResponse(DataResult.empty()); } catch (Exception e) { return createErrorResponse(e); @@ -358,8 +358,8 @@ public Response jwt(@ApiParam(value = "JSON containing the parameters", required public Response token(@ApiParam(value = "Token parameters", required = true) TokenParams jwtParams) { try { String newToken = jwtParams.getExpiration() != null - ? catalogManager.getUserManager().getToken(jwtParams.getUserId(), jwtParams.getAttributes(), jwtParams.getExpiration(), token) - : catalogManager.getUserManager().getNonExpiringToken(jwtParams.getUserId(), jwtParams.getAttributes(), token); + ? catalogManager.getUserManager().getToken(organizationId, jwtParams.getUserId(), jwtParams.getAttributes(), jwtParams.getExpiration(), token) + : catalogManager.getUserManager().getNonExpiringToken(organizationId, jwtParams.getUserId(), jwtParams.getAttributes(), token); AuthenticationResponse authResponse = new AuthenticationResponse(newToken); OpenCGAResult opencgaResponse = new OpenCGAResult<>(0, Collections.emptyList(), 1, Collections.singletonList(authResponse), 1);