diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java b/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java index ea332f365..b583fb97e 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/ClassificationsService.java @@ -4,37 +4,37 @@ public interface ClassificationsService { - public String getFamilies() throws RmesException; + String getFamilies() throws RmesException; - public String getFamily(String id) throws RmesException; + String getFamily(String id) throws RmesException; - public String getFamilyMembers(String id) throws RmesException; + String getFamilyMembers(String id) throws RmesException; - public String getSeries() throws RmesException; + String getSeries() throws RmesException; - public String getOneSeries(String id) throws RmesException; + String getOneSeries(String id) throws RmesException; - public String getSeriesMembers(String id) throws RmesException; + String getSeriesMembers(String id) throws RmesException; - public String getClassifications() throws RmesException; + String getClassifications() throws RmesException; - public String getClassification(String id) throws RmesException; + String getClassification(String id) throws RmesException; - public void updateClassification(String id, String body) throws RmesException; + void updateClassification(String id, String body) throws RmesException; - public String getClassificationLevels(String id) throws RmesException; + String getClassificationLevels(String id) throws RmesException; - public String getClassificationLevel(String classificationid, String levelId) throws RmesException; + String getClassificationLevel(String classificationid, String levelId) throws RmesException; - public String getClassificationLevelMembers(String classificationid, String levelId) throws RmesException; + String getClassificationLevelMembers(String classificationid, String levelId) throws RmesException; - public String getCorrespondences() throws RmesException; + String getCorrespondences() throws RmesException; - public String getCorrespondence(String id) throws RmesException; + String getCorrespondence(String id) throws RmesException; - public String getCorrespondenceAssociations(String id) throws RmesException; + String getCorrespondenceAssociations(String id) throws RmesException; - public String getCorrespondenceAssociation(String correspondenceId, String associationId) throws RmesException; + String getCorrespondenceAssociation(String correspondenceId, String associationId) throws RmesException; - public String setClassificationValidation(String id) throws RmesException; + String setClassificationValidation(String id) throws RmesException; } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsCollectionService.java b/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsCollectionService.java index 4d29856cf..0d19cdccc 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsCollectionService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsCollectionService.java @@ -1,7 +1,7 @@ package fr.insee.rmes.bauhaus_services; import fr.insee.rmes.exceptions.RmesException; -import fr.insee.rmes.webservice.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java b/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java index 149b5c399..742480305 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/ConceptsService.java @@ -2,7 +2,7 @@ import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.concepts.MembersLg; -import fr.insee.rmes.webservice.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.ResponseEntity; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java index 0a40a9ad3..51fb33e39 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/ClassificationsImpl.java @@ -161,7 +161,7 @@ public String setClassificationValidation(String classificationId) throws RmesEx //GET graph JSONObject listGraph = repoGestion.getResponseAsObject(ClassificationsQueries.getGraphUriById(classificationId)); logger.debug("JSON for listGraph id : {}", listGraph); - if (listGraph.length()==0) {throw new RmesNotFoundException(ErrorCodes.CLASSIFICATION_UNKNOWN_ID, "Classification not found", classificationId);} + if (listGraph.isEmpty()) {throw new RmesNotFoundException(ErrorCodes.CLASSIFICATION_UNKNOWN_ID, "Classification not found", classificationId);} String graph = listGraph.getString("graph"); String classifUriString = listGraph.getString(Constants.URI); Resource graphIri = RdfUtils.createIRI(graph); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java index 01e8b96c1..b098a8228 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/classifications/item/ClassificationItemServiceImpl.java @@ -40,7 +40,7 @@ public String getClassificationItem(String classificationId, String itemId) thro logger.info("Starting to get classification item {} from {}", itemId, classificationId); JSONObject item = repoGestion.getResponseAsObject(ItemsQueries.itemQuery(classificationId, itemId)); JSONArray altLabels = repoGestion.getResponseAsArray(ItemsQueries.itemAltQuery(classificationId, itemId)); - if(altLabels.length() != 0) { + if(!altLabels.isEmpty()) { item.put("altLabels", altLabels); } return item.toString(); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java index 3fdd80d01..1dcbb2c89 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/code_list/CodeListServiceImpl.java @@ -166,7 +166,7 @@ private JSONObject groupByBroaderNarrowerCloseMatchByCode(String notation) throw } private void addLinkCodeToItem(JSONObject item, String key, JSONObject broaderNarrowerCloseMatchForCode){ - if(broaderNarrowerCloseMatchForCode.getJSONArray(key).length() > 0){ + if(!broaderNarrowerCloseMatchForCode.getJSONArray(key).isEmpty()){ item.put(key, broaderNarrowerCloseMatchForCode.getJSONArray(key)); } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java index 95e610625..c65a9bb35 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsCollectionServiceImpl.java @@ -9,7 +9,7 @@ import fr.insee.rmes.persistance.sparql_queries.concepts.CollectionsQueries; import fr.insee.rmes.utils.FilesUtils; import fr.insee.rmes.utils.XMLUtils; -import fr.insee.rmes.webservice.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.slf4j.Logger; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java index 12c6b8873..c44b290d4 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImpl.java @@ -21,7 +21,7 @@ import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; import fr.insee.rmes.utils.FilesUtils; import fr.insee.rmes.utils.XMLUtils; -import fr.insee.rmes.webservice.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; import jakarta.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionExportBuilder.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionExportBuilder.java index 5d7284cfc..205a4220a 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionExportBuilder.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/collections/CollectionExportBuilder.java @@ -13,7 +13,7 @@ import fr.insee.rmes.utils.ExportUtils; import fr.insee.rmes.utils.FilesUtils; import fr.insee.rmes.utils.XsltUtils; -import fr.insee.rmes.webservice.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; import jakarta.servlet.http.HttpServletResponse; import org.apache.http.HttpStatus; import org.json.JSONArray; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java index 3558adf23..9a025fe60 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/concepts/concepts/ConceptsUtils.java @@ -19,7 +19,7 @@ import fr.insee.rmes.persistance.sparql_queries.concepts.ConceptsQueries; import fr.insee.rmes.utils.FilesUtils; import fr.insee.rmes.utils.JSONUtils; -import fr.insee.rmes.webservice.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; @@ -86,10 +86,10 @@ public JSONObject getConceptById(String id) throws RmesException{ JSONObject concept = repoGestion.getResponseAsObject(ConceptsQueries.conceptQuery(id)); JSONArray altLabelLg1 = repoGestion.getResponseAsArray(ConceptsQueries.altLabel(id, config.getLg1())); JSONArray altLabelLg2 = repoGestion.getResponseAsArray(ConceptsQueries.altLabel(id, config.getLg2())); - if(altLabelLg1.length() != 0) { + if(!altLabelLg1.isEmpty()) { concept.put(Constants.ALT_LABEL_LG1, JSONUtils.extractFieldToArray(altLabelLg1, "altLabel")); } - if(altLabelLg2.length() != 0) { + if(!altLabelLg2.isEmpty()) { concept.put(Constants.ALT_LABEL_LG2, JSONUtils.extractFieldToArray(altLabelLg2, "altLabel")); } return concept; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImpl.java index 25fe18e3b..eadb9bbfd 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImpl.java @@ -188,6 +188,7 @@ private String persist(Distribution distribution, boolean creation) throws RmesE private void validate(Distribution distribution) throws RmesException { if (distribution.getIdDataset() == null) { throw new RmesBadRequestException("The property idDataset is required"); + } if (distribution.getLabelLg1() == null) { throw new RmesBadRequestException("The property labelLg1 is required"); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java index 046c35cd8..33fd579cd 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/geography/GeographyServiceImpl.java @@ -39,7 +39,7 @@ public class GeographyServiceImpl extends RdfService implements GeographyService public String getGeoFeatures() throws RmesException { logger.info("Starting to get geo features"); JSONArray resQuery = repoGestion.getResponseAsArray(GeoQueries.getFeaturesQuery()); - if (resQuery.length() != 0) { + if (!resQuery.isEmpty()) { for (int i = resQuery.length() - 1; i >= 0; i--) { JSONObject feature = resQuery.getJSONObject(i); if (feature.has(HAS_COMPOSITION)) { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java index 8913cba43..7d9eaeb1d 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/notes/NotesUtils.java @@ -94,7 +94,7 @@ public void createRdfDatableNote(String conceptId, DatableNote datableNote, Mode public void deleteDatableNote(String conceptId, DatableNote datableNote, List notesToDelete) throws RmesException{ JSONObject noteToDelete = repoGestion.getResponseAsObject(NotesQueries.getChangeNoteToDelete(conceptId, datableNote)); - if (noteToDelete.length() != 0) { + if (!noteToDelete.isEmpty()) { notesToDelete.add(RdfUtils.toURI(noteToDelete.getString("changeNoteURI"))); } } @@ -117,7 +117,7 @@ public String getLastVersion(Concept concept, VersionableNote note, String defau } else { JSONObject jsonVersion = repoGestion.getResponseAsObject( NotesQueries.getLastVersionnableNoteVersion(concept.getId(), note.getPredicat())); - if (jsonVersion.length() == 0) { + if (jsonVersion.isEmpty()) { return defaultVersion; } return jsonVersion.getString("version"); @@ -127,7 +127,7 @@ public String getLastVersion(Concept concept, VersionableNote note, String defau public String getConceptVersion(Concept concept) throws RmesException{ String conceptVersion = ONE; JSONObject jsonConceptVersion = repoGestion.getResponseAsObject(NotesQueries.getConceptVersion(concept.getId())); - if (jsonConceptVersion.length() == 0) { + if (jsonConceptVersion.isEmpty()) { return conceptVersion; } conceptVersion = jsonConceptVersion.getString("conceptVersion"); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java index 1ef94c259..c7bb0e268 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/OperationsImpl.java @@ -115,14 +115,14 @@ public void setSeries(String id, String body) throws RmesException { @Override public String getOperationsWithoutReport(String idSeries) throws RmesException { JSONArray resQuery = repoGestion.getResponseAsArray(OperationsQueries.operationsWithoutSimsQuery(idSeries)); - if (resQuery.length()==1 &&resQuery.getJSONObject(0).length()==0) {resQuery.remove(0);} + if (resQuery.length()==1 && resQuery.getJSONObject(0).isEmpty()) {resQuery.remove(0);} return QueryUtils.correctEmptyGroupConcat(resQuery.toString()); } @Override public String getOperationsWithReport(String idSeries) throws RmesException { JSONArray resQuery = repoGestion.getResponseAsArray(OperationsQueries.operationsWithSimsQuery(idSeries)); - if (resQuery.length()==1 &&resQuery.getJSONObject(0).length()==0) {resQuery.remove(0);} + if (resQuery.length()==1 && resQuery.getJSONObject(0).isEmpty()) {resQuery.remove(0);} return QueryUtils.correctEmptyGroupConcat(resQuery.toString()); } @@ -217,7 +217,7 @@ public String setFamilyValidation(String id) throws RmesException{ public String getSeriesWithReport(String idFamily) throws RmesException { JSONArray resQuery = repoGestion.getResponseAsArray(OperationsQueries.seriesWithSimsQuery(idFamily)); - if (resQuery.length()==1 &&resQuery.getJSONObject(0).length()==0) {resQuery.remove(0);} + if (resQuery.length()==1 && resQuery.getJSONObject(0).isEmpty()) {resQuery.remove(0);} return QueryUtils.correctEmptyGroupConcat(resQuery.toString()); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java index 5b7bfde57..ec4834684 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsRubricsUtils.java @@ -73,7 +73,7 @@ public void getAllRubricsJson(String idSims, JSONObject jsonSims) throws RmesException { JSONArray docRubrics = repoGestion .getResponseAsArray(DocumentationsQueries.getDocumentationRubricsQuery(idSims, langService.getLanguage1(), langService.getLanguage2())); - if (docRubrics.length() != 0) { + if (!docRubrics.isEmpty()) { clearRubrics(idSims, docRubrics); jsonSims.put("rubrics", docRubrics); } @@ -116,7 +116,7 @@ else if (rubric.get(Constants.RANGE_TYPE).equals(RangeType.GEOGRAPHY.name())) { clearGeographyRubric(rubric); } } - if (tempMultipleCodeList.size() != 0) { + if (!tempMultipleCodeList.isEmpty()) { tempMultipleCodeList.forEach((k, v) -> docRubrics.put(v)); } return docRubrics; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java index bd3e18033..dd4b94daf 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/DocumentationsUtils.java @@ -83,7 +83,7 @@ public JSONObject getDocumentationByIdSims(String idSims) throws RmesException { // Get general informations JSONObject doc = repoGestion.getResponseAsObject(DocumentationsQueries.getDocumentationTitleQuery(idSims)); - if (doc.length() == 0) { + if (doc.isEmpty()) { throw new RmesNotFoundException(ErrorCodes.SIMS_UNKNOWN_ID, "Documentation not found", idSims); } doc.put(Constants.ID, idSims); @@ -404,7 +404,7 @@ private String createSimsID() throws RmesException { logger.info("Generate documentation id"); JSONObject json = repoGestion.getResponseAsObject(DocumentationsQueries.lastID()); logger.debug("JSON for documentation id : {}", json); - if (json.length() == 0) { + if (json.isEmpty()) { return "1000"; } String id = json.getString(Constants.ID_SIMS); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java index ffb3a0372..761061a12 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/MetadataStructureDefUtils.java @@ -26,7 +26,7 @@ public class MetadataStructureDefUtils extends RdfService { public JSONObject getMetadataAttributeById(String id) throws RmesException{ JSONObject mas = repoGestion.getResponseAsObject(DocumentationsQueries.getAttributeSpecificationQuery(id)); - if (mas.length()==0) {throw new RmesException(HttpStatus.SC_BAD_REQUEST, "Attribute not found", "id doesn't exist"+id);} + if (mas.isEmpty()) {throw new RmesException(HttpStatus.SC_BAD_REQUEST, "Attribute not found", "id doesn't exist"+id);} transformRangeType(mas); mas.put(Constants.ID, id); return mas; @@ -48,7 +48,7 @@ public void transformRangeType(JSONObject mas) throws RmesException { public JSONArray getMetadataAttributes() throws RmesException { JSONArray attributesList = repoGestion.getResponseAsArray(DocumentationsQueries.getAttributesQuery()); - if (attributesList.length() != 0) { + if (!attributesList.isEmpty()) { for (int i = 0; i < attributesList.length(); i++) { JSONObject attribute = attributesList.getJSONObject(i); transformRangeType(attribute); @@ -60,7 +60,7 @@ public JSONArray getMetadataAttributes() throws RmesException { public Map getMetadataAttributesUri() throws RmesException { Map attributes = new HashMap<>(); JSONArray attributesList = repoGestion.getResponseAsArray(DocumentationsQueries.getAttributesUriQuery()); - if (attributesList.length() != 0) { + if (!attributesList.isEmpty()) { for (int i = 0; i < attributesList.length(); i++) { JSONObject attribute = attributesList.getJSONObject(i); if (attribute.has(Constants.ID)&& attribute.has(Constants.URI)) { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java index 8f2979606..ab13ce75b 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/documentations/documents/DocumentsUtils.java @@ -143,7 +143,7 @@ public JSONArray getAllDocuments() throws RmesException { } private void formatDateInJsonArray(JSONArray allDocs) { - if (allDocs.length() != 0) { + if (!allDocs.isEmpty()) { for (int i = 0; i < allDocs.length(); i++) { JSONObject doc = allDocs.getJSONObject(i); formatDateInJsonObject(doc); @@ -177,7 +177,7 @@ protected String createDocumentID() throws RmesException { } public Integer getIdFromJson(JSONObject json) { - if (json.length() == 0) { + if (json.isEmpty()) { return null; } else { String id = json.getString(Constants.ID); @@ -279,7 +279,7 @@ private void checkDocumentDoesNotExist(String id, String url) throws RmesExcepti private void checkUrlDoesNotExist(String id, String url, int errorCode, String errorMessage) throws RmesException { JSONObject existingUriJson = repoGestion.getResponseAsObject(DocumentsQueries.getDocumentUriQuery(url)); - if (existingUriJson.length() > 0) { + if (!existingUriJson.isEmpty()) { String uri = existingUriJson.getString(Constants.DOCUMENT); String existingId = getDocumentNameFromUrl(uri); if (!existingId.equals(id)) { @@ -382,7 +382,7 @@ public HttpStatus deleteDocument(String docId, boolean isLink) throws RmesExcept // Check that the document is not referred to by any sims private void checkDocumentReference(String docId, String uri) throws RmesException { JSONArray jsonResultat = repoGestion.getResponseAsArray(DocumentsQueries.getLinksToDocumentQuery(docId)); - if (jsonResultat.length() > 0) { + if (!jsonResultat.isEmpty()) { throw new RmesBadRequestException(ErrorCodes.DOCUMENT_DELETION_LINKED, "The document " + uri + "cannot be deleted because it is referred to by " + jsonResultat.length() + " sims, including: " + ((JSONObject) jsonResultat.get(0)).get(Constants.TEXT).toString(), @@ -398,7 +398,7 @@ private void checkDocumentReference(String docId, String uri) throws RmesExcepti */ private void checkRightsToModifyFile(String docId) throws RmesException { JSONArray sims = repoGestion.getResponseAsArray(DocumentsQueries.getLinksToDocumentQuery(docId)); - if (sims.length() == 0) return; //document's file isn't linked to a sims + if (sims.isEmpty()) return; //document's file isn't linked to a sims for (int i = 0; i < sims.length(); i++) { String simsUri = ((JSONObject) sims.get(i)).get(Constants.TEXT).toString(); @@ -587,7 +587,7 @@ private String createFileUrl(String name) throws RmesException { private IRI getDocumentUri(IRI url) throws RmesException { JSONObject uri = repoGestion .getResponseAsObject(DocumentsQueries.getDocumentUriQuery(getDocumentNameFromUrl(url.stringValue()))); - if (uri.length() == 0 || !uri.has(Constants.DOCUMENT)) { + if (uri.isEmpty() || !uri.has(Constants.DOCUMENT)) { String id = createDocumentID(); return RdfUtils.objectIRI(ObjectType.DOCUMENT, id); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java index 16e326331..557fd87e8 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/famopeserind_utils/FamOpeSerIndUtils.java @@ -28,7 +28,7 @@ public String createId() throws RmesException { logger.info("Generate famOpeSer id"); JSONObject json = repoGestion.getResponseAsObject(FamOpeSerQueries.lastId()); logger.debug("JSON for famOpeSer id : {}", json); - if (json.length()==0) {return "1000";} + if (json.isEmpty()) {return "1000";} String id = json.getString(Constants.ID); if (id.equals(Constants.UNDEFINED)) {return "1000";} return "s" + (Integer.parseInt(id)+1); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java index a69a51ea3..60c168eaa 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/indicators/IndicatorsUtils.java @@ -204,7 +204,7 @@ private void addLinks(String idIndic, JSONObject indicator) throws RmesException private void addOneTypeOfLink(String id, JSONObject object, IRI predicate) throws RmesException { JSONArray links = repositoryGestion.getResponseAsArray(IndicatorsQueries.indicatorLinks(id, predicate)); - if (links.length() != 0) { + if (!links.isEmpty()) { links = QueryUtils.transformRdfTypeInString(links); object.put(predicate.getLocalName(), links); } @@ -212,7 +212,7 @@ private void addOneTypeOfLink(String id, JSONObject object, IRI predicate) throw private void addOneOrganizationLink(String id, JSONObject object, IRI predicate) throws RmesException { JSONArray organizations = repositoryGestion.getResponseAsArray(IndicatorsQueries.getMultipleOrganizations(id, predicate)); - if (organizations.length() != 0) { + if (!organizations.isEmpty()) { for (int i = 0; i < organizations.length(); i++) { JSONObject orga = organizations.getJSONObject(i); orga.put("type", ObjectType.ORGANIZATION.labelType()); @@ -423,7 +423,7 @@ public String createID() throws RmesException { logger.info("Generate indicator id"); JSONObject json = repositoryGestion.getResponseAsObject(IndicatorsQueries.lastID()); logger.debug("JSON for indicator id : {}" , json); - if (json.length()==0) {return null;} + if (json.isEmpty()) {return null;} String id = json.getString(Constants.ID); if (id.equals(Constants.UNDEFINED)) {return null;} int idInt = Integer.parseInt(id.substring(1))+1; diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java index fa41275f6..5deaffd4e 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/operations/series/SeriesUtils.java @@ -230,7 +230,7 @@ private void addSeriesLinks(String idSeries, JSONObject series) throws RmesExcep private void addOneTypeOfLink(String id, JSONObject series, IRI predicate, String resultType) throws RmesException { JSONArray links = repositoryGestion.getResponseAsArray(OpSeriesQueries.seriesLinks(id, predicate, resultType)); - if (links.length() != 0) { + if (!links.isEmpty()) { links = QueryUtils.transformRdfTypeInString(links); } series.put(predicate.getLocalName(), links); @@ -240,7 +240,7 @@ private Map getOneTypeOfLink(IRI predicate, String resultType JSONArray links = repositoryGestion.getResponseAsArray(OpSeriesQueries.seriesLinks("", predicate, resultType)); Map map = new HashMap<>(); - if (links.length() != 0) { + if (!links.isEmpty()) { links = QueryUtils.transformRdfTypeInString(links); for (int i = 0; i < links.length(); i++) { JSONObject l = links.getJSONObject(i); @@ -269,7 +269,7 @@ private void addSeriesCreators(String id, JSONObject series) throws RmesExceptio private Map> getAllSeriesCreators() throws RmesException { Map> map = new HashMap<>(); JSONArray creators = repositoryGestion.getResponseAsArray(OpSeriesQueries.getCreatorsById("")); - if (creators.length() != 0) { + if (!creators.isEmpty()) { for (int i = 0; i < creators.length(); i++) { JSONObject crea = creators.getJSONObject(i); if (crea.has(ID_SERIE)) { diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java index 23221f3a0..6cfa398f4 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryGestion.java @@ -294,7 +294,7 @@ public void loadObjectWithReplaceLinks(IRI object, Model model) throws RmesExcep try (RepositoryConnection conn=repositoryUtils.initRepository(rdfGestion.getUrlServer(), - rdfGestion.repositoryId()).getConnection();) + rdfGestion.repositoryId()).getConnection()) { clearReplaceLinks(object); loadSimpleObject(object, model, conn); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java index f045c550d..ff88ad392 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/rdf_utils/RepositoryUtils.java @@ -410,7 +410,7 @@ public static JSONArray getResponseAsJSONList(String query, Repository repositor */ public static JSONObject getResponseAsObject(String query, Repository repository) throws RmesException { JSONArray resArray = getResponseAsArray(query, repository); - if (resArray==null || resArray.length() == 0) { + if (resArray==null || resArray.isEmpty()) { return new JSONObject(); } return (JSONObject) resArray.get(0); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java index eb950628a..d0f989efd 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureComponentImpl.java @@ -51,7 +51,7 @@ public JSONObject getComponentObject(String id) throws RmesException { JSONArray response = repoGestion.getResponseAsArray(StructureQueries.getComponent(id)); - if(response.length() == 0){ + if(response.isEmpty()){ throw new RmesNotFoundException("This component does not exist", id); } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java index 507442370..4bf0391e2 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/impl/StructureImpl.java @@ -54,7 +54,7 @@ public String getStructureById(String id) throws RmesException { } private void removeEmptyAttachment(JSONObject cd){ - if(((JSONArray) cd.get("attachment")).length() == 0){ + if(((JSONArray) cd.get("attachment")).isEmpty()){ cd.remove("attachment"); } } diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java index 7500c836c..7244c2b33 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureComponentUtils.java @@ -265,7 +265,7 @@ private String generateNextId(String prefix, String namespaceSuffix, IRI type) t logger.info("Generate id for component"); JSONObject json = repoGestion.getResponseAsObject(StructureQueries.lastId(namespaceSuffix, RdfUtils.toString(type))); logger.debug("JSON when generating the id of a component : {}", json); - if (json.length() == 0) { + if (json.isEmpty()) { return prefix + "1000"; } String id = json.getString(Constants.ID); diff --git a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java index f9b51e2d7..5c92d54eb 100644 --- a/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java +++ b/src/main/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtils.java @@ -164,7 +164,7 @@ private String generateNextId() throws RmesException { logger.info("Generate id for structure"); JSONObject json = repoGestion.getResponseAsObject(StructureQueries.lastStructureId()); logger.debug("JSON when generating the id of a structure : {}", json); - if (json.length() == 0) { + if (json.isEmpty()) { return prefix + "1000"; } String id = json.getString(Constants.ID); diff --git a/src/main/java/fr/insee/rmes/exceptions/RmesExceptionHandler.java b/src/main/java/fr/insee/rmes/exceptions/RmesExceptionHandler.java index fb757b73e..62294420d 100644 --- a/src/main/java/fr/insee/rmes/exceptions/RmesExceptionHandler.java +++ b/src/main/java/fr/insee/rmes/exceptions/RmesExceptionHandler.java @@ -1,12 +1,14 @@ package fr.insee.rmes.exceptions; -import fr.insee.rmes.webservice.UserResources; +import fr.insee.rmes.webservice.*; +import fr.insee.rmes.webservice.classifications.ClassificationsResources; import fr.insee.rmes.webservice.codesLists.CodeListsResources; -import fr.insee.rmes.webservice.dataset.DatasetResources; -import fr.insee.rmes.webservice.distribution.DistributionResources; -import fr.insee.rmes.webservice.operations.DocumentsResources; -import fr.insee.rmes.webservice.operations.MetadataReportResources; -import fr.insee.rmes.webservice.operations.OperationsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsResources; +import fr.insee.rmes.webservice.datasets.DatasetResources; +import fr.insee.rmes.webservice.datasets.DistributionResources; +import fr.insee.rmes.webservice.operations.*; +import fr.insee.rmes.webservice.structures.StructureResources; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; @@ -16,18 +18,37 @@ import java.nio.file.NoSuchFileException; @ControllerAdvice(assignableTypes = { - DatasetResources.class, - DistributionResources.class, CodeListsResources.class, MetadataReportResources.class, - OperationsResources.class, - DocumentsResources.class, UserResources.class, + ConceptsResources.class, + ConceptsCollectionsResources.class, + + StructureResources.class, + ClassificationsResources.class, + // + DatasetResources.class, + DistributionResources.class, + // + + // + FamilyResources.class, + SeriesResources.class, + OperationsResources.class, + IndicatorsResources.class, + DocumentsResources.class, + MetadataReportResources.class + // }) public class RmesExceptionHandler extends ResponseEntityExceptionHandler { - @ExceptionHandler({RmesBadRequestException.class, RmesNotFoundException.class, RmesNotAcceptableException.class, RmesUnauthorizedException.class}) + @ExceptionHandler({ + RmesBadRequestException.class, + RmesNotFoundException.class, + RmesNotAcceptableException.class, + RmesUnauthorizedException.class + }) public final ResponseEntity handleSubclassesOfRmesException(RmesException exception) { return ResponseEntity.status(exception.getStatus()).body(exception.getDetails()); } @@ -41,7 +62,7 @@ public final ResponseEntity handleRmesFileException(RmesFileException ex @ExceptionHandler(RmesException.class) public final ResponseEntity handleRmesException(RmesException exception){ logger.error(exception.getMessageAndDetails(), exception); - return ResponseEntity.internalServerError().body(exception.getMessage()); + return ResponseEntity.internalServerError().body(exception.getDetails()); } @ExceptionHandler(NoSuchFileException.class) diff --git a/src/main/java/fr/insee/rmes/model/ValidationStatus.java b/src/main/java/fr/insee/rmes/model/ValidationStatus.java index 525d04a6e..13122d8a2 100644 --- a/src/main/java/fr/insee/rmes/model/ValidationStatus.java +++ b/src/main/java/fr/insee/rmes/model/ValidationStatus.java @@ -7,7 +7,7 @@ public enum ValidationStatus { private String value; - private ValidationStatus(String value) { + ValidationStatus(String value) { this.setValue(value); } diff --git a/src/main/java/fr/insee/rmes/model/dissemination_status/DisseminationStatus.java b/src/main/java/fr/insee/rmes/model/dissemination_status/DisseminationStatus.java index d8b976339..a60e1858f 100644 --- a/src/main/java/fr/insee/rmes/model/dissemination_status/DisseminationStatus.java +++ b/src/main/java/fr/insee/rmes/model/dissemination_status/DisseminationStatus.java @@ -11,7 +11,7 @@ public enum DisseminationStatus { private final String label; private final String url; - private DisseminationStatus(String label, String url) { + DisseminationStatus(String label, String url) { this.label = label; this.url = url; } diff --git a/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java b/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java index 24f907e1e..d25906fb6 100644 --- a/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java +++ b/src/main/java/fr/insee/rmes/model/operations/documentations/RangeType.java @@ -29,7 +29,7 @@ public enum RangeType { private String jsonType; - private RangeType(IRI rdfType, String jsonType) { + RangeType(IRI rdfType, String jsonType) { this.rdfType = rdfType; this.jsonType = jsonType; } diff --git a/src/main/java/fr/insee/rmes/persistance/ontologies/ADMS.java b/src/main/java/fr/insee/rmes/persistance/ontologies/ADMS.java index baa8f4aa6..6ae318a31 100644 --- a/src/main/java/fr/insee/rmes/persistance/ontologies/ADMS.java +++ b/src/main/java/fr/insee/rmes/persistance/ontologies/ADMS.java @@ -1,9 +1,7 @@ package fr.insee.rmes.persistance.ontologies; import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Namespace; import org.eclipse.rdf4j.model.ValueFactory; -import org.eclipse.rdf4j.model.impl.SimpleNamespace; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; public class ADMS { @@ -13,8 +11,6 @@ public class ADMS { public static final String PREFIX = "adms"; - public static final Namespace NS = new SimpleNamespace(PREFIX, NAMESPACE); - private static IRI createIRI(String suffix) { return factory.createIRI(NAMESPACE, suffix); } diff --git a/src/main/java/fr/insee/rmes/utils/ExportUtils.java b/src/main/java/fr/insee/rmes/utils/ExportUtils.java index 511808879..064c95584 100644 --- a/src/main/java/fr/insee/rmes/utils/ExportUtils.java +++ b/src/main/java/fr/insee/rmes/utils/ExportUtils.java @@ -100,7 +100,7 @@ public InputStream exportAsInputStream(String fileName, Map xmlC } try (OutputStream osOutputFile = FileUtils.openOutputStream(output); - PrintStream printStream = new PrintStream(osOutputFile);) { + PrintStream printStream = new PrintStream(osOutputFile)) { Path tempDir = Files.createTempDirectory("forExport"); Path finalPath = Paths.get(tempDir.toString(), fileName + extension); diff --git a/src/main/java/fr/insee/rmes/webservice/OperationsCommonResources.java b/src/main/java/fr/insee/rmes/webservice/OperationsCommonResources.java deleted file mode 100644 index 392896475..000000000 --- a/src/main/java/fr/insee/rmes/webservice/OperationsCommonResources.java +++ /dev/null @@ -1,38 +0,0 @@ -package fr.insee.rmes.webservice; - - -import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; -import fr.insee.rmes.bauhaus_services.OperationsService; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.responses.ApiResponses; -import io.swagger.v3.oas.annotations.tags.Tag; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - - -@RestController -@RequestMapping("/operations") -@Tag(name="Operations", description="Operation API") -@ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "Success"), - @ApiResponse(responseCode = "204", description = "No Content"), - @ApiResponse(responseCode = "400", description = "Bad Request"), - @ApiResponse(responseCode = "401", description = "Unauthorized"), - @ApiResponse(responseCode = "403", description = "Forbidden"), - @ApiResponse(responseCode = "404", description = "Not found"), - @ApiResponse(responseCode = "406", description = "Not Acceptable"), - @ApiResponse(responseCode = "500", description = "Internal server error") }) -public class OperationsCommonResources extends GenericResources { - - - @Autowired - protected OperationsService operationsService; - - @Autowired - protected OperationsDocumentationsService documentationsService; - - - - -} diff --git a/src/main/java/fr/insee/rmes/webservice/ClassificationsResources.java b/src/main/java/fr/insee/rmes/webservice/classifications/ClassificationsResources.java similarity index 56% rename from src/main/java/fr/insee/rmes/webservice/ClassificationsResources.java rename to src/main/java/fr/insee/rmes/webservice/classifications/ClassificationsResources.java index 40f3df42c..48dde2ad7 100644 --- a/src/main/java/fr/insee/rmes/webservice/ClassificationsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/classifications/ClassificationsResources.java @@ -1,4 +1,4 @@ -package fr.insee.rmes.webservice; +package fr.insee.rmes.webservice.classifications; import fr.insee.rmes.bauhaus_services.ClassificationsService; import fr.insee.rmes.bauhaus_services.Constants; @@ -18,9 +18,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -43,114 +40,81 @@ @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "406", description = "Not Acceptable"), @ApiResponse(responseCode = "500", description = "Internal server error") }) -public class ClassificationsResources extends GenericResources { +public class ClassificationsResources { + public enum Language { - lg1, lg2; + lg1, lg2 } - static final Logger logger = LoggerFactory.getLogger(ClassificationsResources.class); - - @Autowired + final ClassificationsService classificationsService; - @Autowired + final ClassificationItemService classificationItemService; + public ClassificationsResources(ClassificationsService classificationsService, ClassificationItemService classificationItemService) { + this.classificationsService = classificationsService; + this.classificationItemService = classificationItemService; + } + @GetMapping(value = "/families", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getClassificationFamilies", summary = "List of classification families", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=IdLabel.class))))}) - public ResponseEntity getFamilies() { - String jsonResultat; - try { - jsonResultat = classificationsService.getFamilies(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getFamilies() throws RmesException { + String families = classificationsService.getFamilies(); + return ResponseEntity.status(HttpStatus.OK).body(families); } @GetMapping(value="/family/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getFamily", summary = "Classification family", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = FamilyClass.class)))}) - public ResponseEntity getFamily(@PathVariable(Constants.ID) String id) { - String jsonResultat; - try { - jsonResultat = classificationsService.getFamily(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getFamily(@PathVariable(Constants.ID) String id) throws RmesException { + String family = classificationsService.getFamily(id); + return ResponseEntity.status(HttpStatus.OK).body(family); } @GetMapping(value="/family/{id}/members", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getFamilyMembers", summary = "Members of family", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=Members.class))))}) - public ResponseEntity getFamilyMembers(@PathVariable(Constants.ID) String id) { - String jsonResultat; - try { - jsonResultat = classificationsService.getFamilyMembers(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getFamilyMembers(@PathVariable(Constants.ID) String id) throws RmesException { + String familyMembers = classificationsService.getFamilyMembers(id); + return ResponseEntity.status(HttpStatus.OK).body(familyMembers); } @GetMapping(value="/series", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getClassificationSeries", summary = "List of classification series", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=IdLabel.class))))}) - public ResponseEntity getSeries() { - try { - String series = classificationsService.getSeries(); - return ResponseEntity.status(HttpStatus.OK).body(series); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getSeries() throws RmesException { + String series = classificationsService.getSeries(); + return ResponseEntity.status(HttpStatus.OK).body(series); } @GetMapping(value="/series/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getOneSeries(@PathVariable(Constants.ID) String id) { - try { - String serie = classificationsService.getOneSeries(id); - return ResponseEntity.status(HttpStatus.OK).body(serie); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getOneSeries(@PathVariable(Constants.ID) String id) throws RmesException { + String serie = classificationsService.getOneSeries(id); + return ResponseEntity.status(HttpStatus.OK).body(serie); } @GetMapping(value="/series/{id}/members", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getSeriesMembers", summary = "Members of series", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=Members.class))))}) - public ResponseEntity getSeriesMembers(@PathVariable(Constants.ID) String id) { - String jsonResultat; - try { - jsonResultat = classificationsService.getSeriesMembers(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getSeriesMembers(@PathVariable(Constants.ID) String id) throws RmesException { + String seriesMembers = classificationsService.getSeriesMembers(id); + return ResponseEntity.status(HttpStatus.OK).body(seriesMembers); } @GetMapping(value="",produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getClassifications", summary = "List of classifications", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=IdLabel.class))))}) - public ResponseEntity getClassifications() { - String jsonResultat; - try { - jsonResultat = classificationsService.getClassifications(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getClassifications() throws RmesException { + String classifications = classificationsService.getClassifications(); + return ResponseEntity.status(HttpStatus.OK).body(classifications); } @GetMapping(value="/classification/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getClassification(@PathVariable(Constants.ID) String id) { - try { - String classification = classificationsService.getClassification(id); - return ResponseEntity.status(HttpStatus.OK).body(classification); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getClassification(@PathVariable(Constants.ID) String id) throws RmesException { + String classification = classificationsService.getClassification(id); + return ResponseEntity.status(HttpStatus.OK).body(classification); } @PreAuthorize("isAdmin()") @@ -158,153 +122,93 @@ public ResponseEntity getClassification(@PathVariable(Constants.ID) Stri @io.swagger.v3.oas.annotations.Operation(operationId = "updateClassification", summary = "Update an existing classification" ) public ResponseEntity updateClassification( @PathVariable(Constants.ID) String id, - @Parameter(description = "Classification to update", required = true, content = @Content(schema = @Schema(implementation = Classification.class))) @org.springframework.web.bind.annotation.RequestBody String body) { - try { - classificationsService.updateClassification(id, body); - return ResponseEntity.status(HttpStatus.OK).body(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + @Parameter(description = "Classification to update", required = true, content = @Content(schema = @Schema(implementation = Classification.class))) @org.springframework.web.bind.annotation.RequestBody String body) throws RmesException { + classificationsService.updateClassification(id, body); + return ResponseEntity.status(HttpStatus.OK).body(id); } @PreAuthorize("isAdmin()") @PutMapping(value="/classification/{id}/validate") @io.swagger.v3.oas.annotations.Operation(operationId = "publishClassification", summary = "Publish a classification") public ResponseEntity publishClassification( - @PathVariable(Constants.ID) String id) { - try { - classificationsService.setClassificationValidation(id); - } catch (RmesException e) { - logger.error(e.getMessage(), e); - return returnRmesException(e); - } + @PathVariable(Constants.ID) String id) throws RmesException { + classificationsService.setClassificationValidation(id); return ResponseEntity.status(HttpStatus.OK).body(id); } @GetMapping(value="/classification/{id}/items", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getClassificationItems(@PathVariable(Constants.ID) String id) { - try { - String items = classificationItemService.getClassificationItems(id); - return ResponseEntity.status(HttpStatus.OK).body(items); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getClassificationItems(@PathVariable(Constants.ID) String id) throws RmesException { + String items = classificationItemService.getClassificationItems(id); + return ResponseEntity.status(HttpStatus.OK).body(items); } @GetMapping(value="/classification/{id}/levels", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getClassificationLevels(@PathVariable(Constants.ID) String id) { - String jsonResultat; - try { - jsonResultat = classificationsService.getClassificationLevels(id); - } catch (RmesException e) { - return returnRmesException(e); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getClassificationLevels(@PathVariable(Constants.ID) String id) throws RmesException { + String classificationLevels = classificationsService.getClassificationLevels(id); + return ResponseEntity.status(HttpStatus.OK).body(classificationLevels); } @GetMapping(value="/classification/{id}/level/{levelId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getClassificationLevel(@PathVariable(Constants.ID) String id, @PathVariable("levelId") String levelId) { - String jsonResultat; - try { - jsonResultat = classificationsService.getClassificationLevel(id, levelId); - } catch (RmesException e) { - return returnRmesException(e); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getClassificationLevel(@PathVariable(Constants.ID) String id, @PathVariable("levelId") String levelId) throws RmesException { + String classificationLevel = classificationsService.getClassificationLevel(id, levelId); + return ResponseEntity.status(HttpStatus.OK).body(classificationLevel); } @GetMapping(value="/classification/{classificationId}/level/{levelId}/members", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getClassificationLevelMembers(@PathVariable("classificationId") String classificationId, @PathVariable("levelId") String levelId) { - try { - String levelMembers = classificationsService.getClassificationLevelMembers(classificationId, levelId); - return ResponseEntity.status(HttpStatus.OK).body(levelMembers); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getClassificationLevelMembers(@PathVariable("classificationId") String classificationId, @PathVariable("levelId") String levelId) throws RmesException { + String levelMembers = classificationsService.getClassificationLevelMembers(classificationId, levelId); + return ResponseEntity.status(HttpStatus.OK).body(levelMembers); } @GetMapping(value="/classification/{classificationId}/item/{itemId}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getClassificationItem(@PathVariable("classificationId") String classificationId, @PathVariable("itemId") String itemId) { - try { - String classificationItem = classificationItemService.getClassificationItem(classificationId, itemId); - return ResponseEntity.status(HttpStatus.OK).body(classificationItem); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getClassificationItem(@PathVariable("classificationId") String classificationId, @PathVariable("itemId") String itemId) throws RmesException { + String classificationItem = classificationItemService.getClassificationItem(classificationId, itemId); + return ResponseEntity.status(HttpStatus.OK).body(classificationItem); } @PutMapping(value="/classification/{classificationId}/item/{itemId}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity updateClassificationItem( @PathVariable("classificationId") String classificationId, @PathVariable("itemId") String itemId, - @Parameter(description = "Classification to update", required = true, content = @Content(schema = @Schema(implementation = ClassificationItem.class))) @org.springframework.web.bind.annotation.RequestBody String body) { - try { - classificationItemService.updateClassificationItem(classificationId, itemId, body); - return ResponseEntity.status(HttpStatus.OK).body(itemId); - } catch (RmesException e) { - return returnRmesException(e); - } + @Parameter(description = "Classification to update", required = true, content = @Content(schema = @Schema(implementation = ClassificationItem.class))) @org.springframework.web.bind.annotation.RequestBody String body) throws RmesException { + classificationItemService.updateClassificationItem(classificationId, itemId, body); + return ResponseEntity.status(HttpStatus.OK).body(itemId); } @GetMapping(value="/classification/{classificationId}/item/{itemId}/notes/{conceptVersion}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getClassificationItemNotes(@PathVariable("classificationId") String classificationId, - @PathVariable("itemId") String itemId, @PathVariable("conceptVersion") int conceptVersion) { - try { - String notes = classificationItemService.getClassificationItemNotes(classificationId, itemId, conceptVersion); - return ResponseEntity.status(HttpStatus.OK).body(notes); - } catch (RmesException e) { - return returnRmesException(e); - } + @PathVariable("itemId") String itemId, @PathVariable("conceptVersion") int conceptVersion) throws RmesException { + String notes = classificationItemService.getClassificationItemNotes(classificationId, itemId, conceptVersion); + return ResponseEntity.status(HttpStatus.OK).body(notes); } @GetMapping(value="/classification/{classificationId}/item/{itemId}/narrowers", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getClassificationItemNarrowers(@PathVariable("classificationId") String classificationId, @PathVariable("itemId") String itemId) { - try { - String narrowers = classificationItemService.getClassificationItemNarrowers(classificationId, itemId); - return ResponseEntity.status(HttpStatus.OK).body(narrowers); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getClassificationItemNarrowers(@PathVariable("classificationId") String classificationId, @PathVariable("itemId") String itemId) throws RmesException { + String narrowers = classificationItemService.getClassificationItemNarrowers(classificationId, itemId); + return ResponseEntity.status(HttpStatus.OK).body(narrowers); } @GetMapping(value="/correspondences", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCorrespondences() { - try { - String correspondences = classificationsService.getCorrespondences(); - return ResponseEntity.status(HttpStatus.OK).body(correspondences); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getCorrespondences() throws RmesException { + String correspondences = classificationsService.getCorrespondences(); + return ResponseEntity.status(HttpStatus.OK).body(correspondences); } @GetMapping(value="/correspondence/{id}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCorrespondence(@PathVariable(Constants.ID) String id) { - try { - String correspondence = classificationsService.getCorrespondence(id); - return ResponseEntity.status(HttpStatus.OK).body(correspondence); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getCorrespondence(@PathVariable(Constants.ID) String id) throws RmesException { + String correspondence = classificationsService.getCorrespondence(id); + return ResponseEntity.status(HttpStatus.OK).body(correspondence); } @GetMapping(value="/correspondence/{id}/associations", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getCorrespondenceAssociations(@PathVariable(Constants.ID) String id) { - String jsonResultat; - try { - jsonResultat = classificationsService.getCorrespondenceAssociations(id); - } catch (RmesException e) { - return returnRmesException(e); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getCorrespondenceAssociations(@PathVariable(Constants.ID) String id) throws RmesException { + String associations = classificationsService.getCorrespondenceAssociations(id); + return ResponseEntity.status(HttpStatus.OK).body(associations); } @GetMapping(value="/correspondence/{correspondenceId}/association/{associationId}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getCorrespondenceItem(@PathVariable("correspondenceId") String correspondenceId, - @PathVariable("associationId") String associationId) { - String jsonResultat; - try { - jsonResultat = classificationsService.getCorrespondenceAssociation(correspondenceId, associationId); - } catch (RmesException e) { - return returnRmesException(e); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + @PathVariable("associationId") String associationId) throws RmesException { + String association = classificationsService.getCorrespondenceAssociation(correspondenceId, associationId); + return ResponseEntity.status(HttpStatus.OK).body(association); } + } diff --git a/src/main/java/fr/insee/rmes/webservice/codesLists/CodeListsResources.java b/src/main/java/fr/insee/rmes/webservice/codesLists/CodeListsResources.java index 8afd81dfc..787daeed0 100644 --- a/src/main/java/fr/insee/rmes/webservice/codesLists/CodeListsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/codesLists/CodeListsResources.java @@ -68,7 +68,7 @@ public ResponseEntity updateCodesList(@PathVariable(Constants.ID) @P("co @DeleteMapping(value = "/{id}") @Operation(operationId = "deleteCodeList", summary = "Delete a code list") public ResponseEntity deleteCodeList(@PathVariable(Constants.ID) @P("codesListId") String notation) throws RmesException { - codeListService.deleteCodeList(notation, false); + codeListService.deleteCodeList(notation, false); return ResponseEntity.status(HttpStatus.OK).build(); } @@ -170,7 +170,7 @@ public ResponseEntity getCodeByNotation(@PathVariable("notation") @PreAuthorize("isAdmin() || isContributorOfCodesList(#id)") - @PutMapping("/validate/{id}") + @PutMapping("/{id}/validate") @Operation(operationId = "publishFullCodeList", summary = "Publish a codelist") public ResponseEntity publishFullCodeList(@PathVariable(Constants.ID) Id id) throws RmesException { codeListService.publishCodeList(id.getIdentifier(), false); diff --git a/src/main/java/fr/insee/rmes/webservice/codesLists/PartialCodeListsResources.java b/src/main/java/fr/insee/rmes/webservice/codesLists/PartialCodeListsResources.java index 4a7ebdf09..b152906d9 100644 --- a/src/main/java/fr/insee/rmes/webservice/codesLists/PartialCodeListsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/codesLists/PartialCodeListsResources.java @@ -75,7 +75,7 @@ public ResponseEntity getPartialsByParent(@PathVariable("parentCode") St } @PreAuthorize("@AuthorizeMethodDecider.isAdmin()") - @PutMapping("/validate/{id}") + @PutMapping("/{id}/validate") @io.swagger.v3.oas.annotations.Operation(operationId = "publishPartialCodeList", summary = "Publish a partial codelist") public ResponseEntity publishPartialCodeList( @PathVariable(Constants.ID) String id) { diff --git a/src/main/java/fr/insee/rmes/webservice/ConceptsCollectionsResources.java b/src/main/java/fr/insee/rmes/webservice/concepts/ConceptsCollectionsResources.java similarity index 92% rename from src/main/java/fr/insee/rmes/webservice/ConceptsCollectionsResources.java rename to src/main/java/fr/insee/rmes/webservice/concepts/ConceptsCollectionsResources.java index e2164842a..57e4ad9d3 100644 --- a/src/main/java/fr/insee/rmes/webservice/ConceptsCollectionsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/concepts/ConceptsCollectionsResources.java @@ -1,4 +1,4 @@ -package fr.insee.rmes.webservice; +package fr.insee.rmes.webservice.concepts; import fr.insee.rmes.bauhaus_services.ConceptsCollectionService; import fr.insee.rmes.bauhaus_services.ConceptsService; @@ -35,7 +35,7 @@ @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "406", description = "Not Acceptable"), @ApiResponse(responseCode = "500", description = "Internal server error")}) -public class ConceptsCollectionsResources extends GenericResources { +public class ConceptsCollectionsResources { @Autowired public ConceptsCollectionsResources(ConceptsService conceptsService, ConceptsCollectionService conceptsCollectionService) { @@ -56,13 +56,9 @@ public enum Language { @GetMapping(value = "/collections", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getCollections", summary = "List of collections", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = IdLabel.class))))}) - public ResponseEntity getCollections() { - try { - String collections = conceptsCollectionService.getCollections(); - return ResponseEntity.status(HttpStatus.OK).body(collections); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getCollections() throws RmesException { + String collections = conceptsCollectionService.getCollections(); + return ResponseEntity.status(HttpStatus.OK).body(collections); } @GetMapping(value = "/export/{id}", produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE, "application/vnd.oasis.opendocument.text"}) diff --git a/src/main/java/fr/insee/rmes/webservice/ConceptsResources.java b/src/main/java/fr/insee/rmes/webservice/concepts/ConceptsResources.java similarity index 72% rename from src/main/java/fr/insee/rmes/webservice/ConceptsResources.java rename to src/main/java/fr/insee/rmes/webservice/concepts/ConceptsResources.java index d6f8b5362..851f24cf2 100644 --- a/src/main/java/fr/insee/rmes/webservice/ConceptsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/concepts/ConceptsResources.java @@ -1,4 +1,4 @@ -package fr.insee.rmes.webservice; +package fr.insee.rmes.webservice.concepts; import fr.insee.rmes.bauhaus_services.ConceptsCollectionService; import fr.insee.rmes.bauhaus_services.ConceptsService; @@ -40,7 +40,9 @@ @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "406", description = "Not Acceptable"), @ApiResponse(responseCode = "500", description = "Internal server error") }) -public class ConceptsResources extends GenericResources { + + +public class ConceptsResources { static final Logger logger = LoggerFactory.getLogger(ConceptsResources.class); @@ -56,25 +58,17 @@ public ConceptsResources(ConceptsService conceptsService, ConceptsCollectionServ @GetMapping(value="", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getConcepts", summary = "List of concepts", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=IdLabelAltLabel.class))))}) - public ResponseEntity getConcepts() { - try { - String jsonResultat = conceptsService.getConcepts(); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getConcepts() throws RmesException { + String concepts = conceptsService.getConcepts(); + return ResponseEntity.status(HttpStatus.OK).body(concepts); } @GetMapping(value = "/linkedConcepts/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getRelatedConcepts", summary = "List of concepts", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=IdLabel.class))))}) - public ResponseEntity getRelatedConcepts(@PathVariable(Constants.ID) String id) { - try { - String resultat = conceptsService.getRelatedConcepts(id); - return ResponseEntity.status(HttpStatus.OK).body(resultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getRelatedConcepts(@PathVariable(Constants.ID) String id) throws RmesException { + String concepts = conceptsService.getRelatedConcepts(id); + return ResponseEntity.status(HttpStatus.OK).body(concepts); } @@ -83,122 +77,82 @@ public ResponseEntity getRelatedConcepts(@PathVariable(Constants.ID) Str + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CREATOR)") @DeleteMapping(value="/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "deleteConcept", summary = "Delete a concept") - public ResponseEntity deleteConcept(@PathVariable(Constants.ID) String id) { - try { - conceptsService.deleteConcept(id); - return ResponseEntity.status(HttpStatus.OK).body(id); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity deleteConcept(@PathVariable(Constants.ID) String id) throws RmesException { + conceptsService.deleteConcept(id); + return ResponseEntity.status(HttpStatus.OK).body(id); } @GetMapping(value = "/advanced-search", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getConceptsSearch", summary = "Rich list of concepts", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=ConceptsSearch.class))))}) - public ResponseEntity getConceptsSearch() { - try { - String jsonResultat = conceptsService.getConceptsSearch(); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getConceptsSearch() throws RmesException { + String concepts = conceptsService.getConceptsSearch(); + return ResponseEntity.status(HttpStatus.OK).body(concepts); } @GetMapping(value = "/concept/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getConceptByID", summary = "Get a concept", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = ConceptById.class)))}) - public ResponseEntity getConceptByID(@PathVariable(Constants.ID) String id) { - try { - String jsonResultat = conceptsService.getConceptByID(id); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getConceptByID(@PathVariable(Constants.ID) String id) throws RmesException { + String concept = conceptsService.getConceptByID(id); + return ResponseEntity.status(HttpStatus.OK).body(concept); } @GetMapping(value = "/toValidate", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getConceptsToValidate", summary = "List of concepts to validate", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=ConceptsToValidate.class))))}) - public ResponseEntity getConceptsToValidate() { - try { - String jsonResultat = conceptsService.getConceptsToValidate(); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getConceptsToValidate() throws RmesException { + String concepts = conceptsService.getConceptsToValidate(); + return ResponseEntity.status(HttpStatus.OK).body(concepts); } @GetMapping(value = "/concept/{id}/links", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getConceptLinksByID", summary = "List of linked concepts", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=ConceptLinks.class))))}) - public ResponseEntity getConceptLinksByID(@PathVariable(Constants.ID) String id) { - try { - String jsonResultat = conceptsService.getConceptLinksByID(id); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getConceptLinksByID(@PathVariable(Constants.ID) String id) throws RmesException { + String conceptLinks = conceptsService.getConceptLinksByID(id); + return ResponseEntity.status(HttpStatus.OK).body(conceptLinks); } @GetMapping(value = "/concept/{id}/notes/{conceptVersion}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getConceptNotesByID", summary = "Last notes of the concept", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = ConceptNotes.class)))}) - public ResponseEntity getConceptNotesByID(@PathVariable(Constants.ID) String id, @PathVariable("conceptVersion") int conceptVersion) { - try { - String notes = conceptsService.getConceptNotesByID(id, conceptVersion); - return ResponseEntity.status(HttpStatus.OK).body(notes); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getConceptNotesByID(@PathVariable(Constants.ID) String id, @PathVariable("conceptVersion") int conceptVersion) throws RmesException { + String notes = conceptsService.getConceptNotesByID(id, conceptVersion); + return ResponseEntity.status(HttpStatus.OK).body(notes); } @GetMapping(value = "/collections/dashboard", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getCollectionsDashboard", summary = "Rich list of collections", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=IdLabel.class))))}) - public ResponseEntity getCollectionsDashboard() { - try { - String jsonResultat = conceptsCollectionService.getCollectionsDashboard(); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getCollectionsDashboard() throws RmesException { + String collections = conceptsCollectionService.getCollectionsDashboard(); + return ResponseEntity.status(HttpStatus.OK).body(collections); } @GetMapping(value = "/collections/toValidate", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getCollectionsToValidate", summary = "List of collections to validate", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=CollectionsToValidate.class))))}) - public ResponseEntity getCollectionsToValidate() { - try { - String jsonResultat = conceptsService.getCollectionsToValidate(); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getCollectionsToValidate() throws RmesException { + String collections = conceptsService.getCollectionsToValidate(); + return ResponseEntity.status(HttpStatus.OK).body(collections); } @GetMapping(value = "/collection/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getCollectionByID", summary = "Get a collection by its identifier", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = CollectionById.class)))}) - public ResponseEntity getCollectionByID(@PathVariable(Constants.ID) String id) { - try { - String collection = conceptsCollectionService.getCollectionByID(id); - return ResponseEntity.status(HttpStatus.OK).body(collection); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getCollectionByID(@PathVariable(Constants.ID) String id) throws RmesException { + String collection = conceptsCollectionService.getCollectionByID(id); + return ResponseEntity.status(HttpStatus.OK).body(collection); } @GetMapping(value = "/collection/{id}/members", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getCollectionMembersByID", summary = "List of collection member concepts", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=CollectionMembers.class))))}) - public ResponseEntity getCollectionMembersByID(@PathVariable(Constants.ID) String id) { - try { - String jsonResultat = conceptsCollectionService.getCollectionMembersByID(id); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getCollectionMembersByID(@PathVariable(Constants.ID) String id) throws RmesException { + String collectionMembers = conceptsCollectionService.getCollectionMembersByID(id); + return ResponseEntity.status(HttpStatus.OK).body(collectionMembers); } @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " @@ -206,13 +160,9 @@ public ResponseEntity getCollectionMembersByID(@PathVariable(Constants.I @PostMapping(value = "/concept", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setConcept", summary = "Create concept" ) public ResponseEntity setConcept( - @Parameter(description = "Concept", required = true) @RequestBody String body) { - try { - String id = conceptsService.setConcept(body); - return ResponseEntity.status(HttpStatus.OK).body(id); - } catch (RmesException e) { - return returnRmesException(e); - } + @Parameter(description = "Concept", required = true) @RequestBody String body) throws RmesException { + String id = conceptsService.setConcept(body); + return ResponseEntity.status(HttpStatus.OK).body(id); } //TODO Test with Roles.ADMIN, Roles.CONCEPT_CONTRIBUTOR (user stamp is contributor and user stamp is not contributor) : StampRestrictionsServiceImpl.isConceptManager @@ -222,30 +172,22 @@ public ResponseEntity setConcept( @Operation(operationId = "setConceptById", summary = "Update a concept") public ResponseEntity setConcept( @Parameter(description = "Id", required = true) @PathVariable(Constants.ID) String id, - @Parameter(description = "Concept", required = true) @RequestBody String body) { - try { - conceptsService.setConcept(id, body); - logger.info("Concept updated : {}" , id); - return ResponseEntity.noContent().build(); - } catch (RmesException e) { - return returnRmesException(e); - } + @Parameter(description = "Concept", required = true) @RequestBody String body) throws RmesException { + conceptsService.setConcept(id, body); + logger.info("Concept updated : {}" , id); + return ResponseEntity.noContent().build(); } //TODO Test with admin and with concept_creator (user stamp is creator of all concepts, user stamp is not creator of one concept) @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).CONCEPT_CREATOR)") - @PutMapping(value= "/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value= "/{id}/validate", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setConceptsValidation", summary = "Concepts validation") public ResponseEntity setConceptsValidation( @Parameter(description = "Id, put '0' if multiple ids", required = true) @PathVariable(Constants.ID) String id, - @Parameter(description = "Concept ids", required = true) @RequestBody String body) { - try { - conceptsService.setConceptsValidation(body); - return ResponseEntity.noContent().build(); - } catch (RmesException e) { - return returnRmesException(e); - } + @Parameter(description = "Concept ids", required = true) @RequestBody String body) throws RmesException { + conceptsService.setConceptsValidation(body); + return ResponseEntity.noContent().build(); } @GetMapping(value = "/collection/export/{id}", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE, "application/vnd.oasis.opendocument.text" }) @@ -277,13 +219,9 @@ public void exportZipConcept( @PostMapping(value = "/collection", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCollection", summary = "Create collection") public ResponseEntity setCollection( - @Parameter(description = "Collection", required = true) @RequestBody String body) { - try { - conceptsService.setCollection(body); - return ResponseEntity.noContent().build(); - } catch (RmesException e) { - return returnRmesException(e); - } + @Parameter(description = "Collection", required = true) @RequestBody String body) throws RmesException { + conceptsService.setCollection(body); + return ResponseEntity.noContent().build(); } @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " @@ -294,30 +232,20 @@ public ResponseEntity setCollection( public ResponseEntity setCollection( @Parameter(description = "Id", required = true) @PathVariable(Constants.ID) String id, @Parameter(description = "Collection", required = true) @RequestBody String body) throws RmesException { - try { - conceptsService.setCollection(id, body); - logger.info("Update collection : {}" , id); - return ResponseEntity.noContent().build(); - } catch (RmesException e) { - logger.error(e.getMessage(), e); - throw e; - } + conceptsService.setCollection(id, body); + logger.info("Update collection : {}" , id); + return ResponseEntity.noContent().build(); } @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).COLLECTION_CREATOR)") - @PutMapping(value= "/collections/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value= "/collections/{id}/validate", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setCollectionsValidation", summary = "Collections validation") public ResponseEntity setCollectionsValidation( @Parameter(description = "Id, put '0' if multiple ids", required = true) @PathVariable(Constants.ID) String id, @Parameter(description = "Collection id array to validate", required = true) @RequestBody String body) throws RmesException { - try { - conceptsService.setCollectionsValidation(body); - logger.info("Validated concepts : {}" , body); - return ResponseEntity.noContent().build(); - } catch (RmesException e) { - logger.error(e.getMessage(), e); - throw e; - } + conceptsService.setCollectionsValidation(body); + logger.info("Validated concepts : {}" , body); + return ResponseEntity.noContent().build(); } } diff --git a/src/main/java/fr/insee/rmes/webservice/dataset/DatasetResources.java b/src/main/java/fr/insee/rmes/webservice/datasets/DatasetResources.java similarity index 99% rename from src/main/java/fr/insee/rmes/webservice/dataset/DatasetResources.java rename to src/main/java/fr/insee/rmes/webservice/datasets/DatasetResources.java index bfb531e04..bb1ada9f6 100644 --- a/src/main/java/fr/insee/rmes/webservice/dataset/DatasetResources.java +++ b/src/main/java/fr/insee/rmes/webservice/datasets/DatasetResources.java @@ -1,4 +1,4 @@ -package fr.insee.rmes.webservice.dataset; +package fr.insee.rmes.webservice.datasets; import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.datasets.DatasetService; @@ -72,7 +72,6 @@ public String setDataset( public String setDataset( @PathVariable("id") String datasetId, @Parameter(description = "Dataset", required = true) @RequestBody String body) throws RmesException { - return this.datasetService.update(datasetId, body); } diff --git a/src/main/java/fr/insee/rmes/webservice/distribution/DistributionResources.java b/src/main/java/fr/insee/rmes/webservice/datasets/DistributionResources.java similarity index 99% rename from src/main/java/fr/insee/rmes/webservice/distribution/DistributionResources.java rename to src/main/java/fr/insee/rmes/webservice/datasets/DistributionResources.java index 48fda9c5e..2f0d6ddd3 100644 --- a/src/main/java/fr/insee/rmes/webservice/distribution/DistributionResources.java +++ b/src/main/java/fr/insee/rmes/webservice/datasets/DistributionResources.java @@ -1,4 +1,4 @@ -package fr.insee.rmes.webservice.distribution; +package fr.insee.rmes.webservice.datasets; import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.datasets.DatasetService; diff --git a/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java b/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java index ac5001049..bc2efdde0 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/FamilyResources.java @@ -1,11 +1,12 @@ package fr.insee.rmes.webservice.operations; import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; +import fr.insee.rmes.bauhaus_services.OperationsService; import fr.insee.rmes.config.swagger.model.IdLabel; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.Family; import fr.insee.rmes.model.operations.Operation; -import fr.insee.rmes.webservice.OperationsCommonResources; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; @@ -21,18 +22,29 @@ import org.springframework.web.bind.annotation.*; -/*************************************************************************************************** - * FAMILY - ******************************************************************************************************/ - @Qualifier("Family") @RestController @SecurityRequirement(name = "bearerAuth") -@RequestMapping(value = "/operations", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }) +@RequestMapping( + value = "/operations", + produces = { + MediaType.APPLICATION_JSON_VALUE, + MediaType.TEXT_PLAIN_VALUE + } +) @ConditionalOnExpression("'${fr.insee.rmes.bauhaus.activeModules}'.contains('operations')") -public class FamilyResources extends OperationsCommonResources { +public class FamilyResources { + + protected final OperationsService operationsService; + + protected final OperationsDocumentationsService documentationsService; + + public FamilyResources(OperationsService operationsService, OperationsDocumentationsService documentationsService) { + this.operationsService = operationsService; + this.documentationsService = documentationsService; + } + - @GetMapping("/families") @io.swagger.v3.oas.annotations.Operation(operationId = "getFamilies", summary = "List of families", responses = {@ApiResponse(content=@Content(array=@ArraySchema(schema=@Schema(implementation=IdLabel.class))))}) @@ -51,13 +63,9 @@ public ResponseEntity getFamiliesForSearch() throws RmesException { @GetMapping("/families/{id}/seriesWithReport") @io.swagger.v3.oas.annotations.Operation(operationId = "getSeriesWithReport", summary = "Series with metadataReport", responses = {@ApiResponse(content=@Content(schema=@Schema(type="array",implementation= Operation.class)))}) - public ResponseEntity getSeriesWithReport(@PathVariable(Constants.ID) String id) { - try { - String series = operationsService.getSeriesWithReport(id); - return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(series); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getSeriesWithReport(@PathVariable(Constants.ID) String id) throws RmesException { + String series = operationsService.getSeriesWithReport(id); + return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(series); } @GetMapping("/family/{id}") @@ -74,12 +82,8 @@ public ResponseEntity getFamilyByID(@PathVariable(Constants.ID) String i @io.swagger.v3.oas.annotations.Operation(operationId = "setFamilyById", summary = "Update an existing family" ) public ResponseEntity setFamilyById( @PathVariable(Constants.ID) String id, - @Parameter(description = "Family to update", required = true, content = @Content(schema = @Schema(implementation = Family.class))) @RequestBody String body) { - try { - operationsService.setFamily(id, body); - } catch (RmesException e) { - return returnRmesException(e); - } + @Parameter(description = "Family to update", required = true, content = @Content(schema = @Schema(implementation = Family.class))) @RequestBody String body) throws RmesException { + operationsService.setFamily(id, body); return ResponseEntity.status(HttpStatus.OK).body(id); } @@ -89,25 +93,17 @@ public ResponseEntity setFamilyById( @io.swagger.v3.oas.annotations.Operation(operationId = "createFamily", summary = "Create a new family") public ResponseEntity createFamily( @Parameter(description = "Family to create", required = true, content = @Content(schema = @Schema(implementation = Family.class))) - @RequestBody String body) { - try { - String id = operationsService.createFamily(body); - return ResponseEntity.status(HttpStatus.OK).body(id); - } catch (RmesException e) { - return returnRmesException(e); - } + @RequestBody String body) throws RmesException { + String id = operationsService.createFamily(body); + return ResponseEntity.status(HttpStatus.OK).body(id); } @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") - @PutMapping("/family/validate/{id}") + @PutMapping("/family/{id}/validate") @io.swagger.v3.oas.annotations.Operation(operationId = "setFamilyValidation", summary = "Validate a family") public ResponseEntity setFamilyValidation( - @PathVariable(Constants.ID) String id) { - try { - operationsService.setFamilyValidation(id); - return ResponseEntity.status(HttpStatus.OK).body(id); - } catch (RmesException e) { - return returnRmesException(e); - } + @PathVariable(Constants.ID) String id) throws RmesException { + operationsService.setFamilyValidation(id); + return ResponseEntity.status(HttpStatus.OK).body(id); } } diff --git a/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java b/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java index 0440b6dd4..d4bbb64ff 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/IndicatorsResources.java @@ -1,12 +1,13 @@ package fr.insee.rmes.webservice.operations; import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; +import fr.insee.rmes.bauhaus_services.OperationsService; import fr.insee.rmes.config.swagger.model.IdLabelAltLabel; import fr.insee.rmes.config.swagger.model.IdLabelAltLabelSims; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.Indicator; import fr.insee.rmes.utils.XMLUtils; -import fr.insee.rmes.webservice.OperationsCommonResources; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @@ -26,19 +27,22 @@ @SecurityRequirement(name = "bearerAuth") @RequestMapping(value="/operations") @ConditionalOnExpression("'${fr.insee.rmes.bauhaus.activeModules}'.contains('operations')") -public class IndicatorsResources extends OperationsCommonResources { +public class IndicatorsResources { + protected final OperationsService operationsService; + + protected final OperationsDocumentationsService documentationsService; + + public IndicatorsResources(OperationsService operationsService, OperationsDocumentationsService documentationsService) { + this.operationsService = operationsService; + this.documentationsService = documentationsService; + } - - /*************************************************************************************************** - * INDICATORS - ******************************************************************************************************/ @GetMapping(value="/indicators", produces=MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "getIndicators", summary = "List of indicators", responses = {@ApiResponse(content=@Content(schema=@Schema(type="array",implementation=IdLabelAltLabel.class)))}) public ResponseEntity getIndicators() throws RmesException { String indicators = operationsService.getIndicators(); return ResponseEntity.status(HttpStatus.OK).body(indicators); - } @GetMapping(value="/indicators/withSims",produces= MediaType.APPLICATION_JSON_VALUE) @@ -61,22 +65,13 @@ public ResponseEntity getIndicatorsForSearch() throws RmesException { @io.swagger.v3.oas.annotations.Operation(operationId = "getIndicatorByID", summary = "Get an indicator", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = Indicator.class)))}) public ResponseEntity getIndicatorByID(@PathVariable(Constants.ID) String id, - @Parameter(hidden = true)@RequestHeader(required=false) String accept) { - String indicator; + @Parameter(hidden = true)@RequestHeader(required=false) String accept) throws RmesException { + if (accept != null && accept.equals(MediaType.APPLICATION_XML_VALUE)) { - try { - indicator=XMLUtils.produceXMLResponse(operationsService.getIndicatorById(id)); - } catch (RmesException e) { - return returnRmesException(e); - } + return ResponseEntity.status(HttpStatus.OK).body(XMLUtils.produceXMLResponse(operationsService.getIndicatorById(id))); } else { - try { - indicator = operationsService.getIndicatorJsonByID(id); - } catch (RmesException e) { - return returnRmesException(e); - } + return ResponseEntity.status(HttpStatus.OK).body(operationsService.getIndicatorJsonByID(id)); } - return ResponseEntity.status(HttpStatus.OK).body(indicator); } //TODO Test : admin then INDICATOR_CONTRIBUTOR with stamp fit then not @@ -86,25 +81,19 @@ public ResponseEntity getIndicatorByID(@PathVariable(Constants.ID) Strin public ResponseEntity setIndicatorById( @PathVariable(Constants.ID) String id, @Parameter(description = "Indicator to update", required = true, - content = @Content(schema = @Schema(implementation = Indicator.class))) @RequestBody String body) { - try { - operationsService.setIndicator(id, body); - } catch (RmesException e) { - return returnRmesException(e); - } + content = @Content(schema = @Schema(implementation = Indicator.class))) @RequestBody String body) throws RmesException { + + operationsService.setIndicator(id, body); return ResponseEntity.noContent().build(); } @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN , T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR)") - @PutMapping(value="/indicator/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value="/indicator/{id}/validate", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setIndicatorValidation", summary = "Indicator validation") public ResponseEntity setIndicatorValidation( - @PathVariable(Constants.ID) String id) { - try { - operationsService.setIndicatorValidation(id); - } catch (RmesException e) { - return returnRmesException(e); - } + @PathVariable(Constants.ID) String id) throws RmesException { + + operationsService.setIndicatorValidation(id); return ResponseEntity.status(HttpStatus.OK).body(id); } @@ -114,15 +103,9 @@ public ResponseEntity setIndicatorValidation( responses = { @ApiResponse(content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))}) public ResponseEntity setIndicator( @Parameter(description = "Indicator to create", required = true, - content = @Content(schema = @Schema(implementation = Indicator.class))) @RequestBody String body) { - logger.info("POST indicator"); - String id; - try { - id = operationsService.setIndicator(body); - } catch (RmesException e) { - return returnRmesException(e); - } - if (id == null) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(id);} + + content = @Content(schema = @Schema(implementation = Indicator.class))) @RequestBody String body) throws RmesException { + String id = operationsService.setIndicator(body); return ResponseEntity.status(HttpStatus.OK).body(id); } } diff --git a/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java b/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java index 098fcbeb0..5f1902ea4 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/MetadataReportResources.java @@ -1,13 +1,14 @@ package fr.insee.rmes.webservice.operations; import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; +import fr.insee.rmes.bauhaus_services.OperationsService; import fr.insee.rmes.config.swagger.model.Accept; import fr.insee.rmes.config.swagger.model.operations.documentation.Attribute; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.documentations.Documentation; import fr.insee.rmes.model.operations.documentations.MAS; import fr.insee.rmes.utils.XMLUtils; -import fr.insee.rmes.webservice.OperationsCommonResources; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; @@ -30,12 +31,17 @@ @SecurityRequirement(name = "bearerAuth") @RequestMapping("/operations") @ConditionalOnExpression("'${fr.insee.rmes.bauhaus.activeModules}'.contains('operations')") -public class MetadataReportResources extends OperationsCommonResources { +public class MetadataReportResources { + protected final OperationsService operationsService; + + protected final OperationsDocumentationsService documentationsService; + + public MetadataReportResources(OperationsService operationsService, OperationsDocumentationsService documentationsService) { + this.operationsService = operationsService; + this.documentationsService = documentationsService; + } - /*************************************************************************************************** - * DOCUMENTATION - ******************************************************************************************************/ @GetMapping( value = "/metadataStructureDefinition", @@ -53,48 +59,35 @@ public class MetadataReportResources extends OperationsCommonResources { ) public ResponseEntity getMSD( @Parameter(hidden = true) @RequestHeader(required=false) String accept - ) { + ) throws RmesException { Accept acceptHeader = Accept.fromMediaType(accept); - try { - return switch (acceptHeader) { - case XML -> { - var msd = documentationsService.getMSD(); - yield ResponseEntity.ok(XMLUtils.produceResponse(msd, String.valueOf(accept))); - } - case JSON -> { - var jsonResultat = documentationsService.getMSDJson(); - yield ResponseEntity.ok(jsonResultat); - } - default -> ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).build(); - }; - } catch (RmesException e) { - return returnRmesException(e); - } - + return switch (acceptHeader) { + case XML -> { + var msd = documentationsService.getMSD(); + yield ResponseEntity.ok(XMLUtils.produceResponse(msd, String.valueOf(accept))); + } + case JSON -> { + var jsonResultat = documentationsService.getMSDJson(); + yield ResponseEntity.ok(jsonResultat); + } + default -> ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).build(); + }; } @GetMapping(value = "/metadataAttribute/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getMA", summary = "Metadata attribute specification and property", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = Attribute.class)))}) - public ResponseEntity getMetadataAttribute(@PathVariable(Constants.ID) String id) { - try { - String metadataAttribute = documentationsService.getMetadataAttribute(id); - return ResponseEntity.ok(metadataAttribute); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getMetadataAttribute(@PathVariable(Constants.ID) String id) throws RmesException { + String metadataAttribute = documentationsService.getMetadataAttribute(id); + return ResponseEntity.ok(metadataAttribute); } @GetMapping(value = "/metadataAttributes", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getMAs", summary = "Metadata attributes specification and property", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(type="array",implementation = Attribute.class)))}) - public ResponseEntity getMetadataAttributes() { - try { - String metadataAttribute = documentationsService.getMetadataAttributes(); - return ResponseEntity.ok(metadataAttribute); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getMetadataAttributes() throws RmesException { + String metadataAttribute = documentationsService.getMetadataAttributes(); + return ResponseEntity.ok(metadataAttribute); } @@ -102,13 +95,9 @@ public ResponseEntity getMetadataAttributes() { @Operation(operationId = "getMetadataReport", summary = "Metadata report for an id", responses = { @ApiResponse(content = @Content(mediaType = "application/json" , schema = @Schema(implementation = Documentation.class) ))}) - public ResponseEntity getMetadataReport(@PathVariable(Constants.ID) String id) { - try { - String metadataReport = documentationsService.getMetadataReport(id); - return ResponseEntity.ok(metadataReport); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getMetadataReport(@PathVariable(Constants.ID) String id) throws RmesException { + String metadataReport = documentationsService.getMetadataReport(id); + return ResponseEntity.ok(metadataReport); } @GetMapping(value = "/metadataReport/default", produces = MediaType.APPLICATION_JSON_VALUE) @@ -129,23 +118,19 @@ public ResponseEntity getFullSims( required = true, schema = @Schema(pattern = "[0-9]{4}", type = "string")) @PathVariable(Constants.ID) String id, @Parameter(hidden = true) @RequestHeader(required=false) String accept - ) { + ) throws RmesException { Accept acceptHeader = Accept.fromMediaType(accept); - try { - return switch (acceptHeader) { - case XML -> { - var documentation = documentationsService.getFullSimsForXml(id); - yield ResponseEntity.ok(XMLUtils.produceResponse(documentation, accept)); - } - case JSON -> { - var jsonResultat = documentationsService.getFullSimsForJson(id); - yield ResponseEntity.ok(jsonResultat); - } - default -> ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).build(); - }; - } catch (RmesException e) { - return returnRmesException(e); - } + return switch (acceptHeader) { + case XML -> { + var documentation = documentationsService.getFullSimsForXml(id); + yield ResponseEntity.ok(XMLUtils.produceResponse(documentation, accept)); + } + case JSON -> { + var jsonResultat = documentationsService.getFullSimsForJson(id); + yield ResponseEntity.ok(jsonResultat); + } + default -> ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).build(); + }; } /** @@ -157,13 +142,9 @@ public ResponseEntity getFullSims( @Operation(operationId = "getMetadataReport", summary = "Owner stamp for a Metadata report's id", responses = { @ApiResponse(content = @Content(mediaType = "application/json" , schema = @Schema(implementation = Documentation.class) ))}) - public ResponseEntity getMetadataReportOwner(@PathVariable(Constants.ID) String id) { - try { - String metadataReportOwner = documentationsService.getMetadataReportOwner(id); - return ResponseEntity.status(HttpStatus.OK).body(metadataReportOwner); - } catch (RmesException e) { - return returnRmesException(e); - } + public ResponseEntity getMetadataReportOwner(@PathVariable(Constants.ID) String id) throws RmesException { + String metadataReportOwner = documentationsService.getMetadataReportOwner(id); + return ResponseEntity.status(HttpStatus.OK).body(metadataReportOwner); } /** @@ -177,15 +158,10 @@ public ResponseEntity getMetadataReportOwner(@PathVariable(Constants.ID) responses = { @ApiResponse(content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))}) public ResponseEntity setMetadataReport( @Parameter(description = "Metadata report to create", required = true, - content = @Content(schema = @Schema(implementation = Documentation.class))) @RequestBody String body) { - logger.info("POST Metadata report"); - try { - String id = documentationsService.createMetadataReport(body); - if (id == null) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(id);} - return ResponseEntity.status(HttpStatus.OK).body(id); - } catch (RmesException e) { - return returnRmesException(e); - } + content = @Content(schema = @Schema(implementation = Documentation.class))) @RequestBody String body) throws RmesException { + String id = documentationsService.createMetadataReport(body); + if (id == null) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(id);} + return ResponseEntity.status(HttpStatus.OK).body(id); } /** @@ -203,13 +179,9 @@ public ResponseEntity setMetadataReport( public ResponseEntity setMetadataReportById( @PathVariable(Constants.ID) String id, @Parameter(description = "Report to update", required = true, - content = @Content(schema = @Schema(implementation = Documentation.class))) @RequestBody String body) { - try { - documentationsService.setMetadataReport(id, body); - return ResponseEntity.noContent().build(); - } catch (RmesException e) { - return returnRmesException(e); - } + content = @Content(schema = @Schema(implementation = Documentation.class))) @RequestBody String body) throws RmesException { + documentationsService.setMetadataReport(id, body); + return ResponseEntity.noContent().build(); } /** @@ -221,15 +193,9 @@ public ResponseEntity setMetadataReportById( @DeleteMapping(value = "/metadataReport/delete/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "deleteMetadataReportById", summary = "Delete metadata report") public ResponseEntity deleteMetadataReportById( - @PathVariable(Constants.ID) String id) { - try { - HttpStatus result = HttpStatus.NO_CONTENT; - result = documentationsService.deleteMetadataReport(id); - return ResponseEntity.status(result.value()).build(); - - } catch (RmesException e) { - return returnRmesException(e); - } + @PathVariable(Constants.ID) String id) throws RmesException { + HttpStatus result = documentationsService.deleteMetadataReport(id); + return ResponseEntity.status(result.value()).build(); } @@ -242,7 +208,7 @@ public ResponseEntity deleteMetadataReportById( @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).INDICATOR_CONTRIBUTOR " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") - @PutMapping(value = "/metadataReport/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value = "/metadataReport/{id}/validate", consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setMetadataReportValidation", summary = "Sims validation") public ResponseEntity setSimsValidation( @PathVariable(Constants.ID) String id) throws RmesException { @@ -330,11 +296,7 @@ public ResponseEntity getSimsExportFiles(@Parameter( description = "Version anglaise" ) @RequestParam(name = "lg2", defaultValue = "true") boolean lg2 - ) { - try { - return documentationsService.exportMetadataReportTempFiles(id,includeEmptyMas,lg1,lg2); - } catch (RmesException e) { - return ResponseEntity.badRequest().build(); - } + ) throws RmesException { + return documentationsService.exportMetadataReportTempFiles(id,includeEmptyMas,lg1,lg2); } } diff --git a/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java b/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java index b02969437..31709a690 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/OperationsResources.java @@ -1,10 +1,11 @@ package fr.insee.rmes.webservice.operations; import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; +import fr.insee.rmes.bauhaus_services.OperationsService; import fr.insee.rmes.config.swagger.model.IdLabelAltLabel; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.Operation; -import fr.insee.rmes.webservice.OperationsCommonResources; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @@ -23,7 +24,16 @@ @SecurityRequirement(name = "bearerAuth") @RequestMapping("/operations") @ConditionalOnExpression("'${fr.insee.rmes.bauhaus.activeModules}'.contains('operations')") -public class OperationsResources extends OperationsCommonResources { +public class OperationsResources { + + protected final OperationsService operationsService; + + protected final OperationsDocumentationsService documentationsService; + + public OperationsResources(OperationsService operationsService, OperationsDocumentationsService documentationsService) { + this.operationsService = operationsService; + this.documentationsService = documentationsService; + } @GetMapping(value = "/operations", produces = MediaType.APPLICATION_JSON_VALUE) @@ -67,7 +77,7 @@ public ResponseEntity createOperation( } @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") - @PutMapping(value = "/operation/validate/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value = "/operation/{id}/validate", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setOperationValidation", summary = "Operation validation") public ResponseEntity setOperationValidation(@PathVariable(Constants.ID) String id) throws RmesException { operationsService.setOperationValidation(id); diff --git a/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java b/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java index f57dd2424..32cb7d5b2 100644 --- a/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java +++ b/src/main/java/fr/insee/rmes/webservice/operations/SeriesResources.java @@ -1,13 +1,14 @@ package fr.insee.rmes.webservice.operations; import fr.insee.rmes.bauhaus_services.Constants; +import fr.insee.rmes.bauhaus_services.OperationsDocumentationsService; +import fr.insee.rmes.bauhaus_services.OperationsService; import fr.insee.rmes.config.swagger.model.IdLabelAltLabel; import fr.insee.rmes.config.swagger.model.IdLabelAltLabelSims; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.operations.Operation; import fr.insee.rmes.model.operations.Series; import fr.insee.rmes.utils.XMLUtils; -import fr.insee.rmes.webservice.OperationsCommonResources; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @@ -28,58 +29,49 @@ @SecurityRequirement(name = "bearerAuth") @RequestMapping("/operations") @ConditionalOnExpression("'${fr.insee.rmes.bauhaus.activeModules}'.contains('operations')") -public class SeriesResources extends OperationsCommonResources { +public class SeriesResources { + + protected final OperationsService operationsService; + + protected final OperationsDocumentationsService documentationsService; + + public SeriesResources(OperationsService operationsService, OperationsDocumentationsService documentationsService) { + this.operationsService = operationsService; + this.documentationsService = documentationsService; + } + - - /*************************************************************************************************** - * SERIES - ******************************************************************************************************/ @GetMapping(value = "/series", produces = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "getSeries", summary = "List of series", responses = {@ApiResponse(content=@Content(schema=@Schema(type="array",implementation=IdLabelAltLabel.class)))}) public ResponseEntity getSeries() throws RmesException { - String jsonResultat = operationsService.getSeries(); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + String series = operationsService.getSeries(); + return ResponseEntity.status(HttpStatus.OK).body(series); } @GetMapping(value = "/series/withSims", produces = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "getSeriesWithSims", summary = "List of series with related sims", responses = {@ApiResponse(content=@Content(schema=@Schema(type="array",implementation=IdLabelAltLabelSims.class)))}) public ResponseEntity getSeriesWIthSims() throws RmesException { - String jsonResultat = operationsService.getSeriesWithSims(); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + String series = operationsService.getSeriesWithSims(); + return ResponseEntity.status(HttpStatus.OK).body(series); } @GetMapping(value = "/series/{id}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @io.swagger.v3.oas.annotations.Operation(operationId = "getSeriesByID", summary = "Get a series", responses = { @ApiResponse(content = @Content(schema = @Schema(implementation = Series.class)))}) public ResponseEntity getSeriesByID(@PathVariable(Constants.ID) String id, - @Parameter(hidden = true) @RequestHeader(required=false) String accept) { - String resultat; + @Parameter(hidden = true) @RequestHeader(required=false) String accept) throws RmesException { if (accept != null && accept.equals(MediaType.APPLICATION_XML_VALUE)) { - try { - resultat=XMLUtils.produceXMLResponse(operationsService.getSeriesByID(id)); - } catch (RmesException e) { - return returnRmesException(e); - } + return ResponseEntity.status(HttpStatus.OK).body(XMLUtils.produceXMLResponse(operationsService.getSeriesByID(id))); } else { - try { - resultat = operationsService.getSeriesJsonByID(id); - } catch (RmesException e) { - return returnRmesException(e); - } + return ResponseEntity.status(HttpStatus.OK).body(operationsService.getSeriesJsonByID(id)); } - return ResponseEntity.status(HttpStatus.OK).body(resultat); } @GetMapping(value = "/series/advanced-search", produces = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "getSeriesForSearch", summary = "Series", responses = { @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = Series.class)))}) - public ResponseEntity getSeriesForSearch() { - String jsonResultat; - try { - jsonResultat = operationsService.getSeriesForSearch(); - } catch (RmesException e) { - return returnRmesException(e); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getSeriesForSearch() throws RmesException { + String series = operationsService.getSeriesForSearch(); + return ResponseEntity.status(HttpStatus.OK).body(series); } /** @@ -93,8 +85,8 @@ public ResponseEntity getSeriesForSearchWithStamps(@Parameter( required = true, schema = @Schema(pattern = "([A-Za-z0-9_-]+)", type = "string")) @PathVariable(Constants.STAMP) String stamp ) throws RmesException { - String jsonResultat = operationsService.getSeriesForSearchWithStamp(stamp); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + String series = operationsService.getSeriesForSearchWithStamp(stamp); + return ResponseEntity.status(HttpStatus.OK).body(series); } @PreAuthorize("isAdmin() || isContributorOfSerie(#seriesId)") @@ -104,78 +96,45 @@ public ResponseEntity getSeriesForSearchWithStamps(@Parameter( public ResponseEntity setSeriesById( @PathVariable(Constants.ID) @P("seriesId") String id, @Parameter(description = "Series to update", required = true, - content = @Content(schema = @Schema(implementation = Series.class))) @RequestBody String body) { - try { - operationsService.setSeries(id, body); - } catch (RmesException e) { - return returnRmesException(e); - } + content = @Content(schema = @Schema(implementation = Series.class))) @RequestBody String body) throws RmesException { + operationsService.setSeries(id, body); return ResponseEntity.ok(id); } @GetMapping(value = "/series/{id}/operationsWithoutReport", produces = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "getOperationsWithoutReport", summary = "Operations without metadataReport", responses = {@ApiResponse(content=@Content(schema=@Schema(type="array",implementation=Operation.class)))}) - public ResponseEntity getOperationsWithoutReport(@PathVariable(Constants.ID) String id) { - String jsonResultat; - try { - jsonResultat = operationsService.getOperationsWithoutReport(id); - } catch (RmesException e) { - return returnRmesException(e); } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getOperationsWithoutReport(@PathVariable(Constants.ID) String id) throws RmesException { + String operations = operationsService.getOperationsWithoutReport(id); + return ResponseEntity.status(HttpStatus.OK).body(operations); } @GetMapping(value = "/series/{id}/operationsWithReport", produces = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "getOperationsWithReport", summary = "Operations with metadataReport", responses = {@ApiResponse(content=@Content(schema=@Schema(type="array",implementation=Operation.class)))}) - public ResponseEntity getOperationsWithReport(@PathVariable(Constants.ID) String id) { - String jsonResultat; - try { - jsonResultat = operationsService.getOperationsWithReport(id); - } catch (RmesException e) { - return returnRmesException(e); - } - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + public ResponseEntity getOperationsWithReport(@PathVariable(Constants.ID) String id) throws RmesException { + String operations = operationsService.getOperationsWithReport(id); + return ResponseEntity.status(HttpStatus.OK).body(operations); } - - /** - * CREATE - * @param body - * @return response - */ @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN)") @PostMapping(value = "/series", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "createSeries", summary = "Create series") public ResponseEntity createSeries( @Parameter(description = "Series to create", required = true, - content = @Content(schema = @Schema(implementation = Series.class))) @RequestBody String body) { - String id; - try { - id = operationsService.createSeries(body); - } catch (RmesException e) { - return returnRmesException(e) ; - } + content = @Content(schema = @Schema(implementation = Series.class))) @RequestBody String body) throws RmesException { + String id = operationsService.createSeries(body); return ResponseEntity.status(HttpStatus.OK).body(id); } - /** - * PUBLISH - * @param id - * @return response - */ @PreAuthorize("hasAnyRole(T(fr.insee.rmes.config.auth.roles.Roles).ADMIN " + ", T(fr.insee.rmes.config.auth.roles.Roles).SERIES_CONTRIBUTOR)") - @PutMapping(value = "/series/validate/{id}", + @PutMapping(value = "/series/{id}/validate", consumes = MediaType.APPLICATION_JSON_VALUE) @io.swagger.v3.oas.annotations.Operation(operationId = "setSeriesValidation", summary = "Series validation") public ResponseEntity setSeriesValidation( - @PathVariable(Constants.ID) String id) { - try { - operationsService.setSeriesValidation(id); - } catch (RmesException e) { - return returnRmesException(e); - } + @PathVariable(Constants.ID) String id) throws RmesException { + operationsService.setSeriesValidation(id); return ResponseEntity.status(HttpStatus.OK).body(id); } @@ -194,8 +153,8 @@ public ResponseEntity getSeriesWithStamp(@Parameter( required = true, schema = @Schema(pattern = "([A-Za-z0-9_-]+)", type = "string")) @PathVariable(Constants.STAMP) String stamp ) throws RmesException { - String jsonResultat = operationsService.getSeriesWithStamp(stamp); - return ResponseEntity.status(HttpStatus.OK).body(jsonResultat); + String series = operationsService.getSeriesWithStamp(stamp); + return ResponseEntity.status(HttpStatus.OK).body(series); } } diff --git a/src/main/java/fr/insee/rmes/webservice/StructureResources.java b/src/main/java/fr/insee/rmes/webservice/structures/StructureResources.java similarity index 55% rename from src/main/java/fr/insee/rmes/webservice/StructureResources.java rename to src/main/java/fr/insee/rmes/webservice/structures/StructureResources.java index 2f2ba8667..2017a22db 100644 --- a/src/main/java/fr/insee/rmes/webservice/StructureResources.java +++ b/src/main/java/fr/insee/rmes/webservice/structures/StructureResources.java @@ -1,4 +1,4 @@ -package fr.insee.rmes.webservice; +package fr.insee.rmes.webservice.structures; import fr.insee.rmes.bauhaus_services.Constants; import fr.insee.rmes.bauhaus_services.structures.StructureComponent; @@ -16,9 +16,6 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.http.HttpStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -40,39 +37,34 @@ @ApiResponse(responseCode = "404", description = "Not found"), @ApiResponse(responseCode = "406", description = "Not Acceptable"), @ApiResponse(responseCode = "500", description = "Internal server error")}) -public class StructureResources extends GenericResources { +public class StructureResources { - static final Logger logger = LoggerFactory.getLogger(StructureResources.class); - @Autowired + final StructureService structureService; - @Autowired + final StructureComponent structureComponentService; + public StructureResources(StructureService structureService, StructureComponent structureComponentService) { + this.structureService = structureService; + this.structureComponentService = structureComponentService; + } + @GetMapping( produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getStructures", summary = "List of structures", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Structure.class))))}) - public ResponseEntity getStructures() { - String jsonResultat; - try { - jsonResultat = structureService.getStructures(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); + public ResponseEntity getStructures() throws RmesException { + String structures = structureService.getStructures(); + return ResponseEntity.status(HttpStatus.SC_OK).body(structures); } @GetMapping(value = "/search", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getStructuresForSearch", summary = "List of structures for advanced search", responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Structure.class))))}) - public ResponseEntity getStructuresForSearch() { - try { - String jsonResultat = structureService.getStructuresForSearch(); - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getStructuresForSearch() throws RmesException { + String structures = structureService.getStructuresForSearch(); + return ResponseEntity.status(HttpStatus.SC_OK).body(structures); } @GetMapping(value = "/structure/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @@ -83,37 +75,25 @@ public ResponseEntity getStructuresForSearch() { @ApiResponse(content = @Content(schema = @Schema(implementation = StructureById.class))) } ) - public ResponseEntity getStructureById(@PathVariable(Constants.ID) String id) { - try { - String structure = structureService.getStructureById(id); - return ResponseEntity.status(HttpStatus.SC_OK).body(structure); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getStructureById(@PathVariable(Constants.ID) String id) throws RmesException { + String structure = structureService.getStructureById(id); + return ResponseEntity.status(HttpStatus.SC_OK).body(structure); } @PreAuthorize("isAdmin() || isStructureContributor(#id)") - @PutMapping(value = "/structure/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value = "/structure/{id}/validate", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "publishStructureById", summary = "Publish a structure") - public ResponseEntity publishStructureById(@PathVariable(Constants.ID) @P("id") String id) { - try { - String response = structureService.publishStructureById(id); - return ResponseEntity.status(HttpStatus.SC_OK).body(response); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity publishStructureById(@PathVariable(Constants.ID) @P("id") String id) throws RmesException { + String response = structureService.publishStructureById(id); + return ResponseEntity.status(HttpStatus.SC_OK).body(response); } @GetMapping(value = "/structure/{id}/details", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getStructureByIdDetails", summary = "Get all details of a structure", responses = {@ApiResponse(content = @Content(schema = @Schema(implementation = StructureById.class)))}) - public ResponseEntity getStructureByIdDetails(@PathVariable(Constants.ID) String id) { - try { - String jsonResultat = structureService.getStructureByIdWithDetails(id); - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getStructureByIdDetails(@PathVariable(Constants.ID) String id) throws RmesException { + String structure = structureService.getStructureByIdWithDetails(id); + return ResponseEntity.status(HttpStatus.SC_OK).body(structure); } @PreAuthorize("isAdmin() || isStructureAndComponentContributor(#body)") @@ -121,13 +101,9 @@ public ResponseEntity getStructureByIdDetails(@PathVariable(Constants.ID consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "setStructure", summary = "Create a structure") public ResponseEntity setStructure( - @Parameter(description = "Structure", required = true) @RequestBody String body) { - try { - String id = structureService.setStructure(body); - return ResponseEntity.status(HttpStatus.SC_OK).body(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + @Parameter(description = "Structure", required = true) @RequestBody String body) throws RmesException { + String id = structureService.setStructure(body); + return ResponseEntity.status(HttpStatus.SC_OK).body(id); } @PreAuthorize("isAdmin() || isStructureContributor(#structureId)") @@ -136,93 +112,61 @@ public ResponseEntity setStructure( @Operation(operationId = "setStructure", summary = "Update a structure") public ResponseEntity setStructure( @PathVariable("structureId") @P("structureId") String structureId, - @Parameter(description = "Structure", required = true) @RequestBody String body) { - try { - String id = structureService.setStructure(structureId, body); - return ResponseEntity.status(HttpStatus.SC_OK).body(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + @Parameter(description = "Structure", required = true) @RequestBody String body) throws RmesException { + String id = structureService.setStructure(structureId, body); + return ResponseEntity.status(HttpStatus.SC_OK).body(id); } @PreAuthorize("isAdmin() || isStructureContributor(#structureId)") @DeleteMapping("/structure/{structureId}") @Operation(operationId = "deleteStructure", summary = "Delete a structure") - public ResponseEntity deleteStructure(@PathVariable("structureId") @P("structureId") String structureId) { - try { - structureService.deleteStructure(structureId); - return ResponseEntity.status(HttpStatus.SC_OK).body(structureId); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity deleteStructure(@PathVariable("structureId") @P("structureId") String structureId) throws RmesException { + structureService.deleteStructure(structureId); + return ResponseEntity.status(HttpStatus.SC_OK).body(structureId); } @GetMapping(value = "/components/search", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getComponentsForSearch", summary = "Get all mutualized components for advanced search") - public ResponseEntity getComponentsForSearch() { - try { - String jsonResultat = structureComponentService.getComponentsForSearch(); - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getComponentsForSearch() throws RmesException { + String components = structureComponentService.getComponentsForSearch(); + return ResponseEntity.status(HttpStatus.SC_OK).body(components); } @GetMapping(value = "/attributes", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getAttributes", summary = "Get all mutualized attributes") - public ResponseEntity getAttributes() { - try { - String jsonResultat = structureComponentService.getAttributes(); - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getAttributes() throws RmesException { + String attributes = structureComponentService.getAttributes(); + return ResponseEntity.status(HttpStatus.SC_OK).body(attributes); } @GetMapping(value = "/components", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getComponents", summary = "Get all mutualized components") - public ResponseEntity getComponents() { - try { - String jsonResultat = structureComponentService.getComponents(); - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getComponents() throws RmesException { + String components = structureComponentService.getComponents(); + return ResponseEntity.status(HttpStatus.SC_OK).body(components); } @GetMapping(value = "/components/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "getComponentById", summary = "Get a component") - public ResponseEntity getComponentById(@PathVariable(Constants.ID) String id) { - try { - String jsonResultat = structureComponentService.getComponent(id); - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity getComponentById(@PathVariable(Constants.ID) String id) throws RmesException { + String component = structureComponentService.getComponent(id); + return ResponseEntity.status(HttpStatus.SC_OK).body(component); } @PreAuthorize("isAdmin() || isStructureContributor(#structureId)") - @PutMapping(value = "/components/{id}/publish", produces = MediaType.APPLICATION_JSON_VALUE) + @PutMapping(value = "/components/{id}/validate", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "publishComponentById", summary = "Publish a component") - public ResponseEntity publishComponentById(@PathVariable(Constants.ID) @P("structureId") String id) { - try { - String jsonResultat = structureComponentService.publishComponent(id); - return ResponseEntity.status(HttpStatus.SC_OK).body(jsonResultat); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity publishComponentById(@PathVariable(Constants.ID) @P("structureId") String id) throws RmesException { + String result = structureComponentService.publishComponent(id); + return ResponseEntity.status(HttpStatus.SC_OK).body(result); } @PreAuthorize("isAdmin() || isComponentContributor(#id)") @DeleteMapping(value = "/components/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "deleteComponentById", summary = "Delete a mutualized component") - public ResponseEntity deleteComponentById(@PathVariable(Constants.ID) @P("id") String id) { - try { - structureComponentService.deleteComponent(id); - return ResponseEntity.status(HttpStatus.SC_OK).build(); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + public ResponseEntity deleteComponentById(@PathVariable(Constants.ID) @P("id") String id) throws RmesException { + structureComponentService.deleteComponent(id); + return ResponseEntity.status(HttpStatus.SC_OK).build(); } @PreAuthorize("isAdmin() || isComponentContributor(#componentId)") @@ -230,13 +174,9 @@ public ResponseEntity deleteComponentById(@PathVariable(Constants.ID) @P consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "updateComponent", summary = "Update a component") public ResponseEntity updateComponentById(@PathVariable(Constants.ID) @P("componentId") String componentId, - @Parameter(description = "Component", required = true) @RequestBody String body) { - try { - String id = structureComponentService.updateComponent(componentId, body); - return ResponseEntity.status(HttpStatus.SC_OK).body(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + @Parameter(description = "Component", required = true) @RequestBody String body) throws RmesException { + String id = structureComponentService.updateComponent(componentId, body); + return ResponseEntity.status(HttpStatus.SC_OK).body(id); } @PreAuthorize("isAdmin() || isStructureAndComponentContributor(#body)") @@ -244,12 +184,8 @@ public ResponseEntity updateComponentById(@PathVariable(Constants.ID) @P consumes = MediaType.APPLICATION_JSON_VALUE) @Operation(operationId = "createComponent", summary = "Create a component") public ResponseEntity createComponent( - @Parameter(description = "Component", required = true) @RequestBody String body) { - try { - String id = structureComponentService.createComponent(body); - return ResponseEntity.status(HttpStatus.SC_CREATED).body(id); - } catch (RmesException e) { - return ResponseEntity.status(e.getStatus()).body(e.getDetails()); - } + @Parameter(description = "Component", required = true) @RequestBody String body) throws RmesException { + String id = structureComponentService.createComponent(body); + return ResponseEntity.status(HttpStatus.SC_CREATED).body(id); } } diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImplTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImplTest.java index c115a0436..2c6356a74 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImplTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/concepts/ConceptsImplTest.java @@ -11,7 +11,7 @@ import fr.insee.rmes.model.concepts.CollectionForExportOld; import fr.insee.rmes.persistance.sparql_queries.GenericQueries; import fr.insee.rmes.utils.ExportUtils; -import fr.insee.rmes.webservice.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.BeforeAll; diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/datasets/DatasetServiceImplTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/datasets/DatasetServiceImplTest.java index 8d2f97a66..7a1cce98a 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/datasets/DatasetServiceImplTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/datasets/DatasetServiceImplTest.java @@ -28,7 +28,7 @@ import org.mockito.MockedStatic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import java.time.Instant; import java.time.LocalDateTime; @@ -54,14 +54,14 @@ }) class DatasetServiceImplTest { - @MockBean + @MockitoBean SeriesUtils seriesUtils; - @MockBean + @MockitoBean IdGenerator idGenerator; - @MockBean + @MockitoBean PublicationUtils publicationUtils; - @MockBean + @MockitoBean RepositoryGestion repositoryGestion; @Autowired DatasetServiceImpl datasetService; @@ -415,7 +415,7 @@ private void createANewDataset(String nextId) throws RmesException { try ( MockedStatic datasetQueriesMock = mockStatic(DatasetQueries.class); MockedStatic rdfUtilsMock = mockStatic(RdfUtils.class); - MockedStatic dateUtilsMock = mockStatic(DateUtils.class); + MockedStatic dateUtilsMock = mockStatic(DateUtils.class) ) { when(idGenerator.generateNextId()).thenReturn(nextId); IRI iri = SimpleValueFactory.getInstance().createIRI("http://datasetIRI/" + nextId); @@ -606,7 +606,7 @@ void shouldNotDeleteNotUnpublishedDatasetAndReturn406() throws RmesException { JSONArray empty_array = new JSONArray(EMPTY_ARRAY); try ( - MockedStatic datasetQueriesMock = mockStatic(DatasetQueries.class); + MockedStatic datasetQueriesMock = mockStatic(DatasetQueries.class) ) { datasetQueriesMock.when(() -> DatasetQueries.getDataset(any(), any(), any())).thenReturn("query1 "); @@ -632,7 +632,7 @@ void shouldNotDeleteDataSetWithDistributionAndReturn400() throws RmesException { JSONArray mockDistrib = new JSONArray("[{\"idDataset\":\"idTest\",\"id\":\"distrib1\"}]"); try ( MockedStatic datasetQueriesMock = mockStatic(DatasetQueries.class); - MockedStatic distributionQueriesMock = mockStatic(DistributionQueries.class); + MockedStatic distributionQueriesMock = mockStatic(DistributionQueries.class) ) { datasetQueriesMock.when(() -> DatasetQueries.getDataset(any(), any(), any())).thenReturn("query1 "); @@ -665,7 +665,7 @@ void shouldDeleteDataSet() throws RmesException { try ( MockedStatic datasetQueriesMock = mockStatic(DatasetQueries.class); MockedStatic distributionQueriesMock = mockStatic(DistributionQueries.class); - MockedStatic rdfUtilsMock = mockStatic(RdfUtils.class); + MockedStatic rdfUtilsMock = mockStatic(RdfUtils.class) ) { diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImplTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImplTest.java index a095364f6..f0bddba7a 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImplTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/distribution/DistributionServiceImplTest.java @@ -24,7 +24,7 @@ import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import java.time.LocalDateTime; import java.util.Set; @@ -45,12 +45,12 @@ "fr.insee.rmes.bauhaus.lg2=en" }) class DistributionServiceImplTest { - @MockBean + @MockitoBean RepositoryGestion repositoryGestion; - @MockBean + @MockitoBean PublicationUtils publicationUtils; - @MockBean + @MockitoBean IdGenerator idGenerator; @Autowired DistributionServiceImpl distributionService; @@ -149,7 +149,7 @@ private void createANewDistribution(String nextId) throws RmesException { try ( MockedStatic datasetQueriesMock = Mockito.mockStatic(DistributionQueries.class); MockedStatic rdfUtilsMock = Mockito.mockStatic(RdfUtils.class); - MockedStatic dateUtilsMock = Mockito.mockStatic(DateUtils.class); + MockedStatic dateUtilsMock = Mockito.mockStatic(DateUtils.class) ) { when(idGenerator.generateNextId()).thenReturn(nextId); IRI iri = SimpleValueFactory.getInstance().createIRI("http://distributionIRI/" + nextId); @@ -334,7 +334,7 @@ void shouldDeleteDistribution() throws RmesException{ IRI distributionUri = RdfUtils.toURI(stringDistributionIri); try( MockedStatic distributionQueriesMock = Mockito.mockStatic(DistributionQueries.class); - MockedStatic rdfUtilsMock = Mockito.mockStatic(RdfUtils.class); + MockedStatic rdfUtilsMock = Mockito.mockStatic(RdfUtils.class) ) { distributionQueriesMock.when(() -> DistributionQueries.getDistribution(any(), any())).thenReturn("query1 "); diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtilsTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtilsTest.java index 0856318a9..41be3c473 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtilsTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/structures/utils/StructureUtilsTest.java @@ -17,7 +17,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; @@ -30,7 +30,7 @@ class StructureUtilsTest { @Mock StructureUtils mockStructureUtils; - @MockBean + @MockitoBean RepositoryGestion repositoryGestion; @Autowired diff --git a/src/test/java/fr/insee/rmes/bauhaus_services/themes/ThemeServiceImplTest.java b/src/test/java/fr/insee/rmes/bauhaus_services/themes/ThemeServiceImplTest.java index acd8f67b8..e38ba1413 100644 --- a/src/test/java/fr/insee/rmes/bauhaus_services/themes/ThemeServiceImplTest.java +++ b/src/test/java/fr/insee/rmes/bauhaus_services/themes/ThemeServiceImplTest.java @@ -9,7 +9,7 @@ import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @@ -19,7 +19,7 @@ "fr.insee.rmes.bauhaus.theme.conceptSchemeFilter=filter1" }) class ThemeServiceImplTest { - @MockBean + @MockitoBean RepositoryGestion repositoryGestion; @Autowired diff --git a/src/test/java/fr/insee/rmes/external/services/rbac/RBACServiceImplTest.java b/src/test/java/fr/insee/rmes/external/services/rbac/RBACServiceImplTest.java index 77b17f143..6d1fabd06 100644 --- a/src/test/java/fr/insee/rmes/external/services/rbac/RBACServiceImplTest.java +++ b/src/test/java/fr/insee/rmes/external/services/rbac/RBACServiceImplTest.java @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import java.util.List; import java.util.Map; @@ -18,7 +18,7 @@ class RBACServiceImplTest { @Autowired RBACServiceImpl rbacService; - @MockBean + @MockitoBean RBACConfiguration configuration; @Test diff --git a/src/test/java/fr/insee/rmes/integration/CorsConfigDefaultToAppHostPropertyForOriginTest.java b/src/test/java/fr/insee/rmes/integration/CorsConfigDefaultToAppHostPropertyForOriginTest.java index 10428bfca..580c61913 100644 --- a/src/test/java/fr/insee/rmes/integration/CorsConfigDefaultToAppHostPropertyForOriginTest.java +++ b/src/test/java/fr/insee/rmes/integration/CorsConfigDefaultToAppHostPropertyForOriginTest.java @@ -9,8 +9,8 @@ import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -28,7 +28,7 @@ class CorsConfigDefaultToAppHostPropertyForOriginTest { // Perform mock request on http://localhost:80 private MockMvc mockMvc; - @MockBean + @MockitoBean private StampsService stampsService; @ValueSource(strings = { diff --git a/src/test/java/fr/insee/rmes/integration/CorsConfigTest.java b/src/test/java/fr/insee/rmes/integration/CorsConfigTest.java index 45f98b2f9..15ebe93f7 100644 --- a/src/test/java/fr/insee/rmes/integration/CorsConfigTest.java +++ b/src/test/java/fr/insee/rmes/integration/CorsConfigTest.java @@ -9,8 +9,8 @@ import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -28,7 +28,7 @@ class CorsConfigTest { // Perform mock request on http://localhost:80 private MockMvc mockMvc; - @MockBean + @MockitoBean private StampsService stampsService; @ValueSource(strings = { diff --git a/src/test/java/fr/insee/rmes/integration/TestDocumentsResourcesWithFilesOperation.java b/src/test/java/fr/insee/rmes/integration/TestDocumentsResourcesWithFilesOperation.java index 5db3be9e7..97fcdc439 100644 --- a/src/test/java/fr/insee/rmes/integration/TestDocumentsResourcesWithFilesOperation.java +++ b/src/test/java/fr/insee/rmes/integration/TestDocumentsResourcesWithFilesOperation.java @@ -17,9 +17,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -29,8 +29,6 @@ import static fr.insee.rmes.utils.ConsoleCapture.startCapturingConsole; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -41,17 +39,17 @@ class TestDocumentsResourcesWithFilesOperation { @Autowired private MockMvc mockMvc; - @MockBean + @MockitoBean private RepositoryPublication repositoryPublication; - @MockBean + @MockitoBean private StampsRestrictionServiceImpl stampsRestrictionService; - @MockBean + @MockitoBean private IdGenerator idGenerator; - @MockBean + @MockitoBean private PublicationUtils publicationUtils; - @MockBean + @MockitoBean private Config config; - @MockBean + @MockitoBean private RepositoryGestion repositoryGestion; private final String fichierId="ID"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java b/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java index abdde6499..04dc34738 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/PublicResourcesAuthorizationsTest.java @@ -13,9 +13,9 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.stream.Stream; @@ -45,9 +45,9 @@ class PublicResourcesAuthorizationsTest { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean private StampsService stampsService; public static Stream endpointsProvider() { diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestClassificationsRessourcesEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestClassificationsRessourcesEnvProd.java index 9c5264c04..1a7aeb1d1 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestClassificationsRessourcesEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestClassificationsRessourcesEnvProd.java @@ -10,17 +10,17 @@ import fr.insee.rmes.config.auth.security.CommonSecurityConfiguration; import fr.insee.rmes.config.auth.security.DefaultSecurityContext; import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; -import fr.insee.rmes.webservice.ClassificationsResources; +import fr.insee.rmes.webservice.classifications.ClassificationsResources; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultMatcher; @@ -57,13 +57,13 @@ class TestClassificationsRessourcesEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean private ClassificationsService classificationsService; - @MockBean + @MockitoBean private ClassificationItemService classificationItemService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; private final String idep = "xxxxxx"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestCodeListsResourcesEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestCodeListsResourcesEnvProd.java index e133388c7..074a22b30 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestCodeListsResourcesEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestCodeListsResourcesEnvProd.java @@ -15,10 +15,10 @@ import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -51,11 +51,11 @@ class TestCodeListsResourcesEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean private CodeListService codeListService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; private final String idep = "xxxxxx"; @@ -282,7 +282,7 @@ void putCodeAsNotCodesListContributor() throws Exception { @Test void validateCodeAdmin_ok() throws Exception { configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.ADMIN)); - mvc.perform(put("/codeList/validate/1").header("Authorization", "Bearer toto") + mvc.perform(put("/codeList/1/validate").header("Authorization", "Bearer toto") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{\"id\": \"1\"}")) @@ -294,7 +294,7 @@ void validateCodeAsCodesListContributor_ok() throws Exception { when(stampAuthorizationChecker.isCodesListManagerWithStamp(anyString(), eq(new Stamp(timbre)))).thenReturn(true); configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.CODESLIST_CONTRIBUTOR)); - mvc.perform(put("/codeList/validate/1").header("Authorization", "Bearer toto") + mvc.perform(put("/codeList/1/validate").header("Authorization", "Bearer toto") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{\"id\": \"1\"}")) @@ -303,7 +303,7 @@ void validateCodeAsCodesListContributor_ok() throws Exception { @Test void validateCode_noAuth() throws Exception { - mvc.perform(put("/codeList/validate/1") + mvc.perform(put("/codeList/1/validate") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{\"id\": \"1\"}")) @@ -313,7 +313,7 @@ void validateCode_noAuth() throws Exception { @Test void validateCodeAsNotCodesListContributor() throws Exception { configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("mauvais rĂ´le")); - mvc.perform(put("/codeList/validate/1").header("Authorization", "Bearer toto") + mvc.perform(put("/codeList/1/validate").header("Authorization", "Bearer toto") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{\"id\": \"1\"}")) diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestDatasetsResourcesEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestDatasetsResourcesEnvProd.java index 401127549..4db478f0c 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestDatasetsResourcesEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestDatasetsResourcesEnvProd.java @@ -11,16 +11,16 @@ import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; import fr.insee.rmes.config.auth.user.Stamp; import fr.insee.rmes.model.dataset.Dataset; -import fr.insee.rmes.webservice.dataset.DatasetResources; +import fr.insee.rmes.webservice.datasets.DatasetResources; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -55,11 +55,11 @@ class TestDatasetsResourcesEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean DatasetService datasetService; private static Dataset dataset; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestDistributionsResourcesEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestDistributionsResourcesEnvProd.java index 955fef25c..28faf247d 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestDistributionsResourcesEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestDistributionsResourcesEnvProd.java @@ -12,14 +12,14 @@ import fr.insee.rmes.config.auth.security.DefaultSecurityContext; import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; import fr.insee.rmes.config.auth.user.Stamp; -import fr.insee.rmes.webservice.distribution.DistributionResources; +import fr.insee.rmes.webservice.datasets.DistributionResources; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -50,13 +50,13 @@ class TestDistributionsResourcesEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean private DatasetService datasetService; - @MockBean + @MockitoBean private DistributionService distributionService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; private final String idep = "xxxxxx"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestDocumentsResourcesEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestDocumentsResourcesEnvProd.java index 6fee05f63..20bd40b92 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestDocumentsResourcesEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestDocumentsResourcesEnvProd.java @@ -18,13 +18,13 @@ import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.web.MockMultipartFile; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -63,11 +63,11 @@ class TestDocumentsResourcesEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean private DocumentsService documentsService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; private final String idep = "xxxxxx"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java index a24f9f342..2b103dd9d 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvHorsProd.java @@ -11,10 +11,10 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -46,10 +46,10 @@ class TestGeographyResourcesAuthorizationsEnvHorsProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private GeographyService geographyService; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; private final String idep = "xxxxux"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java index 16bed0138..04aed709d 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestGeographyResourcesAuthorizationsEnvProd.java @@ -12,10 +12,10 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -44,14 +44,14 @@ class TestGeographyResourcesAuthorizationsEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private GeographyService geographyService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; private final String idep = "xxxxux"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestIndicatorsResourcesAuthorizationsEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestIndicatorsResourcesAuthorizationsEnvProd.java index 0adf29937..44e03aed5 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestIndicatorsResourcesAuthorizationsEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestIndicatorsResourcesAuthorizationsEnvProd.java @@ -11,12 +11,14 @@ import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; import fr.insee.rmes.webservice.operations.IndicatorsResources; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -24,7 +26,7 @@ import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(controllers = IndicatorsResources.class, @@ -47,20 +49,51 @@ class TestIndicatorsResourcesAuthorizationsEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private OperationsService operationsService; - @MockBean + @MockitoBean private OperationsDocumentationsService operationsDocumentationsService; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; private final String idep = "xxxxux"; private final String timbre = "XX59-YYY"; + @ValueSource(strings = { + "/operations/indicators/", + "/operations/indicators/withSims", + "/operations/indicators/advanced-search", + "/operations/indicator/1" + }) + @ParameterizedTest + void getWithAdmin_Ok(String url) throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.ADMIN)); + mvc.perform(get(url).header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @ValueSource(strings = { + "/operations/indicators/", + "/operations/indicators/withSims", + "/operations/indicators/advanced-search", + "/operations/indicator/1" + }) + @ParameterizedTest + void getWithContributor_Ok(String url) throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.SERIES_CONTRIBUTOR)); + mvc.perform(get(url).header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test void postIndicatorWhenAdmin_ok() throws Exception { configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.ADMIN)); @@ -94,4 +127,66 @@ void postIndicatorWhenIndicatorFakeRole_ko() throws Exception { .andExpect(status().isForbidden()); } + @Test + void putIndicatorWhenAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.ADMIN)); + when(operationsService.setIndicator(anyString())).thenReturn("1"); + mvc.perform(put("/operations/indicator/1").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"} ")) + .andExpect(status().is2xxSuccessful()); + } + + @Test + void putIndicatorWhenIndicatorContributor_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.INDICATOR_CONTRIBUTOR)); + when(operationsService.setIndicator(anyString())).thenReturn("1"); + mvc.perform(put("/operations/indicator/1").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"} ")) + .andExpect(status().is2xxSuccessful()); + } + + @Test + void putIndicatorWhenIndicatorFakeRole_ko() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("fake")); + when(operationsService.setIndicator(anyString())).thenReturn("1"); + mvc.perform(put("/operations/indicator/1").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content("{\"id\": \"1\"} ")) + .andExpect(status().isForbidden()); + } + + @Test + void validateIndicatorWhenAdmin_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.ADMIN)); + when(operationsService.setIndicator(anyString())).thenReturn("1"); + mvc.perform(put("/operations/indicator/1/validate").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void validateIndicatorWhenIndicatorContributor_ok() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.INDICATOR_CONTRIBUTOR)); + when(operationsService.setIndicator(anyString())).thenReturn("1"); + mvc.perform(put("/operations/indicator/1/validate").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + void validateIndicatorWhenIndicatorFakeRole_ko() throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of("fake")); + when(operationsService.setIndicator(anyString())).thenReturn("1"); + mvc.perform(put("/operations/indicator/1/validate").header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isForbidden()); + } } diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestMetadataReportResourcesAuthorizationsEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestMetadataReportResourcesAuthorizationsEnvProd.java index 7e32f26de..02f299fa8 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestMetadataReportResourcesAuthorizationsEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestMetadataReportResourcesAuthorizationsEnvProd.java @@ -19,7 +19,6 @@ import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; @@ -27,6 +26,7 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -60,16 +60,16 @@ class TestMetadataReportResourcesAuthorizationsEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private OperationsDocumentationsService documentationsService; - @MockBean + @MockitoBean private OperationsService operationsService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; private final String idep = "xxxxux"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesAuthorizationsEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesAuthorizationsEnvProd.java index e3e03aeff..bd62bff5a 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesAuthorizationsEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesAuthorizationsEnvProd.java @@ -13,10 +13,10 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -46,15 +46,15 @@ class TestSeriesResourcesAuthorizationsEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private OperationsService operationsService; - @MockBean + @MockitoBean private OperationsDocumentationsService operationsDocumentationsService; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; private final String idep = "xxxxux"; private final String timbre = "XX59-YYY"; diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesEnvProd.java index 96d9cd638..89bd7a78e 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestSeriesResourcesEnvProd.java @@ -13,19 +13,22 @@ import fr.insee.rmes.config.auth.user.Stamp; import fr.insee.rmes.webservice.operations.SeriesResources; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -51,22 +54,57 @@ class TestSeriesResourcesEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private OperationsService operationsService; - @MockBean + @MockitoBean protected OperationsDocumentationsService documentationsService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; private final String idep = "xxxxux"; private final String timbre = "XX59-YYY"; int seriesId = 10; + @ValueSource(strings = { + "/operations/series/", + "/operations/series/withSims", + "/operations/series/1", + "/operations/series/advanced-search", + "/operations/series/advanced-search/stamp", + "/operations/series/1/operationsWithReport", + "/operations/series/1/operationsWithoutReport" + }) + @ParameterizedTest + void getWithAdmin_Ok(String url) throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.ADMIN)); + mvc.perform(get(url).header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @ValueSource(strings = { + "/operations/series/", + "/operations/series/withSims", + "/operations/series/1", + "/operations/series/advanced-search", + "/operations/series/advanced-search/stamp", + "/operations/series/1/operationsWithReport", + "/operations/series/1/operationsWithoutReport" + }) + @ParameterizedTest + void getWithContributor_Ok(String url) throws Exception { + configureJwtDecoderMock(jwtDecoder, idep, timbre, List.of(Roles.SERIES_CONTRIBUTOR)); + mvc.perform(get(url).header("Authorization", "Bearer toto") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } @Test void putSeriesAdmin_ok() throws Exception { diff --git a/src/test/java/fr/insee/rmes/integration/authorizations/TestStructuresResourcesEnvProd.java b/src/test/java/fr/insee/rmes/integration/authorizations/TestStructuresResourcesEnvProd.java index f5e7fd295..9825e3e0e 100644 --- a/src/test/java/fr/insee/rmes/integration/authorizations/TestStructuresResourcesEnvProd.java +++ b/src/test/java/fr/insee/rmes/integration/authorizations/TestStructuresResourcesEnvProd.java @@ -12,21 +12,20 @@ import fr.insee.rmes.config.auth.security.DefaultSecurityContext; import fr.insee.rmes.config.auth.security.OpenIDConnectSecurityContext; import fr.insee.rmes.config.auth.user.Stamp; -import fr.insee.rmes.webservice.StructureResources; +import fr.insee.rmes.webservice.structures.StructureResources; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.*; -import static fr.insee.rmes.integration.authorizations.TokenForTestsConfiguration.KEY_FOR_ROLES_IN_ROLE_CLAIM; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -51,15 +50,15 @@ class TestStructuresResourcesEnvProd { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; - @MockBean + @MockitoBean private StructureService structureService; - @MockBean + @MockitoBean StructureComponent structureComponentService; - @MockBean + @MockitoBean protected OperationsDocumentationsService documentationsService; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; private final String idep = "xxxxxx"; private final String timbre = "XX59-YYY"; diff --git a/src/test/java/fr/insee/rmes/webservice/ConceptsResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/ConceptsResourcesTest.java index 4b8b95c2e..6b6dcf95c 100644 --- a/src/test/java/fr/insee/rmes/webservice/ConceptsResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/ConceptsResourcesTest.java @@ -2,7 +2,7 @@ import fr.insee.rmes.bauhaus_services.ConceptsCollectionService; import fr.insee.rmes.exceptions.RmesException; -import org.apache.http.HttpStatus; +import fr.insee.rmes.webservice.concepts.ConceptsResources; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,13 +27,6 @@ public void init() { MockitoAnnotations.openMocks(this); } - @Test - void shouldReturn500IfRmesExceptionWhenFetchingCollectionById() throws RmesException { - when(conceptsCollectionService.getCollectionByID(anyString())).thenThrow(new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "erreur", "")); - ResponseEntity response = conceptsResources.getCollectionByID("1"); - Assertions.assertEquals(500, response.getStatusCode().value()); - } - @Test void shouldReturn200WhenFetchingCollectionById() throws RmesException { when(conceptsCollectionService.getCollectionByID(anyString())).thenReturn("result"); diff --git a/src/test/java/fr/insee/rmes/webservice/DatasetResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/DatasetResourcesTest.java index 8bd2a5b31..7b8bbfcfe 100644 --- a/src/test/java/fr/insee/rmes/webservice/DatasetResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/DatasetResourcesTest.java @@ -3,7 +3,7 @@ import fr.insee.rmes.bauhaus_services.datasets.DatasetService; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.dataset.Dataset; -import fr.insee.rmes.webservice.dataset.DatasetResources; +import fr.insee.rmes.webservice.datasets.DatasetResources; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/fr/insee/rmes/webservice/DistributionResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/DistributionResourcesTest.java index ccfa67ea4..e119d6aba 100644 --- a/src/test/java/fr/insee/rmes/webservice/DistributionResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/DistributionResourcesTest.java @@ -7,7 +7,7 @@ import fr.insee.rmes.config.auth.user.User; import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.model.dataset.Distribution; -import fr.insee.rmes.webservice.distribution.DistributionResources; +import fr.insee.rmes.webservice.datasets.DistributionResources; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; diff --git a/src/test/java/fr/insee/rmes/webservice/DocumentsResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/DocumentsResourcesTest.java index 8204cd645..8e6bdd64e 100644 --- a/src/test/java/fr/insee/rmes/webservice/DocumentsResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/DocumentsResourcesTest.java @@ -2,15 +2,14 @@ import fr.insee.rmes.bauhaus_services.DocumentsService; import fr.insee.rmes.config.BaseConfigForMvcTests; -import fr.insee.rmes.exceptions.RmesException; import fr.insee.rmes.exceptions.RmesNotFoundException; import fr.insee.rmes.webservice.operations.DocumentsResources; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.HttpStatus; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -24,7 +23,7 @@ @Import(BaseConfigForMvcTests.class) class DocumentsResourcesTest { - @MockBean + @MockitoBean private DocumentsService documentsService; @Autowired diff --git a/src/test/java/fr/insee/rmes/webservice/PublicResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/PublicResourcesTest.java index 4dce69db6..d9145d568 100644 --- a/src/test/java/fr/insee/rmes/webservice/PublicResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/PublicResourcesTest.java @@ -11,9 +11,9 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -44,9 +44,9 @@ class PublicResourcesTest { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean StampsService stampsService; @Test diff --git a/src/test/java/fr/insee/rmes/webservice/StructureResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/StructureResourcesTest.java index a561263fd..400e93f7c 100644 --- a/src/test/java/fr/insee/rmes/webservice/StructureResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/StructureResourcesTest.java @@ -2,7 +2,7 @@ import fr.insee.rmes.bauhaus_services.structures.StructureService; import fr.insee.rmes.exceptions.RmesException; -import org.apache.http.HttpStatus; +import fr.insee.rmes.webservice.structures.StructureResources; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,20 +27,6 @@ public void init() { MockitoAnnotations.openMocks(this); } - @Test - void shouldReturn500IfRmesExceptionWhenFetchingStructuresForSearch() throws RmesException { - when(structureService.getStructuresForSearch()).thenThrow(new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "erreur", "")); - ResponseEntity response = structureResources.getStructuresForSearch(); - Assertions.assertEquals(500, response.getStatusCode().value()); - } - - @Test - void shouldReturn500IfRmesExceptionWhenFetchingStructureById() throws RmesException { - when(structureService.getStructureById(anyString())).thenThrow(new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "erreur", "")); - ResponseEntity response = structureResources.getStructureById("1"); - Assertions.assertEquals(500, response.getStatusCode().value()); - } - @Test void shouldReturn200WhenFetchingStructureById() throws RmesException { when(structureService.getStructureById(anyString())).thenReturn("result"); @@ -49,13 +35,6 @@ void shouldReturn200WhenFetchingStructureById() throws RmesException { Assertions.assertEquals("result", response.getBody()); } - @Test - void shouldReturn500IfRmesExceptionWhenPublishingAStructure() throws RmesException { - when(structureService.publishStructureById(anyString())).thenThrow(new RmesException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "erreur", "")); - ResponseEntity response = structureResources.publishStructureById("1"); - Assertions.assertEquals(500, response.getStatusCode().value()); - } - @Test void shouldReturn200WhenPublishingAStructure() throws RmesException { when(structureService.publishStructureById(anyString())).thenReturn("result publishing"); diff --git a/src/test/java/fr/insee/rmes/webservice/UnactiveStructureResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/UnactiveStructureResourcesTest.java index d75e2150e..7b178d6fd 100644 --- a/src/test/java/fr/insee/rmes/webservice/UnactiveStructureResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/UnactiveStructureResourcesTest.java @@ -1,21 +1,25 @@ package fr.insee.rmes.webservice; import fr.insee.rmes.bauhaus_services.StampAuthorizationChecker; +import fr.insee.rmes.webservice.classifications.ClassificationsResources; +import fr.insee.rmes.webservice.concepts.ConceptsCollectionsResources; +import fr.insee.rmes.webservice.concepts.ConceptsResources; import fr.insee.rmes.webservice.operations.*; +import fr.insee.rmes.webservice.structures.StructureResources; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.bean.override.mockito.MockitoBean; @SpringBootTest(properties = "fr.insee.rmes.bauhaus.activeModules=") @ExtendWith(MockitoExtension.class) class UnactiveModulesTest { - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; @Autowired(required = false) diff --git a/src/test/java/fr/insee/rmes/webservice/UserResourcesEnvHorsProdTest.java b/src/test/java/fr/insee/rmes/webservice/UserResourcesEnvHorsProdTest.java index 2d82e03ee..8cf392a49 100644 --- a/src/test/java/fr/insee/rmes/webservice/UserResourcesEnvHorsProdTest.java +++ b/src/test/java/fr/insee/rmes/webservice/UserResourcesEnvHorsProdTest.java @@ -13,10 +13,10 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -48,11 +48,11 @@ class UserResourcesEnvHorsProdTest { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean private RBACService rbacService; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; private static final String FAKE_STAMP_ANSWER = "{\"stamp\": \"fakeStampForDvAndQf\"}"; diff --git a/src/test/java/fr/insee/rmes/webservice/UserResourcesTestEnvProd.java b/src/test/java/fr/insee/rmes/webservice/UserResourcesTestEnvProd.java index f97505486..bd386054f 100644 --- a/src/test/java/fr/insee/rmes/webservice/UserResourcesTestEnvProd.java +++ b/src/test/java/fr/insee/rmes/webservice/UserResourcesTestEnvProd.java @@ -12,10 +12,10 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import java.util.List; @@ -46,11 +46,11 @@ class UserResourcesEnvProdTest { @Autowired private MockMvc mvc; - @MockBean + @MockitoBean StampAuthorizationChecker stampAuthorizationChecker; - @MockBean + @MockitoBean private RBACService rbacService; - @MockBean + @MockitoBean private JwtDecoder jwtDecoder; @Test diff --git a/src/test/java/fr/insee/rmes/webservice/operations/OperationsResourcesTest.java b/src/test/java/fr/insee/rmes/webservice/operations/OperationsResourcesTest.java index b3dc28f3f..36a44d376 100644 --- a/src/test/java/fr/insee/rmes/webservice/operations/OperationsResourcesTest.java +++ b/src/test/java/fr/insee/rmes/webservice/operations/OperationsResourcesTest.java @@ -10,9 +10,9 @@ import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @@ -26,13 +26,13 @@ @Import({UserProviderFromSecurityContext.class, DefaultSecurityContext.class}) class OperationsResourcesTest { - @MockBean + @MockitoBean protected OperationsService operationsService; - @MockBean + @MockitoBean protected OperationsDocumentationsService documentationsService; - @MockBean + @MockitoBean FakeUserConfiguration fakeUserConfiguration; @Autowired