Skip to content

Commit

Permalink
Revert "495 : etre capable de supprimer une distribution (#649)" (#673)
Browse files Browse the repository at this point in the history
This reverts commit ef07628.
  • Loading branch information
GtanSndil authored Jun 28, 2024
1 parent ef07628 commit 62bbcd6
Show file tree
Hide file tree
Showing 10 changed files with 24 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
@Service
public class DatasetServiceImpl extends RdfService implements DatasetService {

public static final String CONTRIBUTOR = "contributor";
private static Pattern ALT_IDENTIFIER_PATTERN = Pattern.compile("^[a-zA-Z0-9-_]+$");

public static final String THEME = "theme";
Expand Down Expand Up @@ -120,7 +119,7 @@ public String publishDataset(String id) throws RmesException {
IRI catalogRecordIri = RdfUtils.createIRI(getCatalogRecordBaseUri() + "/" + id);

publicationUtils.publishResource(iri, Set.of("processStep", "archiveUnit", "validationState"));
publicationUtils.publishResource(catalogRecordIri, Set.of(CREATOR, CONTRIBUTOR));
publicationUtils.publishResource(catalogRecordIri, Set.of(CREATOR, "contributor"));
model.add(iri, INSEE.VALIDATION_STATE, RdfUtils.setLiteralString(ValidationStatus.VALIDATED), RdfUtils.createIRI(getDatasetsGraph()));
model.remove(iri, INSEE.VALIDATION_STATE, RdfUtils.setLiteralString(ValidationStatus.UNPUBLISHED), RdfUtils.createIRI(getDatasetsGraph()));
model.remove(iri, INSEE.VALIDATION_STATE, RdfUtils.setLiteralString(ValidationStatus.MODIFIED), RdfUtils.createIRI(getDatasetsGraph()));
Expand Down Expand Up @@ -162,7 +161,7 @@ public String getDatasetByID(String id) throws RmesException {


JSONObject catalogRecord = new JSONObject();
getMultipleTripletsForObject(catalogRecord, CONTRIBUTOR, DatasetQueries.getDatasetContributors(catalogRecordIRI, getDatasetsGraph()), CONTRIBUTOR);
getMultipleTripletsForObject(catalogRecord, "contributor", DatasetQueries.getDatasetContributors(catalogRecordIRI, getDatasetsGraph()), "contributor");

if(dataset.has(CATALOG_RECORD_CREATOR)){
catalogRecord.put(CREATOR, dataset.getString(CATALOG_RECORD_CREATOR));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import fr.insee.rmes.exceptions.RmesException;
import fr.insee.rmes.model.dataset.PatchDistribution;
import org.springframework.http.ResponseEntity;

public interface DistributionService {

Expand All @@ -17,6 +16,4 @@ public interface DistributionService {
String publishDistribution(String id) throws RmesException;

void patchDistribution(String distributionId, PatchDistribution distribution) throws RmesException;

void deleteDistributionId(String distributionId) throws RmesException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,10 @@

import fr.insee.rmes.bauhaus_services.rdf_utils.RdfService;
import fr.insee.rmes.bauhaus_services.rdf_utils.RdfUtils;
import fr.insee.rmes.config.auth.security.SecurityExpressionRootForBauhaus;
import fr.insee.rmes.config.auth.security.restrictions.StampsRestrictionsService;
import fr.insee.rmes.exceptions.ErrorCodes;
import fr.insee.rmes.exceptions.RmesBadRequestException;
import fr.insee.rmes.exceptions.RmesException;
import fr.insee.rmes.exceptions.RmesNotFoundException;
import fr.insee.rmes.model.ValidationStatus;
import fr.insee.rmes.model.dataset.Dataset;
import fr.insee.rmes.model.dataset.Distribution;
import fr.insee.rmes.model.dataset.PatchDistribution;
import fr.insee.rmes.persistance.ontologies.INSEE;
Expand All @@ -24,10 +20,7 @@
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Set;
Expand Down Expand Up @@ -65,10 +58,6 @@ private String getDatasetsBaseUri(){
return baseUriGestion + datasetsBaseUriSuffix;
}

protected IRI getDatasetIri(String datasetId){
IRI iri = RdfUtils.createIRI(getDatasetsBaseUri() + "/" + datasetId);
return iri;
}
@Override
public String getDistributions() throws RmesException {
return this.repoGestion.getResponseAsArray(DistributionQueries.getDistributions(getDistributionGraph())).toString();
Expand Down Expand Up @@ -122,7 +111,7 @@ private String update(String distributionId, Distribution distribution) throws R
@Override
public String publishDistribution(String id) throws RmesException {
Model model = new LinkedHashModel();
IRI iri = getDatasetIri(id);
IRI iri = RdfUtils.createIRI(getDistributionBaseUri() + "/" + id);

publicationUtils.publishResource(iri, Set.of());
model.add(iri, INSEE.VALIDATION_STATE, RdfUtils.setLiteralString(ValidationStatus.VALIDATED), RdfUtils.createIRI(getDistributionGraph()));
Expand All @@ -134,39 +123,23 @@ public String publishDistribution(String id) throws RmesException {
return id;
}

@Override
public void deleteDistributionId(String distributionId) throws RmesException{
String distributionString = getDistributionByID(distributionId);
Distribution distribution = Deserializer.deserializeBody(distributionString, Distribution.class);
if (!isUnpublished(distribution)){
throw new RmesBadRequestException(ErrorCodes.DISTRIBUTION_DELETE_ONLY_UNPUBLISHED, "Only unpublished distributions can be deleted");
}
IRI distributionIRI = RdfUtils.createIRI(getDistributionBaseUri());
Resource graph = getDatasetIri(distributionId);
String distributionURI = getDistributionBaseUri() + "/" + distributionId;
repoGestion.deleteObject(RdfUtils.createIRI(distributionURI));
repoGestion.deleteTripletByPredicate(distributionIRI,DCAT.DISTRIBUTION,graph);
}
private boolean isUnpublished(Distribution distribution) {
return "Unpublished".equalsIgnoreCase(distribution.getValidationState());
}

private String persist(Distribution distribution, boolean creation) throws RmesException {
Resource graph = RdfUtils.createIRI(getDistributionGraph());

IRI distributionIRI = getDatasetIri(distribution.getId());
IRI distributionIRI = RdfUtils.createIRI(getDistributionBaseUri() + "/" + distribution.getId());

Model model = new LinkedHashModel();

if(!creation){
JSONObject previousValue = new JSONObject(this.getDistributionByID(distribution.getId()));
if(previousValue.has("idDataset")){
IRI iriDataset = getDatasetIri(previousValue.getString("idDataset"));
IRI iriDataset = RdfUtils.createIRI(getDatasetsBaseUri() + "/" + previousValue.getString("idDataset"));
repoGestion.deleteTripletByPredicateAndValue(iriDataset, DCAT.HAS_DISTRIBUTION, graph, null, distributionIRI);
}
}

RdfUtils.addTripleUri(getDatasetIri(distribution.getIdDataset()), DCAT.HAS_DISTRIBUTION, distributionIRI, model, graph);
RdfUtils.addTripleUri(RdfUtils.createIRI(getDatasetsBaseUri() + "/" + distribution.getIdDataset()), DCAT.HAS_DISTRIBUTION, distributionIRI, model, graph);

model.add(distributionIRI, DCTERMS.IDENTIFIER, RdfUtils.setLiteralString(distribution.getId()), graph);
model.add(distributionIRI, RDF.TYPE, DCAT.DISTRIBUTION, graph);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ public class RepositoryGestion {

private static final String FAILURE_LOAD_OBJECT = "Failure load object : {}";
private static final String FAILURE_REPLACE_GRAPH = "Failure replace graph : ";
private static final String FAILURE_DELETE_OBJECT = "Failure delete object";

static final Logger logger = LoggerFactory.getLogger(RepositoryGestion.class);

Expand Down Expand Up @@ -205,27 +204,9 @@ public void deleteTripletByPredicateAndValue(Resource object, IRI predicate, Res
processConnection(connection-> connection.remove(object, predicate, value, graph), conn, "delete triplet whose object is "+ object);
}

public void deleteTripletByPredicateAndValue(Resource object, IRI predicate, Resource graph, Value value) throws RmesException {
try {
RepositoryConnection conn = repositoryUtils.initRepository(config.getRdfServerGestion(),
config.getRepositoryIdGestion()).getConnection();

conn.remove(object, predicate, value, graph);
conn.close();
} catch (RepositoryException e) {
logger.error(FAILURE_LOAD_OBJECT , object);
logger.error(e.getMessage());
throw new RmesException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), FAILURE_LOAD_OBJECT + object);

}
}
public void deleteTripletByPredicate(Resource object, IRI predicate, Resource graph, RepositoryConnection conn) throws RmesException {
deleteTripletByPredicateAndValue(object, predicate, graph, conn, null);
}
public void deleteTripletByPredicate(Resource object, IRI predicate, Resource graph) throws RmesException {
deleteTripletByPredicateAndValue(object, predicate, graph, null);
}


public void loadSimpleObjectWithoutDeletion(IRI object, Model model, RepositoryConnection conn) throws RmesException {
processConnection(connection-> connection.add(model), conn, FAILURE_LOAD_OBJECT + object);
Expand Down Expand Up @@ -255,20 +236,6 @@ public void deleteObject(IRI object, RepositoryConnection conn) throws RmesExcep
processConnection(connection-> connection.remove(object, null, null), conn, "delete " + object);
}

public void deleteObject(IRI object) throws RmesException {
try {
RepositoryConnection conn = repositoryUtils.initRepository(config.getRdfServerGestion(),
config.getRepositoryIdGestion()).getConnection();

conn.remove(object, null, null);
conn.close();
} catch (RepositoryException e) {
logger.error(FAILURE_DELETE_OBJECT , object);
logger.error(e.getMessage());
throw new RmesException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), FAILURE_DELETE_OBJECT + object);
}
}

/**
* @param graph
* @param model
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/fr/insee/rmes/exceptions/ErrorCodes.java
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public class ErrorCodes {
//DATASET and DISTRIBUTION
public static final int DISTRIUBTION_PATCH_INCORRECT_BODY = 1201;
public static final int DATASET_PATCH_INCORRECT_BODY = 1202;
public static final int DISTRIBUTION_DELETE_ONLY_UNPUBLISHED = 1203;



/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public class Distribution {
String url;
String validationState;


public String getId() {
return id;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public String getDistributions() throws RmesException {
}

@GetMapping("/{id}")
@Operation(operationId = "getDistribution", summary = "Get a distributions",
@Operation(operationId = "getDistribution", summary = "List of distributions",
responses = {@ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Distribution.class))))})
public String getDistribution(@PathVariable(Constants.ID) String id) throws RmesException {
return this.distributionService.getDistributionByID(id);
Expand All @@ -81,7 +81,7 @@ public String getDatasetsForDistributionCreation(@AuthenticationPrincipal Object
}

@PreAuthorize("isAdmin() || isDatasetContributor()")
@PostMapping(value = "", consumes = APPLICATION_JSON_VALUE)
@PostMapping(value = "", consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(operationId = "createDistribution", summary = "Create a distribution")
@ResponseStatus(HttpStatus.CREATED)
public String createDistribution(
Expand All @@ -90,7 +90,7 @@ public String createDistribution(
}

@PreAuthorize("isAdmin() || isDistributionContributorWithStamp(#distributionId)")
@PutMapping(value = "/{id}", consumes = APPLICATION_JSON_VALUE)
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@Operation(operationId = "updateDistribution", summary = "Update a distribution")
public String updateDistribution(
@PathVariable("id") String distributionId,
Expand All @@ -105,15 +105,13 @@ public String updateDistribution(
summary = "Delete a distribution"
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The distribution has been deleted"),
@ApiResponse(responseCode = "403", description = "You are not authorized to call this endpoint"),
@ApiResponse(responseCode = "400", description = "Bad request"),
@ApiResponse(responseCode = "404", description = "This distribution does not exist")
@ApiResponse(responseCode = "501", description = "This endpoint is not implemented")
})
public ResponseEntity<Void> deleteDistribution(
@PathVariable(Constants.ID) String distributionId) throws RmesException{
distributionService.deleteDistributionId(distributionId);
return ResponseEntity.status(HttpStatus.OK).build();
public ResponseEntity deleteDistribution(
@PathVariable(Constants.ID) String distributionId
) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}

@PreAuthorize("isAdmin() || isDistributionContributorWithStamp(#distributionId)")
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/bauhaus-core.properties
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ fr.insee.rmes.bauhaus.adms.identifiantsAlternatifs.baseURI = identifiantsAlterna
###############################
#DATASET
###############################
fr.insee.rmes.bauhaus.datasets.graph = catalogue
fr.insee.rmes.bauhaus.datasets.graph = catalogues
fr.insee.rmes.bauhaus.datasets.record.baseURI = catalogues/entreeCatalogue
fr.insee.rmes.bauhaus.datasets.baseURI = datasets
fr.insee.rmes.bauhaus.theme.graph = concepts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
import org.eclipse.rdf4j.model.vocabulary.DCAT;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
Expand All @@ -23,8 +22,11 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

import java.time.LocalDateTime;
import java.util.Set;

import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
Expand All @@ -49,8 +51,6 @@ class DistributionServiceImplTest {
public static final String EMPTY_JSON_OBJECT = "{}";
@Autowired
DistributionServiceImpl distributionService;


public static final String DISTRIB = "{\"id\":\"d1000\"}";
public static final String DISTRIB_A_PATCHER = "{\"byteSize\":\"3\",\"labelLg2\":\"test_patch\",\"labelLg1\":\"test_patch\",\"created\":\"2024-04-10T16:34:09.651166561\",\"idDataset\":\"jd1004\",\"id\":\"d1004\",\"updated\":\"2024-04-07T16:34:09.651166561\",\"url\":\"http://test\"}";
public static final String DISTRIB_PATCHEE = "[(http://distributionIRI/jd1004, http://www.w3.org/ns/dcat#distribution, http://distributionIRI/d1004, http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://purl.org/dc/terms/identifier, \"d1004\", http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/ns/dcat#Distribution, http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://purl.org/dc/terms/title, \"test_patch\"@fr, http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://purl.org/dc/terms/title, \"test_patch\"@en, http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://purl.org/dc/terms/created, \"2024-04-10T16:34:09.651166561\"^^<http://www.w3.org/2001/XMLSchema#dateTime>, http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://purl.org/dc/terms/modified, \"2024-04-05T16:34:09.651166561\"^^<http://www.w3.org/2001/XMLSchema#dateTime>, http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://www.w3.org/ns/dcat#byteSize, \"5\", http://datasetGraph/) [http://datasetGraph/], (http://distributionIRI/d1004, http://www.w3.org/ns/dcat#downloadURL, \"http://test2\", http://datasetGraph/) [http://datasetGraph/]]";
Expand Down Expand Up @@ -331,45 +331,4 @@ void shouldPatchByteSizeDistribution() throws RmesException {
Assertions.assertEquals(DISTRIB_PATCHEE,model.getValue().toString());
}


@Test
void shouldNotDeleteNotUnpublishedDistributionAndReturn400() throws RmesException {
JSONObject mockJSON = new JSONObject("{\n" +
" \"id\": \"idTest\",\n" +
" \"validationState\": \"Not Unpublished\"\n" +
"}");
when(repositoryGestion.getResponseAsObject(Mockito.anyString())).thenReturn(mockJSON);
RmesException exception = assertThrows(RmesBadRequestException.class, () -> distributionService.deleteDistributionId("idTest"));
Assertions.assertEquals("{\"code\":1203,\"message\":\"Only unpublished distributions can be deleted\"}", exception.getDetails());

}

@Test
void shouldDeleteDistribution() throws RmesException{
JSONObject mockJSON = new JSONObject("{\"id\":\"idtest\",\"validationState\":\"Unpublished\"}");
String stringDistributionIri = "http://bauhaus/catalogues/distribution/idtest";
IRI distributionUri = RdfUtils.toURI(stringDistributionIri);
try(
MockedStatic<DistributionQueries> distributionQueriesMock = Mockito.mockStatic(DistributionQueries.class);
MockedStatic<RdfUtils> rdfUtilsMock = Mockito.mockStatic(RdfUtils.class);
)
{
distributionQueriesMock.when(() -> DistributionQueries.getDistribution(any(), any())).thenReturn("query1 ");
when(repositoryGestion.getResponseAsObject("query1 ")).thenReturn(mockJSON);
rdfUtilsMock.when(() -> RdfUtils.createIRI(any(String.class))).thenReturn(distributionUri);
rdfUtilsMock.when(() -> RdfUtils.toURI(any(String.class))).thenReturn(distributionUri);

// Capture the argument passed to deleteObject
ArgumentCaptor<IRI> uriCaptor = ArgumentCaptor.forClass(IRI.class);
distributionService.deleteDistributionId("idTest");
verify(repositoryGestion, times(1)).deleteObject(uriCaptor.capture());
Assertions.assertEquals(distributionUri, uriCaptor.getValue());
verify(repositoryGestion, times(1)).deleteObject(distributionUri);
verify(repositoryGestion, times(1)).deleteTripletByPredicate(any(IRI.class), eq(DCAT.DISTRIBUTION), any(IRI.class));
}

}



}
Loading

0 comments on commit 62bbcd6

Please sign in to comment.