From 06e5842d9deb3f1b83bed6eaefdf727cb0320b8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 12:11:35 +0200 Subject: [PATCH 01/19] [Enhancement kbss-cvut/termit-ui#820] Add DataController endpoint for retrieving custom attribute usage --- .../kbss/termit/persistence/dao/DataDao.java | 92 +++++++++++++++++++ .../cvut/kbss/termit/rest/DataController.java | 42 ++++++++- .../repository/DataRepositoryService.java | 16 +++- 3 files changed, 148 insertions(+), 2 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index 73edd45e0..b76beaada 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -42,14 +42,24 @@ import cz.cvut.kbss.termit.util.TypeAwareByteArrayResource; import cz.cvut.kbss.termit.util.TypeAwareResource; import jakarta.annotation.Nullable; +import org.eclipse.rdf4j.model.IRI; +import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Resource; +import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; +import org.eclipse.rdf4j.model.util.Values; +import org.eclipse.rdf4j.query.BindingSet; +import org.eclipse.rdf4j.query.TupleQuery; +import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.rio.RDFFormat; import org.eclipse.rdf4j.rio.RDFHandler; import org.eclipse.rdf4j.rio.Rio; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; import java.io.ByteArrayOutputStream; @@ -317,4 +327,86 @@ public void insertRawData(Collection data) { con.commit(); } } + + private int countCustomAttributeUsage(RepositoryConnection con, String whereQuery, IRI predicate) { + final TupleQuery countQuery = con.prepareTupleQuery("SELECT (COUNT(*) AS ?count) " + whereQuery); + + countQuery.setBinding("predicate", predicate); + countQuery.setIncludeInferred(false); + + try (TupleQueryResult result = countQuery.evaluate()) { + final BindingSet bindings = result.next(); + return ((Literal) bindings.getValue("count")).intValue(); + } + } + + private List findCustomAttributeUsage(RepositoryConnection con, String whereQuery, IRI predicate, long offset, int resultLimit) { + final TupleQuery pageQuery = con.prepareTupleQuery("SELECT ?subject ?predicate ?object ?context "+ + whereQuery + + "LIMIT " + resultLimit + + " OFFSET " + offset); + + pageQuery.setBinding("predicate", predicate); + pageQuery.setIncludeInferred(false); + + final List statements = new ArrayList<>(resultLimit); + + try (TupleQueryResult result = pageQuery.evaluate()) { + while (result.hasNext()) { + final BindingSet bindings = result.next(); + + final Resource subject = (Resource) bindings.getValue("subject"); + final IRI statementPredicate = (IRI) bindings.getValue("predicate"); + final Value object = bindings.getValue("object"); + final Resource context = (Resource) bindings.getValue("context"); + + statements.add(Values.getValueFactory().createStatement( + subject, + statementPredicate, + object, + context + )); + } + } + + return statements; + } + + /** + * Finds statements where the specified custom attribute is used as a predicate. + * + * @param identifier Custom attribute identifier + * @param pageable {@link Pageable} + * @return Page of RDF statements + */ + public Page findCustomAttributeUsage(URI identifier, Pageable pageable) { + Objects.requireNonNull(identifier); + Objects.requireNonNull(pageable); + + final org.eclipse.rdf4j.repository.Repository repo = em.unwrap(org.eclipse.rdf4j.repository.Repository.class); + final IRI predicate = Values.iri(identifier.toString()); + + final String whereQuery = """ + WHERE { + GRAPH ?context { + ?subject ?predicate ?object . + } + } + """; + + try (RepositoryConnection con = repo.getConnection()) { + final int totalCount = countCustomAttributeUsage(con, whereQuery, predicate); + + if (totalCount == 0 || pageable.getOffset() >= totalCount) { + return new PageImpl<>(List.of(), pageable, totalCount); + } + + int maxResults = Math.min(totalCount, pageable.getPageSize()); + final List statements = findCustomAttributeUsage(con, whereQuery, predicate, pageable.getOffset(), maxResults); + + return new PageImpl<>(statements, pageable, totalCount); + } catch (RuntimeException e) { + throw new PersistenceException(e); + } + } } diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index 72f85503d..0194ae50c 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -21,18 +21,25 @@ import cz.cvut.kbss.termit.exception.NotFoundException; import cz.cvut.kbss.termit.model.CustomAttribute; import cz.cvut.kbss.termit.model.RdfsResource; +import cz.cvut.kbss.termit.rest.doc.ApiDocConstants; import cz.cvut.kbss.termit.rest.util.RestUtils; import cz.cvut.kbss.termit.security.SecurityConstants; +import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.repository.DataRepositoryService; +import cz.cvut.kbss.termit.util.Constants; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; 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.eclipse.rdf4j.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -58,10 +65,12 @@ public class DataController { private static final Logger LOG = LoggerFactory.getLogger(DataController.class); private final DataRepositoryService dataService; + private final IdentifierResolver identifierResolver; @Autowired - public DataController(DataRepositoryService dataService) { + public DataController(DataRepositoryService dataService, IdentifierResolver identifierResolver) { this.dataService = dataService; + this.identifierResolver = identifierResolver; } @Operation(description = "Gets all unique RDF properties used by the data in the system.") @@ -121,6 +130,37 @@ public void updateCustomAttribute(@Parameter( LOG.debug("Updated custom attribute {}.", update); } + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, + description = "Retrieves the triples where the specified custom attribute is used as predicate.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "The list of triples with the custom attribute as predicate"), + @ApiResponse(responseCode = "404", description = "Attribute not found") + }) + @GetMapping(value = "/custom-attributes/{localName}/usage", produces = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) + public ResponseEntity> getCustomAttributeUsage(@Parameter( + description = "Locally (in the context of the namespace) unique part of the attribute identifier.", + example = "custom-attribute") + @PathVariable String localName, + @Parameter( + description = "Custom attribute identifier namespace", + example = "http://onto.fel.cvut.cz/ontologies/application/termit/custom-attribute/" + ) + @RequestParam String namespace, + @Parameter(description = ApiDocConstants.PAGE_SIZE_DESCRIPTION) + @RequestParam(name = Constants.QueryParams.PAGE_SIZE, required = false) Integer pageSize, + @Parameter(description = ApiDocConstants.PAGE_NO_DESCRIPTION) + @RequestParam(name = Constants.QueryParams.PAGE, required = false) Integer pageNo) { + Pageable pageable = Constants.DEFAULT_PAGE_SPEC; + if (pageSize != null && pageNo != null) { + pageable = PageRequest.of(pageNo, pageSize); + } + final URI identifier = identifierResolver.resolveIdentifier(namespace, localName); + final Page result = dataService.findCustomAttributeUsage(identifier, pageable); + return ResponseEntity.ok() + .header(Constants.X_TOTAL_COUNT_HEADER, Long.toString(result.getTotalElements())) + .body(result.getContent()); + } + @Operation(description = "Gets basic metadata for a RDFS resource with the specified IRI.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "RDSF resource metadata."), diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index 57d3ee7fb..85ef97963 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -28,12 +28,14 @@ import cz.cvut.kbss.termit.persistence.dao.spec.CustomAttributeSpecifications; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.util.Configuration; -import cz.cvut.kbss.termit.util.Vocabulary; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import org.eclipse.rdf4j.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -197,4 +199,16 @@ public void updateCustomAttribute(@Nonnull CustomAttribute attribute) { public Optional getLabel(URI id, @Nullable String language) { return dataDao.getLabel(id, language); } + + /** + * Finds statements where the specified custom attribute is used as a predicate. + * + * @param identifier Custom attribute identifier + * @param pageable {@link Pageable} + * @return Page of RDF statements + */ + @Transactional(readOnly = true) + public Page findCustomAttributeUsage(URI identifier, Pageable pageable) { + return dataDao.findCustomAttributeUsage(identifier, pageable); + } } From f32fe223a8d317db09565c3ad71a66e5c8330684 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 13:10:42 +0200 Subject: [PATCH 02/19] [Test] Add DataDao tests for custom attribute usage retrieval --- .../termit/persistence/dao/DataDaoTest.java | 163 ++++++++++++++++++ 1 file changed, 163 insertions(+) diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java index c1c8e81f8..5446ac915 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java @@ -35,6 +35,8 @@ import cz.cvut.kbss.termit.util.TypeAwareResource; import cz.cvut.kbss.termit.util.Vocabulary; import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.Triple; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; @@ -50,12 +52,15 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; import org.springframework.test.annotation.DirtiesContext; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Optional; +import java.util.Set; import static cz.cvut.kbss.termit.environment.Environment.getPrimaryLabel; import static org.hamcrest.MatcherAssert.assertThat; @@ -63,6 +68,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -390,4 +396,161 @@ void findAllCustomAttributesByDomainReturnsCustomAttributesWithSpecifiedDomain() CustomAttributeSpecifications.hasDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)))); assertEquals(List.of(pTwo), result); } + + @Test + void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithSimpleSubject() { + // Subject of the custom attribute annotation is IRI + + final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("AttributeName", "en"), null); + attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); + transactional(() -> em.persist(attribute)); + + final URI termIri = Generator.generateUri(); + final URI context = Generator.generateUri(); + final String value = "Custom attribute value"; + + transactional(() -> { + final Repository repo = em.unwrap(Repository.class); + final ValueFactory vf = repo.getValueFactory(); + try (final RepositoryConnection connection = repo.getConnection()) { + // term a skos:Concept + connection.add( + vf.createIRI(termIri.toString()), // subject + RDF.TYPE, // predicate + SKOS.CONCEPT, // object + vf.createIRI(context.toString()) // context + ); + // term attribute value + connection.add( + vf.createIRI(termIri.toString()), // subject + vf.createIRI(attribute.getUri().toString()), // predicate + vf.createLiteral(value), // object + vf.createIRI(context.toString()) // context + ); + connection.commit(); + } + }); + + transactional(() -> { + final Page result = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); + + assertEquals(1, result.getTotalElements()); + final Statement statement = result.getContent().getFirst(); + assertEquals(termIri.toString(), statement.getSubject().stringValue()); + assertEquals(attribute.getUri().toString(), statement.getPredicate().stringValue()); + assertEquals(value, statement.getObject().stringValue()); + }); + } + + @Test + void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithTripleSubject() { + // subject of custom attribute is another triple + + final URI relation = URI.create(SKOS.RELATED.stringValue()); + final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute", "en"), null); + attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.RDF.STATEMENT)); + attribute.setAnnotatedRelationships(Set.of(relation)); + transactional(() -> em.persist(attribute)); + + final URI termOne = Generator.generateUri(); + final URI termTwo = Generator.generateUri(); + final URI context = Generator.generateUri(); + final String value = "Custom attribute value"; + + transactional(() -> { + final Repository repo = em.unwrap(Repository.class); + final ValueFactory vf = repo.getValueFactory(); + + // termOne skos:related termTwo + final Triple subjectTriple = vf.createTriple( + vf.createIRI(termOne.toString()), // subject + SKOS.RELATED, // predicate + vf.createIRI(termTwo.toString()) // object + ); + + try (final RepositoryConnection connection = repo.getConnection()) { + // triple attribute value + connection.add(subjectTriple, // subject (another triple) + vf.createIRI(attribute.getUri().toString()), // predicate + vf.createLiteral(value), // object + vf.createIRI(context.toString()) // context + ); + connection.commit(); + } + }); + + transactional(() -> { + final Page result = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); + + assertEquals(1, result.getTotalElements()); + final Statement statement = result.getContent().getFirst(); + assertInstanceOf(Triple.class, statement.getSubject()); + + final Triple resultTriple = (Triple) statement.getSubject(); + assertEquals(termOne.toString(), resultTriple.getSubject().stringValue()); + assertEquals(relation.toString(), resultTriple.getPredicate().stringValue()); + assertEquals(termTwo.toString(), resultTriple.getObject().stringValue()); + + assertEquals(attribute.getUri().toString(), statement.getPredicate().stringValue()); + assertEquals(value, statement.getObject().stringValue()); + }); + } + + @Test + void findCustomAttributeUsageReturnsTotalElementsCountMatchingNumberOfUsagesOfRequestedAttribute() { + // Unrelated attribute has a single usage, attribute B has two usages + final CustomAttribute unrelated = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute A", "en"), null); + unrelated.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); + + final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute B", "en"), null); + attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); + + transactional(() -> { + em.persist(unrelated); + em.persist(attribute); + }); + + final URI termOne = Generator.generateUri(); + final URI termTwo = Generator.generateUri(); + final URI context = Generator.generateUri(); + + transactional(() -> { + final Repository repo = em.unwrap(Repository.class); + final ValueFactory vf = repo.getValueFactory(); + try (final RepositoryConnection connection = repo.getConnection()) { + // one usage of unrelated attribute + connection.add( + vf.createIRI(termOne.toString()), + vf.createIRI(unrelated.getUri().toString()), + vf.createLiteral("A value"), + vf.createIRI(context.toString()) + ); + + // two usages of attribute + connection.add( + vf.createIRI(termOne.toString()), + vf.createIRI(attribute.getUri().toString()), + vf.createLiteral("B value one"), + vf.createIRI(context.toString()) + ); + connection.add( + vf.createIRI(termTwo.toString()), + vf.createIRI(attribute.getUri().toString()), + vf.createLiteral("B value two"), + vf.createIRI(context.toString()) + ); + connection.commit(); + } + }); + + transactional(() -> { + final Page result = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); + assertEquals(2, result.getTotalElements()); + }); + } + } From 02a126ed19ccfc8560a9b09914ac735412da9323 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 14:14:48 +0200 Subject: [PATCH 03/19] [Enhancement kbss-cvut/termit-ui#820] Add DataController endpoint for custom attribute removal --- .../kbss/termit/persistence/dao/DataDao.java | 44 +++- .../cvut/kbss/termit/rest/DataController.java | 29 ++ .../repository/DataRepositoryService.java | 16 ++ .../termit/persistence/dao/DataDaoTest.java | 248 ++++++++++++------ 4 files changed, 259 insertions(+), 78 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index b76beaada..413f2aca8 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -406,7 +406,49 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl return new PageImpl<>(statements, pageable, totalCount); } catch (RuntimeException e) { - throw new PersistenceException(e); + throw new PersistenceException("Failed to find custom attribute usage", e); + } + } + + public void removeAllCustomAttributeUsages(CustomAttribute attribute) { + Objects.requireNonNull(attribute); + Objects.requireNonNull(attribute.getUri()); + Objects.requireNonNull(attribute.getDomain()); + Objects.requireNonNull(attribute.getRange()); + try { + em.createNativeQuery(""" + DELETE { + GRAPH ?context { + ?subject ?attribute ?object . + } + } WHERE { + GRAPH ?context { + { + ?subject ?attribute ?object . + FILTER((isLiteral(?object) && DATATYPE(?object) = ?range)) + } UNION { + ?subject ?attribute ?object . + ?object a ?range . + } + ?subject a ?domain . + } + } + """) + .setParameter("attribute", attribute.getUri()) + .setParameter("domain", attribute.getDomain()) + .setParameter("range", attribute.getRange()) + .executeUpdate(); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to remove all custom attribute usages", e); + } + } + + public void removeCustomAttribute(CustomAttribute attribute) { + Objects.requireNonNull(attribute); + try { + em.remove(attribute); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to remove custom attribute", e); } } } diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index 0194ae50c..fca2752f2 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -44,6 +44,7 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @@ -161,6 +162,34 @@ public ResponseEntity> getCustomAttributeUsage(@Parameter( .body(result.getContent()); } + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, + description = "Removes the custom attribute, " + + "if it has usages, force parameter is required and the removal will remove all the usages as well.") + @ApiResponses({ + @ApiResponse(responseCode = "204", description = "Custom attribute was removed"), + @ApiResponse(responseCode = "400", description = "Force parameter is required for removal of attribute with usages"), + @ApiResponse(responseCode = "404", description = "Attribute not found") + }) + @ResponseStatus(HttpStatus.NO_CONTENT) + @DeleteMapping(value = "/custom-attributes/{localName}") + public void removeCustomAttribute(@Parameter( + description = "Locally (in the context of the namespace) unique part of the attribute identifier.", + example = "custom-attribute") + @PathVariable String localName, + @Parameter( + description = "Custom attribute identifier namespace", + example = "http://onto.fel.cvut.cz/ontologies/application/termit/custom-attribute/" + ) + @RequestParam String namespace, + @Parameter( + description = "Indicates whether to force the removal of the attribute and its usages.", + example = "false" + ) + @RequestParam boolean force) { + final URI identifier = identifierResolver.resolveIdentifier(namespace, localName); + dataService.removeCustomAttribute(identifier, force); + } + @Operation(description = "Gets basic metadata for a RDFS resource with the specified IRI.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "RDSF resource metadata."), diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index 85ef97963..8e97cdfbc 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -28,6 +28,7 @@ import cz.cvut.kbss.termit.persistence.dao.spec.CustomAttributeSpecifications; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.util.Configuration; +import cz.cvut.kbss.termit.util.Utils; import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import org.eclipse.rdf4j.model.Statement; @@ -211,4 +212,19 @@ public Optional getLabel(URI id, @Nullable String language) { public Page findCustomAttributeUsage(URI identifier, Pageable pageable) { return dataDao.findCustomAttributeUsage(identifier, pageable); } + + @Transactional + public void removeCustomAttribute(URI identifier, boolean force) { + final boolean hasUsage = findCustomAttributeUsage(identifier, Pageable.ofSize(1)).hasContent(); + if (hasUsage && !force) { + throw new ValidationException("Unable to remove a CustomAttribute with usages: " + Utils.uriToString(identifier)); + } + + final CustomAttribute attribute = dataDao.findCustomAttribute(identifier) + .orElseThrow(() -> NotFoundException + .create(CustomAttribute.class, identifier)); + + dataDao.removeAllCustomAttributeUsages(attribute); + dataDao.removeCustomAttribute(attribute); + } } diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java index 5446ac915..d5bc6ed14 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java @@ -34,12 +34,16 @@ import cz.cvut.kbss.termit.service.export.ExportFormat; import cz.cvut.kbss.termit.util.TypeAwareResource; import cz.cvut.kbss.termit.util.Vocabulary; +import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; +import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.Triple; +import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; +import org.eclipse.rdf4j.model.util.Values; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.RDFS; import org.eclipse.rdf4j.model.vocabulary.SKOS; @@ -61,6 +65,7 @@ import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.stream.Stream; import static cz.cvut.kbss.termit.environment.Environment.getPrimaryLabel; import static org.hamcrest.MatcherAssert.assertThat; @@ -397,6 +402,24 @@ void findAllCustomAttributesByDomainReturnsCustomAttributesWithSpecifiedDomain() assertEquals(List.of(pTwo), result); } + private void withStatements(Statement... statements) { + transactional(() -> { + final Repository repo = em.unwrap(Repository.class); + try (final RepositoryConnection connection = repo.getConnection()) { + Stream.of(statements).forEach(connection::add); + connection.commit(); + } + }); + } + + private static Statement statement(Resource subject, IRI predicate, Value object, Resource context) { + return Values.getValueFactory().createStatement( + subject, + predicate, + object, + context); + } + @Test void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithSimpleSubject() { // Subject of the custom attribute annotation is IRI @@ -406,31 +429,23 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithSimpleSubject() attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); transactional(() -> em.persist(attribute)); - final URI termIri = Generator.generateUri(); - final URI context = Generator.generateUri(); - final String value = "Custom attribute value"; + final IRI termIri = Values.iri(Generator.generateUri().toString()); + final IRI context = Values.iri(Generator.generateUri().toString()); + final Value value = Values.literal("Custom attribute value"); - transactional(() -> { - final Repository repo = em.unwrap(Repository.class); - final ValueFactory vf = repo.getValueFactory(); - try (final RepositoryConnection connection = repo.getConnection()) { + withStatements( // term a skos:Concept - connection.add( - vf.createIRI(termIri.toString()), // subject - RDF.TYPE, // predicate - SKOS.CONCEPT, // object - vf.createIRI(context.toString()) // context - ); + statement(termIri, + RDF.TYPE, + SKOS.CONCEPT, + context), + // term attribute value - connection.add( - vf.createIRI(termIri.toString()), // subject - vf.createIRI(attribute.getUri().toString()), // predicate - vf.createLiteral(value), // object - vf.createIRI(context.toString()) // context - ); - connection.commit(); - } - }); + statement(termIri, + Values.iri(attribute.getUri().toString()), + value, + context) + ); transactional(() -> { final Page result = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); @@ -439,7 +454,7 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithSimpleSubject() final Statement statement = result.getContent().getFirst(); assertEquals(termIri.toString(), statement.getSubject().stringValue()); assertEquals(attribute.getUri().toString(), statement.getPredicate().stringValue()); - assertEquals(value, statement.getObject().stringValue()); + assertEquals(value, statement.getObject()); }); } @@ -454,32 +469,25 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithTripleSubject() attribute.setAnnotatedRelationships(Set.of(relation)); transactional(() -> em.persist(attribute)); - final URI termOne = Generator.generateUri(); - final URI termTwo = Generator.generateUri(); - final URI context = Generator.generateUri(); - final String value = "Custom attribute value"; - - transactional(() -> { - final Repository repo = em.unwrap(Repository.class); - final ValueFactory vf = repo.getValueFactory(); + final IRI termOne = Values.iri(Generator.generateUri().toString()); + final IRI termTwo = Values.iri(Generator.generateUri().toString()); + final IRI context = Values.iri(Generator.generateUri().toString()); + final Value value = Values.literal("Custom attribute value"); - // termOne skos:related termTwo - final Triple subjectTriple = vf.createTriple( - vf.createIRI(termOne.toString()), // subject - SKOS.RELATED, // predicate - vf.createIRI(termTwo.toString()) // object - ); + // termOne skos:related termTwo + final Triple subjectTriple = Values.triple( + termOne, + SKOS.RELATED, + termTwo + ); - try (final RepositoryConnection connection = repo.getConnection()) { + withStatements( // triple attribute value - connection.add(subjectTriple, // subject (another triple) - vf.createIRI(attribute.getUri().toString()), // predicate - vf.createLiteral(value), // object - vf.createIRI(context.toString()) // context - ); - connection.commit(); - } - }); + statement(subjectTriple, + Values.iri(attribute.getUri().toString()), + value, + context) + ); transactional(() -> { final Page result = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); @@ -489,12 +497,12 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithTripleSubject() assertInstanceOf(Triple.class, statement.getSubject()); final Triple resultTriple = (Triple) statement.getSubject(); - assertEquals(termOne.toString(), resultTriple.getSubject().stringValue()); + assertEquals(termOne, resultTriple.getSubject()); assertEquals(relation.toString(), resultTriple.getPredicate().stringValue()); - assertEquals(termTwo.toString(), resultTriple.getObject().stringValue()); + assertEquals(termTwo, resultTriple.getObject()); assertEquals(attribute.getUri().toString(), statement.getPredicate().stringValue()); - assertEquals(value, statement.getObject().stringValue()); + assertEquals(value, statement.getObject()); }); } @@ -514,38 +522,29 @@ void findCustomAttributeUsageReturnsTotalElementsCountMatchingNumberOfUsagesOfRe em.persist(attribute); }); - final URI termOne = Generator.generateUri(); - final URI termTwo = Generator.generateUri(); - final URI context = Generator.generateUri(); + final IRI termOne = Values.iri(Generator.generateUri().toString()); + final IRI termTwo = Values.iri(Generator.generateUri().toString()); + final IRI context = Values.iri(Generator.generateUri().toString()); - transactional(() -> { - final Repository repo = em.unwrap(Repository.class); - final ValueFactory vf = repo.getValueFactory(); - try (final RepositoryConnection connection = repo.getConnection()) { + + withStatements( // one usage of unrelated attribute - connection.add( - vf.createIRI(termOne.toString()), - vf.createIRI(unrelated.getUri().toString()), - vf.createLiteral("A value"), - vf.createIRI(context.toString()) - ); + statement(termOne, + Values.iri(unrelated.getUri().toString()), + Values.literal("unrelated value"), + context), // two usages of attribute - connection.add( - vf.createIRI(termOne.toString()), - vf.createIRI(attribute.getUri().toString()), - vf.createLiteral("B value one"), - vf.createIRI(context.toString()) - ); - connection.add( - vf.createIRI(termTwo.toString()), - vf.createIRI(attribute.getUri().toString()), - vf.createLiteral("B value two"), - vf.createIRI(context.toString()) - ); - connection.commit(); - } - }); + statement(termOne, + Values.iri(attribute.getUri().toString()), + Values.literal("B value one"), + context), + + statement(termTwo, + Values.iri(attribute.getUri().toString()), + Values.literal("B value two"), + context) + ); transactional(() -> { final Page result = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); @@ -553,4 +552,99 @@ void findCustomAttributeUsageReturnsTotalElementsCountMatchingNumberOfUsagesOfRe }); } + @Test + void removeAllCustomAttributeUsagesRemovesUsagesWithSimpleSubjectAndKeepsOtherStatements() { + // Subject of the custom attribute usage is a plain IRI + final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute", "en"), null); + attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); + attribute.setRange(URI.create(XSD.STRING)); + transactional(() -> em.persist(attribute)); + + final IRI termIri = Values.iri(Generator.generateUri().toString()); + final IRI context = Values.iri(Generator.generateUri().toString()); + final Value value = Values.literal("Custom attribute value"); + + withStatements( + // term a skos:Concept + statement( + termIri, + RDF.TYPE, + SKOS.CONCEPT, + context + ), + // term attribute value + statement( + termIri, + Values.iri(attribute.getUri().toString()), + value, + context + ) + ); + + transactional(() -> sut.removeAllCustomAttributeUsages(attribute)); + + transactional(() -> { + final Page usage = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); + assertEquals(0, usage.getTotalElements()); + + boolean typeAssertionExists = em.createNativeQuery("ASK WHERE { GRAPH ?ctx { ?x a ?type . } }", Boolean.class) + .setParameter("x", URI.create(termIri.stringValue())) + .setParameter("type", URI.create(SKOS.CONCEPT.stringValue())) + .setParameter("ctx", URI.create(context.stringValue())) + .getSingleResult(); + assertTrue(typeAssertionExists); + }); + } + + @Test + void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOriginalAnnotatedRelationship() { + // Subject of the custom attribute usage is another triple + final URI relation = URI.create(SKOS.RELATED.stringValue()); + final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute", "en"), null); + attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.RDF.STATEMENT)); + attribute.setRange(URI.create(XSD.STRING)); + attribute.setAnnotatedRelationships(Set.of(relation)); + transactional(() -> em.persist(attribute)); + + final IRI termOne = Values.iri(Generator.generateUri().toString()); + final IRI termTwo = Values.iri(Generator.generateUri().toString()); + final IRI context = Values.iri(Generator.generateUri().toString()); + final Value value = Values.literal("Custom attribute value"); + + // termOne skos:related termTwo + final Statement subjectStatement = statement( + termOne, + Values.iri(relation.toString()), + termTwo, + context + ); + + withStatements( + subjectStatement, + // usage of the attribute on the relationship + statement( + Values.triple(subjectStatement), + Values.iri(attribute.getUri().toString()), + value, + context + ) + ); + + transactional(() -> sut.removeAllCustomAttributeUsages(attribute)); + + transactional(() -> { + final Page usage = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); + assertEquals(0, usage.getTotalElements()); + + final boolean relatedStatementExists = em.createNativeQuery("ASK WHERE { GRAPH ?ctx { ?x ?related ?y . } }", Boolean.class) + .setParameter("x", URI.create(termOne.stringValue())) + .setParameter("y", URI.create(termTwo.stringValue())) + .setParameter("related", relation) + .setParameter("ctx", URI.create(context.stringValue())) + .getSingleResult(); + assertTrue(relatedStatementExists); + }); + } } From 224f0bf06a82138a245f4ac85abbc2c278e3103d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 14:22:14 +0200 Subject: [PATCH 04/19] [Docs] Add missing javadoc for DataRepositoryService#removeCustomAttribute --- .../termit/service/repository/DataRepositoryService.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index 8e97cdfbc..d481d298b 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -213,6 +213,14 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl return dataDao.findCustomAttributeUsage(identifier, pageable); } + /** + * Removes custom attribute identified by {@code identifier}. + * If usages exist, {@code force} needs to be enabled in order to remove the attribute and its usages. + * + * @param identifier the identifier of the {@link CustomAttribute} + * @param force whether to force removal of the attribute and its usages + * @throws ValidationException if attribute usage exists and {@code force} is {@code false} + */ @Transactional public void removeCustomAttribute(URI identifier, boolean force) { final boolean hasUsage = findCustomAttributeUsage(identifier, Pageable.ofSize(1)).hasContent(); From 0eea4690858cc4e250f0fdf1759f2da54eca4327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 14:22:47 +0200 Subject: [PATCH 05/19] [Test] Add DataRepositoryService tests for custom attribute removal --- .../repository/DataRepositoryServiceTest.java | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java index f87dd2583..a5f521531 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java @@ -11,7 +11,7 @@ import cz.cvut.kbss.termit.persistence.dao.DataDao; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.util.Configuration; -import cz.cvut.kbss.termit.util.Vocabulary; +import org.eclipse.rdf4j.model.Statement; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,8 +21,11 @@ import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; import java.net.URI; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -33,6 +36,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -141,4 +145,34 @@ void updateCustomAttributeUpdatesLabelAndDescriptionOfExistingCustomAttribute() assertEquals(updated.getRange(), existing.getRange()); assertEquals(updated.getAnnotatedRelationships(), existing.getAnnotatedRelationships()); } + + @Test + void removeCustomAttributeThrowsValidationExceptionWhenUsagesExistAndForceIsFalse() { + final URI uri = Generator.generateUri(); + final Statement statement = mock(Statement.class); + + when(dataDao.findCustomAttributeUsage(uri, Pageable.ofSize(1))) + .thenReturn(new PageImpl<>(List.of(statement))); + + assertThrows(ValidationException.class, () -> sut.removeCustomAttribute(uri, false)); + } + + @Test + void removeCustomAttributeRemovesAllUsagesAndCustomAttribute() { + final URI uri = Generator.generateUri(); + final CustomAttribute attribute = new CustomAttribute(); + attribute.setUri(uri); + + final Statement statement = mock(Statement.class); + + when(dataDao.findCustomAttributeUsage(uri, Pageable.ofSize(1))) + .thenReturn(new PageImpl<>(List.of(statement))); + when(dataDao.findCustomAttribute(uri)) + .thenReturn(Optional.of(attribute)); + + sut.removeCustomAttribute(uri, true); + + verify(dataDao).removeAllCustomAttributeUsages(attribute); + verify(dataDao).removeCustomAttribute(attribute); + } } From 32afc119d686396e7020b5c2ab60b9eafe8a4224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 14:31:25 +0200 Subject: [PATCH 06/19] [Ref] Fix code indention in DataController --- .../cvut/kbss/termit/rest/DataController.java | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index fca2752f2..20cb4ea21 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -139,18 +139,18 @@ public void updateCustomAttribute(@Parameter( }) @GetMapping(value = "/custom-attributes/{localName}/usage", produces = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) public ResponseEntity> getCustomAttributeUsage(@Parameter( - description = "Locally (in the context of the namespace) unique part of the attribute identifier.", - example = "custom-attribute") - @PathVariable String localName, - @Parameter( - description = "Custom attribute identifier namespace", - example = "http://onto.fel.cvut.cz/ontologies/application/termit/custom-attribute/" - ) - @RequestParam String namespace, - @Parameter(description = ApiDocConstants.PAGE_SIZE_DESCRIPTION) - @RequestParam(name = Constants.QueryParams.PAGE_SIZE, required = false) Integer pageSize, - @Parameter(description = ApiDocConstants.PAGE_NO_DESCRIPTION) - @RequestParam(name = Constants.QueryParams.PAGE, required = false) Integer pageNo) { + description = "Locally (in the context of the namespace) unique part of the attribute identifier.", + example = "custom-attribute") + @PathVariable String localName, + @Parameter( + description = "Custom attribute identifier namespace", + example = "http://onto.fel.cvut.cz/ontologies/application/termit/custom-attribute/" + ) + @RequestParam String namespace, + @Parameter(description = ApiDocConstants.PAGE_SIZE_DESCRIPTION) + @RequestParam(name = Constants.QueryParams.PAGE_SIZE, required = false) Integer pageSize, + @Parameter(description = ApiDocConstants.PAGE_NO_DESCRIPTION) + @RequestParam(name = Constants.QueryParams.PAGE, required = false) Integer pageNo) { Pageable pageable = Constants.DEFAULT_PAGE_SPEC; if (pageSize != null && pageNo != null) { pageable = PageRequest.of(pageNo, pageSize); @@ -173,19 +173,18 @@ public ResponseEntity> getCustomAttributeUsage(@Parameter( @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping(value = "/custom-attributes/{localName}") public void removeCustomAttribute(@Parameter( - description = "Locally (in the context of the namespace) unique part of the attribute identifier.", - example = "custom-attribute") - @PathVariable String localName, - @Parameter( - description = "Custom attribute identifier namespace", - example = "http://onto.fel.cvut.cz/ontologies/application/termit/custom-attribute/" - ) - @RequestParam String namespace, - @Parameter( - description = "Indicates whether to force the removal of the attribute and its usages.", - example = "false" - ) - @RequestParam boolean force) { + description = "Locally (in the context of the namespace) unique part of the attribute identifier.", + example = "custom-attribute") + @PathVariable String localName, + @Parameter( + description = "Custom attribute identifier namespace", + example = "http://onto.fel.cvut.cz/ontologies/application/termit/custom-attribute/" + ) + @RequestParam String namespace, + @Parameter( + description = "Indicates whether to force the removal of the attribute and its usages." + ) + @RequestParam boolean force) { final URI identifier = identifierResolver.resolveIdentifier(namespace, localName); dataService.removeCustomAttribute(identifier, force); } From 5dc8db4e4493757d54ed9fb7f9a889d28d6ae893 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 14:50:05 +0200 Subject: [PATCH 07/19] [Ref] Remove domain and range validation when removing custom attribute usages and remove any triple where attribute is used as predicate --- .../kbss/termit/persistence/dao/DataDao.java | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index 413f2aca8..04011e559 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -410,11 +410,14 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl } } + /** + * Removes all triples where the {@link CustomAttribute} is used as predicate + * + * @param attribute {@link CustomAttribute} whose usages should be removed + */ public void removeAllCustomAttributeUsages(CustomAttribute attribute) { Objects.requireNonNull(attribute); Objects.requireNonNull(attribute.getUri()); - Objects.requireNonNull(attribute.getDomain()); - Objects.requireNonNull(attribute.getRange()); try { em.createNativeQuery(""" DELETE { @@ -423,20 +426,11 @@ public void removeAllCustomAttributeUsages(CustomAttribute attribute) { } } WHERE { GRAPH ?context { - { - ?subject ?attribute ?object . - FILTER((isLiteral(?object) && DATATYPE(?object) = ?range)) - } UNION { - ?subject ?attribute ?object . - ?object a ?range . - } - ?subject a ?domain . + ?subject ?attribute ?object . } } """) .setParameter("attribute", attribute.getUri()) - .setParameter("domain", attribute.getDomain()) - .setParameter("range", attribute.getRange()) .executeUpdate(); } catch (RuntimeException e) { throw new PersistenceException("Failed to remove all custom attribute usages", e); From fb7d69bd3e5fe8c5bf134a0599d431766e364475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 15:15:17 +0200 Subject: [PATCH 08/19] [Ref] Replace findCustomAttributeUsage with simple ask query in isCustomAttributeUsed --- .../kbss/termit/persistence/dao/DataDao.java | 17 +++++++++ .../repository/DataRepositoryService.java | 6 ++- .../termit/persistence/dao/DataDaoTest.java | 38 +++++++++++++++++++ .../repository/DataRepositoryServiceTest.java | 15 ++------ 4 files changed, 63 insertions(+), 13 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index 04011e559..82ab02e46 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -437,6 +437,23 @@ public void removeAllCustomAttributeUsages(CustomAttribute attribute) { } } + /** + * Checks whether the {@link CustomAttribute} is used anywhere as a predicate. + * + * @param attributeUri the URI of the attribute to check + * @return {@code true} when the identifier of the custom attribute is used as predicate, {@code false} otherwise. + */ + public boolean isCustomAttributeUsed(URI attributeUri) { + Objects.requireNonNull(attributeUri); + try { + return em.createNativeQuery("ASK { ?s ?p ?o }", Boolean.class) + .setParameter("p", attributeUri) + .getSingleResult(); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to check for custom attribute usage", e); + } + } + public void removeCustomAttribute(CustomAttribute attribute) { Objects.requireNonNull(attribute); try { diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index d481d298b..de54c78ae 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -223,7 +223,7 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl */ @Transactional public void removeCustomAttribute(URI identifier, boolean force) { - final boolean hasUsage = findCustomAttributeUsage(identifier, Pageable.ofSize(1)).hasContent(); + final boolean hasUsage = dataDao.isCustomAttributeUsed(identifier); if (hasUsage && !force) { throw new ValidationException("Unable to remove a CustomAttribute with usages: " + Utils.uriToString(identifier)); } @@ -234,5 +234,9 @@ public void removeCustomAttribute(URI identifier, boolean force) { dataDao.removeAllCustomAttributeUsages(attribute); dataDao.removeCustomAttribute(attribute); + // ensure the attribute is no longer used + if (dataDao.isCustomAttributeUsed(identifier)) { + throw new ValidationException("Failed to remove a CustomAttribute with usages: " + Utils.uriToString(identifier)); + } } } diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java index d5bc6ed14..1abcb53f3 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java @@ -647,4 +647,42 @@ void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOrigina assertTrue(relatedStatementExists); }); } + + @Test + void isCustomAttributeUsedReturnsTrueWhenAttributeIsUsedAsPredicate() { + final URI attributeUri = Generator.generateUri(); + final IRI subject = Values.iri(Generator.generateUri().toString()); + final IRI context = Values.iri(Generator.generateUri().toString()); + final Value object = Values.literal("Sample value"); + + withStatements(statement(subject, Values.iri(attributeUri.toString()), object, context)); + + final boolean result = sut.isCustomAttributeUsed(attributeUri); + assertTrue(result); + } + + @Test + void isCustomAttributeUsedReturnsFalseWhenAttributeIsNotUsed() { + final URI attributeUri = Generator.generateUri(); + + final boolean result = sut.isCustomAttributeUsed(attributeUri); + assertFalse(result); + } + + @Test + void isCustomAttributeUsedReturnsFalseWhenAttributeIsNotUsedAsPredicate() { + final URI attributeUri = Generator.generateUri(); + final IRI subject = Values.iri(Generator.generateUri().toString()); + final IRI attributeIri = Values.iri(attributeUri.toString()); + final IRI predicate = Values.iri(Generator.generateUri().toString()); + final IRI context = Values.iri(Generator.generateUri().toString()); + final Value object = Values.literal("Sample value"); + + withStatements(statement(subject, predicate, object, context)); + withStatements(statement(attributeIri, predicate, object, context)); + withStatements(statement(subject, predicate, attributeIri, context)); + + final boolean result = sut.isCustomAttributeUsed(attributeUri); + assertFalse(result); + } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java index a5f521531..fa96071c6 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java @@ -11,7 +11,6 @@ import cz.cvut.kbss.termit.persistence.dao.DataDao; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.util.Configuration; -import org.eclipse.rdf4j.model.Statement; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,11 +20,8 @@ import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.Pageable; import java.net.URI; -import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -36,7 +32,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -149,10 +144,8 @@ void updateCustomAttributeUpdatesLabelAndDescriptionOfExistingCustomAttribute() @Test void removeCustomAttributeThrowsValidationExceptionWhenUsagesExistAndForceIsFalse() { final URI uri = Generator.generateUri(); - final Statement statement = mock(Statement.class); - when(dataDao.findCustomAttributeUsage(uri, Pageable.ofSize(1))) - .thenReturn(new PageImpl<>(List.of(statement))); + when(dataDao.isCustomAttributeUsed(uri)).thenReturn(true); assertThrows(ValidationException.class, () -> sut.removeCustomAttribute(uri, false)); } @@ -163,10 +156,8 @@ void removeCustomAttributeRemovesAllUsagesAndCustomAttribute() { final CustomAttribute attribute = new CustomAttribute(); attribute.setUri(uri); - final Statement statement = mock(Statement.class); - - when(dataDao.findCustomAttributeUsage(uri, Pageable.ofSize(1))) - .thenReturn(new PageImpl<>(List.of(statement))); + when(dataDao.isCustomAttributeUsed(uri)).thenReturn(true) + .thenReturn(false); when(dataDao.findCustomAttribute(uri)) .thenReturn(Optional.of(attribute)); From 3dfcde3707eac62206da509292f3b6fcb912af74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 15:32:53 +0200 Subject: [PATCH 09/19] [Bug] Add missing authorization for custom attribute manipulation endpoints --- src/main/java/cz/cvut/kbss/termit/rest/DataController.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index 20cb4ea21..35d2676a8 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -119,6 +119,7 @@ public ResponseEntity createCustomAttribute(@Parameter(description = "Attr @ApiResponse(responseCode = "404", description = "Attribute not found.") }) @ResponseStatus(HttpStatus.NO_CONTENT) + @PreAuthorize("hasRole('" + SecurityConstants.ROLE_FULL_USER + "')") @PutMapping(value = "/custom-attributes/{localName}", consumes = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) public void updateCustomAttribute(@Parameter( @@ -137,6 +138,7 @@ public void updateCustomAttribute(@Parameter( @ApiResponse(responseCode = "200", description = "The list of triples with the custom attribute as predicate"), @ApiResponse(responseCode = "404", description = "Attribute not found") }) + @PreAuthorize("hasRole('" + SecurityConstants.ROLE_FULL_USER + "')") @GetMapping(value = "/custom-attributes/{localName}/usage", produces = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) public ResponseEntity> getCustomAttributeUsage(@Parameter( description = "Locally (in the context of the namespace) unique part of the attribute identifier.", @@ -170,6 +172,7 @@ public ResponseEntity> getCustomAttributeUsage(@Parameter( @ApiResponse(responseCode = "400", description = "Force parameter is required for removal of attribute with usages"), @ApiResponse(responseCode = "404", description = "Attribute not found") }) + @PreAuthorize("hasRole('" + SecurityConstants.ROLE_FULL_USER + "')") @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping(value = "/custom-attributes/{localName}") public void removeCustomAttribute(@Parameter( From 0adcf398c8a804a9e2f0c9f7639486ccf3a01913 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 27 Aug 2026 16:10:40 +0200 Subject: [PATCH 10/19] [Ref] Add logging for custom attribute removal --- src/main/java/cz/cvut/kbss/termit/rest/DataController.java | 1 + .../kbss/termit/service/repository/DataRepositoryService.java | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index 35d2676a8..960892ce9 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -190,6 +190,7 @@ public void removeCustomAttribute(@Parameter( @RequestParam boolean force) { final URI identifier = identifierResolver.resolveIdentifier(namespace, localName); dataService.removeCustomAttribute(identifier, force); + LOG.debug("Removed custom attribute: {}", identifier); } @Operation(description = "Gets basic metadata for a RDFS resource with the specified IRI.") diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index de54c78ae..f1ef740fe 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -232,7 +232,9 @@ public void removeCustomAttribute(URI identifier, boolean force) { .orElseThrow(() -> NotFoundException .create(CustomAttribute.class, identifier)); + LOG.debug("Removing all usage of custom attribute {}", identifier); dataDao.removeAllCustomAttributeUsages(attribute); + LOG.debug("Removing custom attribute {}", identifier); dataDao.removeCustomAttribute(attribute); // ensure the attribute is no longer used if (dataDao.isCustomAttributeUsed(identifier)) { From 324d9df8ea4109bb7f2dec6a07e5fd35ac50320b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 28 Aug 2026 10:12:16 +0200 Subject: [PATCH 11/19] [Bug] Evict jopa cache for contexts affected by custom attribute removal --- .../kbss/termit/persistence/dao/DataDao.java | 35 +++++++++++++++++++ .../repository/DataRepositoryService.java | 9 +++++ .../repository/DataRepositoryServiceTest.java | 20 +++++++++++ 3 files changed, 64 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index 82ab02e46..82216de70 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -19,6 +19,7 @@ import cz.cvut.kbss.jopa.exceptions.NoResultException; import cz.cvut.kbss.jopa.exceptions.NoUniqueResultException; +import cz.cvut.kbss.jopa.model.Cache; import cz.cvut.kbss.jopa.model.EntityManager; import cz.cvut.kbss.jopa.model.descriptors.Descriptor; import cz.cvut.kbss.jopa.model.descriptors.EntityDescriptor; @@ -410,6 +411,30 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl } } + /** + * Finds contexts in which the custom attribute is used + * + * @param customAttribute the custom attribute to look up + * @return contexts where the attribute URI is used as a predicate + */ + public List findCustomAttributeUsageContexts(CustomAttribute customAttribute) { + Objects.requireNonNull(customAttribute); + Objects.requireNonNull(customAttribute.getUri()); + try { + return em.createNativeQuery(""" + SELECT DISTINCT ?context WHERE { + GRAPH ?context { + ?subject ?attribute ?object . + } + } + """, URI.class) + .setParameter("attribute", customAttribute.getUri()) + .getResultList(); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to find custom attribute usage contexts", e); + } + } + /** * Removes all triples where the {@link CustomAttribute} is used as predicate * @@ -462,4 +487,14 @@ public void removeCustomAttribute(CustomAttribute attribute) { throw new PersistenceException("Failed to remove custom attribute", e); } } + + /** + * Evicts {@link cz.cvut.kbss.jopa.model.EntityManagerFactory} cache for each specified context. + * + * @param contexts context to evict from cache + */ + public void evictCacheForContexts(List contexts) { + final Cache emfCache = em.getEntityManagerFactory().getCache(); + contexts.forEach(emfCache::evict); + } } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index f1ef740fe..a311c73f7 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -44,6 +44,7 @@ import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; @Service public class DataRepositoryService { @@ -232,6 +233,8 @@ public void removeCustomAttribute(URI identifier, boolean force) { .orElseThrow(() -> NotFoundException .create(CustomAttribute.class, identifier)); + final List affectedContexts = dataDao.findCustomAttributeUsageContexts(attribute); + LOG.debug("Removing all usage of custom attribute {}", identifier); dataDao.removeAllCustomAttributeUsages(attribute); LOG.debug("Removing custom attribute {}", identifier); @@ -240,5 +243,11 @@ public void removeCustomAttribute(URI identifier, boolean force) { if (dataDao.isCustomAttributeUsed(identifier)) { throw new ValidationException("Failed to remove a CustomAttribute with usages: " + Utils.uriToString(identifier)); } + + LOG.atDebug() + .addArgument(() -> affectedContexts.stream().map(Utils::uriToString).collect(Collectors.joining(", "))) + .log("Evicting cache for contexts affected by custom attribute removal: {}"); + + dataDao.evictCacheForContexts(affectedContexts); } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java index fa96071c6..43de54cee 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java @@ -22,6 +22,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import java.net.URI; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -166,4 +167,23 @@ void removeCustomAttributeRemovesAllUsagesAndCustomAttribute() { verify(dataDao).removeAllCustomAttributeUsages(attribute); verify(dataDao).removeCustomAttribute(attribute); } + + @Test + void removeCustomAttributeEvictsCacheForAffectedContexts() { + final List affectedContexts = List.of(Generator.generateUri(), Generator.generateUri()); + final URI uri = Generator.generateUri(); + final CustomAttribute attribute = new CustomAttribute(); + attribute.setUri(uri); + + when(dataDao.isCustomAttributeUsed(uri)).thenReturn(true) + .thenReturn(false); + when(dataDao.findCustomAttribute(uri)) + .thenReturn(Optional.of(attribute)); + when(dataDao.findCustomAttributeUsageContexts(attribute)) + .thenReturn(affectedContexts); + + sut.removeCustomAttribute(uri, true); + + verify(dataDao).evictCacheForContexts(affectedContexts); + } } From f7404778e94f9dbeb3a3290a8f3a14ff9c60659e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 09:16:56 +0200 Subject: [PATCH 12/19] [Ref] Replace force parameter for custom attribute removal with removeUsages parameter allowing to keep custom attribute usages --- .../kbss/termit/persistence/dao/DataDao.java | 17 --------- .../cvut/kbss/termit/rest/DataController.java | 7 ++-- .../repository/DataRepositoryService.java | 34 ++++++++--------- .../termit/persistence/dao/DataDaoTest.java | 38 ------------------- .../repository/DataRepositoryServiceTest.java | 18 +++++---- 5 files changed, 31 insertions(+), 83 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index 82216de70..9f6c4f89c 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -462,23 +462,6 @@ public void removeAllCustomAttributeUsages(CustomAttribute attribute) { } } - /** - * Checks whether the {@link CustomAttribute} is used anywhere as a predicate. - * - * @param attributeUri the URI of the attribute to check - * @return {@code true} when the identifier of the custom attribute is used as predicate, {@code false} otherwise. - */ - public boolean isCustomAttributeUsed(URI attributeUri) { - Objects.requireNonNull(attributeUri); - try { - return em.createNativeQuery("ASK { ?s ?p ?o }", Boolean.class) - .setParameter("p", attributeUri) - .getSingleResult(); - } catch (RuntimeException e) { - throw new PersistenceException("Failed to check for custom attribute usage", e); - } - } - public void removeCustomAttribute(CustomAttribute attribute) { Objects.requireNonNull(attribute); try { diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index 960892ce9..29e4192f9 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -185,11 +185,12 @@ public void removeCustomAttribute(@Parameter( ) @RequestParam String namespace, @Parameter( - description = "Indicates whether to force the removal of the attribute and its usages." + description = "Indicates whether to remove the usages of the custom attribute as well" + + "When false, only the attribute itself will be removed, its usages will be kept." ) - @RequestParam boolean force) { + @RequestParam boolean removeUsages) { final URI identifier = identifierResolver.resolveIdentifier(namespace, localName); - dataService.removeCustomAttribute(identifier, force); + dataService.removeCustomAttribute(identifier, removeUsages); LOG.debug("Removed custom attribute: {}", identifier); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index a311c73f7..03374bd2a 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -41,6 +41,7 @@ import org.springframework.transaction.annotation.Transactional; import java.net.URI; +import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -219,35 +220,32 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl * If usages exist, {@code force} needs to be enabled in order to remove the attribute and its usages. * * @param identifier the identifier of the {@link CustomAttribute} - * @param force whether to force removal of the attribute and its usages + * @param removeUsages whether to also remove all usages of the {@link CustomAttribute} * @throws ValidationException if attribute usage exists and {@code force} is {@code false} */ @Transactional - public void removeCustomAttribute(URI identifier, boolean force) { - final boolean hasUsage = dataDao.isCustomAttributeUsed(identifier); - if (hasUsage && !force) { - throw new ValidationException("Unable to remove a CustomAttribute with usages: " + Utils.uriToString(identifier)); - } - + public void removeCustomAttribute(URI identifier, boolean removeUsages) { final CustomAttribute attribute = dataDao.findCustomAttribute(identifier) .orElseThrow(() -> NotFoundException .create(CustomAttribute.class, identifier)); - final List affectedContexts = dataDao.findCustomAttributeUsageContexts(attribute); + List affectedContexts = Collections.emptyList(); + if (removeUsages) { + affectedContexts = dataDao.findCustomAttributeUsageContexts(attribute); + LOG.debug("Removing all usage of custom attribute {}", identifier); + dataDao.removeAllCustomAttributeUsages(attribute); + } - LOG.debug("Removing all usage of custom attribute {}", identifier); - dataDao.removeAllCustomAttributeUsages(attribute); LOG.debug("Removing custom attribute {}", identifier); dataDao.removeCustomAttribute(attribute); - // ensure the attribute is no longer used - if (dataDao.isCustomAttributeUsed(identifier)) { - throw new ValidationException("Failed to remove a CustomAttribute with usages: " + Utils.uriToString(identifier)); - } - LOG.atDebug() - .addArgument(() -> affectedContexts.stream().map(Utils::uriToString).collect(Collectors.joining(", "))) - .log("Evicting cache for contexts affected by custom attribute removal: {}"); + if (!affectedContexts.isEmpty()) { + final List contextsToEvict = affectedContexts; + LOG.atDebug() + .addArgument(() -> contextsToEvict.stream().map(Utils::uriToString).collect(Collectors.joining(", "))) + .log("Evicting cache for contexts affected by custom attribute removal: {}"); - dataDao.evictCacheForContexts(affectedContexts); + dataDao.evictCacheForContexts(contextsToEvict); + } } } diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java index 1abcb53f3..d5bc6ed14 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java @@ -647,42 +647,4 @@ void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOrigina assertTrue(relatedStatementExists); }); } - - @Test - void isCustomAttributeUsedReturnsTrueWhenAttributeIsUsedAsPredicate() { - final URI attributeUri = Generator.generateUri(); - final IRI subject = Values.iri(Generator.generateUri().toString()); - final IRI context = Values.iri(Generator.generateUri().toString()); - final Value object = Values.literal("Sample value"); - - withStatements(statement(subject, Values.iri(attributeUri.toString()), object, context)); - - final boolean result = sut.isCustomAttributeUsed(attributeUri); - assertTrue(result); - } - - @Test - void isCustomAttributeUsedReturnsFalseWhenAttributeIsNotUsed() { - final URI attributeUri = Generator.generateUri(); - - final boolean result = sut.isCustomAttributeUsed(attributeUri); - assertFalse(result); - } - - @Test - void isCustomAttributeUsedReturnsFalseWhenAttributeIsNotUsedAsPredicate() { - final URI attributeUri = Generator.generateUri(); - final IRI subject = Values.iri(Generator.generateUri().toString()); - final IRI attributeIri = Values.iri(attributeUri.toString()); - final IRI predicate = Values.iri(Generator.generateUri().toString()); - final IRI context = Values.iri(Generator.generateUri().toString()); - final Value object = Values.literal("Sample value"); - - withStatements(statement(subject, predicate, object, context)); - withStatements(statement(attributeIri, predicate, object, context)); - withStatements(statement(subject, predicate, attributeIri, context)); - - final boolean result = sut.isCustomAttributeUsed(attributeUri); - assertFalse(result); - } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java index 43de54cee..91214af25 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java @@ -33,6 +33,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -143,12 +145,18 @@ void updateCustomAttributeUpdatesLabelAndDescriptionOfExistingCustomAttribute() } @Test - void removeCustomAttributeThrowsValidationExceptionWhenUsagesExistAndForceIsFalse() { + void removeCustomAttributeKeepsUsagesWhenRemoveUsagesIsFalse() { final URI uri = Generator.generateUri(); + final CustomAttribute attribute = new CustomAttribute(); + attribute.setUri(uri); + + when(dataDao.findCustomAttribute(uri)) + .thenReturn(Optional.of(attribute)); - when(dataDao.isCustomAttributeUsed(uri)).thenReturn(true); + sut.removeCustomAttribute(uri, false); - assertThrows(ValidationException.class, () -> sut.removeCustomAttribute(uri, false)); + verify(dataDao, never()).removeAllCustomAttributeUsages(any()); + verify(dataDao).removeCustomAttribute(attribute); } @Test @@ -157,8 +165,6 @@ void removeCustomAttributeRemovesAllUsagesAndCustomAttribute() { final CustomAttribute attribute = new CustomAttribute(); attribute.setUri(uri); - when(dataDao.isCustomAttributeUsed(uri)).thenReturn(true) - .thenReturn(false); when(dataDao.findCustomAttribute(uri)) .thenReturn(Optional.of(attribute)); @@ -175,8 +181,6 @@ void removeCustomAttributeEvictsCacheForAffectedContexts() { final CustomAttribute attribute = new CustomAttribute(); attribute.setUri(uri); - when(dataDao.isCustomAttributeUsed(uri)).thenReturn(true) - .thenReturn(false); when(dataDao.findCustomAttribute(uri)) .thenReturn(Optional.of(attribute)); when(dataDao.findCustomAttributeUsageContexts(attribute)) From 88b44edbb424e8fa2f9aaff000e2c9b41bfa46fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 09:46:02 +0200 Subject: [PATCH 13/19] [Bug] Ensure custom artifact removal does not affect vocabulary snapshots --- .../kbss/termit/persistence/dao/DataDao.java | 15 +++++ .../termit/persistence/dao/DataDaoTest.java | 59 ++++++++++++++++++- 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index 9f6c4f89c..25c900d0a 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -42,6 +42,7 @@ import cz.cvut.kbss.termit.util.Configuration.Persistence; import cz.cvut.kbss.termit.util.TypeAwareByteArrayResource; import cz.cvut.kbss.termit.util.TypeAwareResource; +import cz.cvut.kbss.termit.util.Vocabulary; import jakarta.annotation.Nullable; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; @@ -333,6 +334,7 @@ private int countCustomAttributeUsage(RepositoryConnection con, String whereQuer final TupleQuery countQuery = con.prepareTupleQuery("SELECT (COUNT(*) AS ?count) " + whereQuery); countQuery.setBinding("predicate", predicate); + countQuery.setBinding("versionOfVocabulary", Values.iri(Vocabulary.s_c_version_of_vocabulary)); countQuery.setIncludeInferred(false); try (TupleQueryResult result = countQuery.evaluate()) { @@ -348,6 +350,8 @@ private List findCustomAttributeUsage(RepositoryConnection con, Strin " OFFSET " + offset); pageQuery.setBinding("predicate", predicate); + pageQuery.setBinding("versionOfVocabulary", Values.iri(Vocabulary.s_c_version_of_vocabulary)); + pageQuery.setIncludeInferred(false); final List statements = new ArrayList<>(resultLimit); @@ -391,6 +395,9 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl WHERE { GRAPH ?context { ?subject ?predicate ?object . + FILTER NOT EXISTS { + ?context a ?versionOfVocabulary . + } } } """; @@ -425,10 +432,14 @@ public List findCustomAttributeUsageContexts(CustomAttribute customAttribut SELECT DISTINCT ?context WHERE { GRAPH ?context { ?subject ?attribute ?object . + FILTER NOT EXISTS { + ?context a ?versionOfVocabulary . + } } } """, URI.class) .setParameter("attribute", customAttribute.getUri()) + .setParameter("versionOfVocabulary", URI.create(Vocabulary.s_c_version_of_vocabulary)) .getResultList(); } catch (RuntimeException e) { throw new PersistenceException("Failed to find custom attribute usage contexts", e); @@ -452,10 +463,14 @@ public void removeAllCustomAttributeUsages(CustomAttribute attribute) { } WHERE { GRAPH ?context { ?subject ?attribute ?object . + FILTER NOT EXISTS { + ?context a ?versionOfVocabulary . + } } } """) .setParameter("attribute", attribute.getUri()) + .setParameter("versionOfVocabulary", URI.create(Vocabulary.s_c_version_of_vocabulary)) .executeUpdate(); } catch (RuntimeException e) { throw new PersistenceException("Failed to remove all custom attribute usages", e); diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java index d5bc6ed14..a73ed1a22 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java @@ -634,7 +634,7 @@ void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOrigina transactional(() -> sut.removeAllCustomAttributeUsages(attribute)); - transactional(() -> { + readOnlyTransactional(() -> { final Page usage = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); assertEquals(0, usage.getTotalElements()); @@ -647,4 +647,61 @@ void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOrigina assertTrue(relatedStatementExists); }); } + + Statement setupAttributeUsageInSnapshot(IRI context, CustomAttribute attribute) { + final Statement attributeUsageStatement = statement( + Values.iri(Generator.generateUriString()), + Values.iri(attribute.getUri().toString()), + Values.literal("usageValue"), + context + ); + + transactional(() -> em.persist(attribute)); + withStatements( + statement( + context, + RDF.TYPE, + Values.iri(Vocabulary.s_c_version_of_vocabulary), + context + ), + attributeUsageStatement + ); + return attributeUsageStatement; + } + + @Test + void removeAllCustomAttributeUsagesDoesNotRemoveUsagesFromSnapshots() { + final IRI context = Values.iri(Generator.generateUriString()); + final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute", "en"), null); + + setupAttributeUsageInSnapshot(context, attribute); + + transactional(() -> sut.removeAllCustomAttributeUsages(attribute)); + + readOnlyTransactional(() -> { + final boolean usageExists = em.createNativeQuery(""" + ASK { ?subject ?attribute ?value .} + """, Boolean.class) + .setParameter("attribute", attribute.getUri()) + .getSingleResult(); + + assertTrue(usageExists, "Remove attribute usage must not affect snapshots"); + }); + } + + @Test + void findCustomAttributeUsageDoesNotFindUsageInSnapshots() { + final IRI context = Values.iri(Generator.generateUriString()); + final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute", "en"), null); + + setupAttributeUsageInSnapshot(context, attribute); + + readOnlyTransactional(() -> { + Page usages = sut.findCustomAttributeUsage(attribute.getUri(), PageRequest.of(0, 10)); + assertEquals(0, usages.getTotalElements()); + assertTrue(usages.isEmpty()); + }); + } } From 89b817977520a0db6f1b32c2b59a208c8ce303e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 10:11:03 +0200 Subject: [PATCH 14/19] [Ref] Merge custom attribute usage query into a single final where query clause --- .../kbss/termit/persistence/dao/DataDao.java | 78 +++++++++---------- 1 file changed, 36 insertions(+), 42 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java index 25c900d0a..6a065c882 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/DataDao.java @@ -35,6 +35,7 @@ import cz.cvut.kbss.termit.model.CustomAttribute; import cz.cvut.kbss.termit.model.CustomAttribute_; import cz.cvut.kbss.termit.model.RdfsResource; +import cz.cvut.kbss.termit.model.Vocabulary_; import cz.cvut.kbss.termit.persistence.dao.spec.Specification; import cz.cvut.kbss.termit.persistence.dao.util.Quad; import cz.cvut.kbss.termit.service.export.ExportFormat; @@ -85,6 +86,21 @@ public class DataDao { private static final URI RDFS_LABEL = URI.create(RDFS.LABEL); + /** + * SPARQL where clause matching custom attribute usage in vocabulary graphs, while excluding snapshots + */ + private static final String CUSTOM_ATTRIBUTE_USAGE_WHERE_CLAUSE = """ + WHERE { + GRAPH ?context { + ?subject ?attribute ?object . + ?context a ?vocabulary . + FILTER NOT EXISTS { + ?context a ?versionOfVocabulary . + } + } + } + """; + private final EntityManager em; private final Persistence config; @@ -330,11 +346,10 @@ public void insertRawData(Collection data) { } } - private int countCustomAttributeUsage(RepositoryConnection con, String whereQuery, IRI predicate) { - final TupleQuery countQuery = con.prepareTupleQuery("SELECT (COUNT(*) AS ?count) " + whereQuery); + private int countCustomAttributeUsage(RepositoryConnection con, IRI predicate) { + final TupleQuery countQuery = con.prepareTupleQuery("SELECT (COUNT(*) AS ?count) " + CUSTOM_ATTRIBUTE_USAGE_WHERE_CLAUSE); - countQuery.setBinding("predicate", predicate); - countQuery.setBinding("versionOfVocabulary", Values.iri(Vocabulary.s_c_version_of_vocabulary)); + bindCustomAttributeUsageQueryParameters(countQuery, predicate); countQuery.setIncludeInferred(false); try (TupleQueryResult result = countQuery.evaluate()) { @@ -343,15 +358,13 @@ private int countCustomAttributeUsage(RepositoryConnection con, String whereQuer } } - private List findCustomAttributeUsage(RepositoryConnection con, String whereQuery, IRI predicate, long offset, int resultLimit) { - final TupleQuery pageQuery = con.prepareTupleQuery("SELECT ?subject ?predicate ?object ?context "+ - whereQuery + + private List findCustomAttributeUsage(RepositoryConnection con, IRI predicate, long offset, int resultLimit) { + final TupleQuery pageQuery = con.prepareTupleQuery("SELECT ?subject ?attribute ?object ?context "+ + CUSTOM_ATTRIBUTE_USAGE_WHERE_CLAUSE + "LIMIT " + resultLimit + " OFFSET " + offset); - pageQuery.setBinding("predicate", predicate); - pageQuery.setBinding("versionOfVocabulary", Values.iri(Vocabulary.s_c_version_of_vocabulary)); - + bindCustomAttributeUsageQueryParameters(pageQuery, predicate); pageQuery.setIncludeInferred(false); final List statements = new ArrayList<>(resultLimit); @@ -361,7 +374,7 @@ private List findCustomAttributeUsage(RepositoryConnection con, Strin final BindingSet bindings = result.next(); final Resource subject = (Resource) bindings.getValue("subject"); - final IRI statementPredicate = (IRI) bindings.getValue("predicate"); + final IRI statementPredicate = (IRI) bindings.getValue("attribute"); final Value object = bindings.getValue("object"); final Resource context = (Resource) bindings.getValue("context"); @@ -391,26 +404,15 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl final org.eclipse.rdf4j.repository.Repository repo = em.unwrap(org.eclipse.rdf4j.repository.Repository.class); final IRI predicate = Values.iri(identifier.toString()); - final String whereQuery = """ - WHERE { - GRAPH ?context { - ?subject ?predicate ?object . - FILTER NOT EXISTS { - ?context a ?versionOfVocabulary . - } - } - } - """; - try (RepositoryConnection con = repo.getConnection()) { - final int totalCount = countCustomAttributeUsage(con, whereQuery, predicate); + final int totalCount = countCustomAttributeUsage(con, predicate); if (totalCount == 0 || pageable.getOffset() >= totalCount) { return new PageImpl<>(List.of(), pageable, totalCount); } int maxResults = Math.min(totalCount, pageable.getPageSize()); - final List statements = findCustomAttributeUsage(con, whereQuery, predicate, pageable.getOffset(), maxResults); + final List statements = findCustomAttributeUsage(con, predicate, pageable.getOffset(), maxResults); return new PageImpl<>(statements, pageable, totalCount); } catch (RuntimeException e) { @@ -428,17 +430,9 @@ public List findCustomAttributeUsageContexts(CustomAttribute customAttribut Objects.requireNonNull(customAttribute); Objects.requireNonNull(customAttribute.getUri()); try { - return em.createNativeQuery(""" - SELECT DISTINCT ?context WHERE { - GRAPH ?context { - ?subject ?attribute ?object . - FILTER NOT EXISTS { - ?context a ?versionOfVocabulary . - } - } - } - """, URI.class) + return em.createNativeQuery("SELECT DISTINCT ?context " + CUSTOM_ATTRIBUTE_USAGE_WHERE_CLAUSE, URI.class) .setParameter("attribute", customAttribute.getUri()) + .setParameter("vocabulary", Vocabulary_.entityClassIRI) .setParameter("versionOfVocabulary", URI.create(Vocabulary.s_c_version_of_vocabulary)) .getResultList(); } catch (RuntimeException e) { @@ -460,16 +454,10 @@ public void removeAllCustomAttributeUsages(CustomAttribute attribute) { GRAPH ?context { ?subject ?attribute ?object . } - } WHERE { - GRAPH ?context { - ?subject ?attribute ?object . - FILTER NOT EXISTS { - ?context a ?versionOfVocabulary . - } - } } - """) + """ + CUSTOM_ATTRIBUTE_USAGE_WHERE_CLAUSE) .setParameter("attribute", attribute.getUri()) + .setParameter("vocabulary", Vocabulary_.entityClassIRI) .setParameter("versionOfVocabulary", URI.create(Vocabulary.s_c_version_of_vocabulary)) .executeUpdate(); } catch (RuntimeException e) { @@ -477,6 +465,12 @@ public void removeAllCustomAttributeUsages(CustomAttribute attribute) { } } + private void bindCustomAttributeUsageQueryParameters(TupleQuery query, IRI predicate) { + query.setBinding("attribute", predicate); + query.setBinding("vocabulary", Values.iri(Vocabulary_.entityClassIRI.toString())); + query.setBinding("versionOfVocabulary", Values.iri(Vocabulary.s_c_version_of_vocabulary)); + } + public void removeCustomAttribute(CustomAttribute attribute) { Objects.requireNonNull(attribute); try { From ef81f1676d2a12489c752bf87c23ddea1ed50d5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 10:17:32 +0200 Subject: [PATCH 15/19] [Test] Fix failing tests due to missing context is vocabulary axiom --- .../termit/persistence/dao/DataDaoTest.java | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java index a73ed1a22..863593631 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java @@ -29,6 +29,7 @@ import cz.cvut.kbss.termit.model.RdfsResource; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.User; +import cz.cvut.kbss.termit.model.Vocabulary_; import cz.cvut.kbss.termit.persistence.dao.spec.CustomAttributeSpecifications; import cz.cvut.kbss.termit.persistence.dao.util.Quad; import cz.cvut.kbss.termit.service.export.ExportFormat; @@ -444,6 +445,11 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithSimpleSubject() statement(termIri, Values.iri(attribute.getUri().toString()), value, + context), + // context is a vocabulary + statement(context, + RDF.TYPE, + Values.iri(Vocabulary_.entityClassIRI.toString()), context) ); @@ -486,6 +492,11 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithTripleSubject() statement(subjectTriple, Values.iri(attribute.getUri().toString()), value, + context), + // context is a vocabulary + statement(context, + RDF.TYPE, + Values.iri(Vocabulary_.entityClassIRI.toString()), context) ); @@ -543,6 +554,12 @@ void findCustomAttributeUsageReturnsTotalElementsCountMatchingNumberOfUsagesOfRe statement(termTwo, Values.iri(attribute.getUri().toString()), Values.literal("B value two"), + context), + + // context is a vocabulary + statement(context, + RDF.TYPE, + Values.iri(Vocabulary_.entityClassIRI.toString()), context) ); @@ -648,7 +665,7 @@ void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOrigina }); } - Statement setupAttributeUsageInSnapshot(IRI context, CustomAttribute attribute) { + void setupAttributeUsageInSnapshot(IRI context, CustomAttribute attribute) { final Statement attributeUsageStatement = statement( Values.iri(Generator.generateUriString()), Values.iri(attribute.getUri().toString()), @@ -666,7 +683,6 @@ Statement setupAttributeUsageInSnapshot(IRI context, CustomAttribute attribute) ), attributeUsageStatement ); - return attributeUsageStatement; } @Test From 82f03bfa5566f1a860c02613d17351dc6b02c3e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 10:22:18 +0200 Subject: [PATCH 16/19] [Test] Add custom attribute creation helper method --- .../termit/persistence/dao/DataDaoTest.java | 43 ++++++++----------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java index 863593631..e29a6446c 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/DataDaoTest.java @@ -365,12 +365,10 @@ void insertDataInsertsSpecifiedQuadsIntoRepository() { @Test void findAllCustomAttributesReturnsCustomAttributes() { - final CustomAttribute pOne = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute one", "en"), null); + final CustomAttribute pOne = createCustomAttribute(); pOne.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); pOne.setRange(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); - final CustomAttribute pTwo = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute two", "en"), null); + final CustomAttribute pTwo = createCustomAttribute(); pTwo.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); pTwo.setRange(URI.create(XSD.BOOLEAN)); transactional(() -> { @@ -385,12 +383,10 @@ void findAllCustomAttributesReturnsCustomAttributes() { @Test void findAllCustomAttributesByDomainReturnsCustomAttributesWithSpecifiedDomain() { - final CustomAttribute pOne = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute one", "en"), null); + final CustomAttribute pOne = createCustomAttribute(); pOne.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT_SCHEME)); pOne.setRange(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); - final CustomAttribute pTwo = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute two", "en"), null); + final CustomAttribute pTwo = createCustomAttribute(); pTwo.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); pTwo.setRange(URI.create(XSD.BOOLEAN)); transactional(() -> { @@ -425,8 +421,7 @@ private static Statement statement(Resource subject, IRI predicate, Value object void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithSimpleSubject() { // Subject of the custom attribute annotation is IRI - final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("AttributeName", "en"), null); + final CustomAttribute attribute = createCustomAttribute(); attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); transactional(() -> em.persist(attribute)); @@ -469,8 +464,7 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithTripleSubject() // subject of custom attribute is another triple final URI relation = URI.create(SKOS.RELATED.stringValue()); - final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute", "en"), null); + final CustomAttribute attribute = createCustomAttribute(); attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.RDF.STATEMENT)); attribute.setAnnotatedRelationships(Set.of(relation)); transactional(() -> em.persist(attribute)); @@ -520,12 +514,10 @@ void findCustomAttributeUsageReturnsUsageOfRequestedAttributeWithTripleSubject() @Test void findCustomAttributeUsageReturnsTotalElementsCountMatchingNumberOfUsagesOfRequestedAttribute() { // Unrelated attribute has a single usage, attribute B has two usages - final CustomAttribute unrelated = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute A", "en"), null); + final CustomAttribute unrelated = createCustomAttribute(); unrelated.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); - final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute B", "en"), null); + final CustomAttribute attribute = createCustomAttribute(); attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); transactional(() -> { @@ -572,8 +564,7 @@ void findCustomAttributeUsageReturnsTotalElementsCountMatchingNumberOfUsagesOfRe @Test void removeAllCustomAttributeUsagesRemovesUsagesWithSimpleSubjectAndKeepsOtherStatements() { // Subject of the custom attribute usage is a plain IRI - final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute", "en"), null); + final CustomAttribute attribute = createCustomAttribute(); attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.SKOS.CONCEPT)); attribute.setRange(URI.create(XSD.STRING)); transactional(() -> em.persist(attribute)); @@ -618,8 +609,7 @@ void removeAllCustomAttributeUsagesRemovesUsagesWithSimpleSubjectAndKeepsOtherSt void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOriginalAnnotatedRelationship() { // Subject of the custom attribute usage is another triple final URI relation = URI.create(SKOS.RELATED.stringValue()); - final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute", "en"), null); + final CustomAttribute attribute = createCustomAttribute(); attribute.setDomain(URI.create(cz.cvut.kbss.jopa.vocabulary.RDF.STATEMENT)); attribute.setRange(URI.create(XSD.STRING)); attribute.setAnnotatedRelationships(Set.of(relation)); @@ -665,7 +655,7 @@ void removeAllCustomAttributeUsagesRemovesUsagesWithTripleSubjectAndKeepsOrigina }); } - void setupAttributeUsageInSnapshot(IRI context, CustomAttribute attribute) { + private void setupAttributeUsageInSnapshot(IRI context, CustomAttribute attribute) { final Statement attributeUsageStatement = statement( Values.iri(Generator.generateUriString()), Values.iri(attribute.getUri().toString()), @@ -688,8 +678,7 @@ void setupAttributeUsageInSnapshot(IRI context, CustomAttribute attribute) { @Test void removeAllCustomAttributeUsagesDoesNotRemoveUsagesFromSnapshots() { final IRI context = Values.iri(Generator.generateUriString()); - final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute", "en"), null); + final CustomAttribute attribute = createCustomAttribute(); setupAttributeUsageInSnapshot(context, attribute); @@ -709,8 +698,7 @@ void removeAllCustomAttributeUsagesDoesNotRemoveUsagesFromSnapshots() { @Test void findCustomAttributeUsageDoesNotFindUsageInSnapshots() { final IRI context = Values.iri(Generator.generateUriString()); - final CustomAttribute attribute = new CustomAttribute(Generator.generateUri(), - MultilingualString.create("Attribute", "en"), null); + final CustomAttribute attribute = createCustomAttribute(); setupAttributeUsageInSnapshot(context, attribute); @@ -720,4 +708,9 @@ void findCustomAttributeUsageDoesNotFindUsageInSnapshots() { assertTrue(usages.isEmpty()); }); } + + private static CustomAttribute createCustomAttribute() { + return new CustomAttribute(Generator.generateUri(), + MultilingualString.create("Attribute " + Generator.randomInt(), "en"), null); + } } From 8c85bf16ad1b1a15c1e94f2d55c56e76035cc60b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 09:48:29 +0200 Subject: [PATCH 17/19] [Bug] Update custom attribute endpoint authorization to require ROLE_ADMIN --- src/main/java/cz/cvut/kbss/termit/rest/DataController.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index 29e4192f9..d9ab71b91 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -119,7 +119,7 @@ public ResponseEntity createCustomAttribute(@Parameter(description = "Attr @ApiResponse(responseCode = "404", description = "Attribute not found.") }) @ResponseStatus(HttpStatus.NO_CONTENT) - @PreAuthorize("hasRole('" + SecurityConstants.ROLE_FULL_USER + "')") + @PreAuthorize("hasRole('" + SecurityConstants.ROLE_ADMIN + "')") @PutMapping(value = "/custom-attributes/{localName}", consumes = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) public void updateCustomAttribute(@Parameter( @@ -138,7 +138,7 @@ public void updateCustomAttribute(@Parameter( @ApiResponse(responseCode = "200", description = "The list of triples with the custom attribute as predicate"), @ApiResponse(responseCode = "404", description = "Attribute not found") }) - @PreAuthorize("hasRole('" + SecurityConstants.ROLE_FULL_USER + "')") + @PreAuthorize("hasRole('" + SecurityConstants.ROLE_ADMIN + "')") @GetMapping(value = "/custom-attributes/{localName}/usage", produces = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) public ResponseEntity> getCustomAttributeUsage(@Parameter( description = "Locally (in the context of the namespace) unique part of the attribute identifier.", @@ -172,7 +172,7 @@ public ResponseEntity> getCustomAttributeUsage(@Parameter( @ApiResponse(responseCode = "400", description = "Force parameter is required for removal of attribute with usages"), @ApiResponse(responseCode = "404", description = "Attribute not found") }) - @PreAuthorize("hasRole('" + SecurityConstants.ROLE_FULL_USER + "')") + @PreAuthorize("hasRole('" + SecurityConstants.ROLE_ADMIN + "')") @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping(value = "/custom-attributes/{localName}") public void removeCustomAttribute(@Parameter( From 60fa2b75827156d014c9313e8255a655ce97441d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 09:52:06 +0200 Subject: [PATCH 18/19] [Docs] Remove references to old force parameter that was replaced with removeUsages in remove custom attribute endpoint --- src/main/java/cz/cvut/kbss/termit/rest/DataController.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java index d9ab71b91..5e7a1b32c 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/DataController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/DataController.java @@ -166,10 +166,9 @@ public ResponseEntity> getCustomAttributeUsage(@Parameter( @Operation(security = {@SecurityRequirement(name = "bearer-key")}, description = "Removes the custom attribute, " + - "if it has usages, force parameter is required and the removal will remove all the usages as well.") + "if the removeUsages is not enabled, the usages of the attribute wont be removed.") @ApiResponses({ @ApiResponse(responseCode = "204", description = "Custom attribute was removed"), - @ApiResponse(responseCode = "400", description = "Force parameter is required for removal of attribute with usages"), @ApiResponse(responseCode = "404", description = "Attribute not found") }) @PreAuthorize("hasRole('" + SecurityConstants.ROLE_ADMIN + "')") From 2b5a14b81b1147ab63c7a74ec8d390be5b4d684f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 09:57:38 +0200 Subject: [PATCH 19/19] [Docs] Remove references to old force parameter that was replaced with removeUsages in remove custom attribute data repository method --- .../kbss/termit/service/repository/DataRepositoryService.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index 03374bd2a..4342a6c0c 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -217,11 +217,9 @@ public Page findCustomAttributeUsage(URI identifier, Pageable pageabl /** * Removes custom attribute identified by {@code identifier}. - * If usages exist, {@code force} needs to be enabled in order to remove the attribute and its usages. * * @param identifier the identifier of the {@link CustomAttribute} * @param removeUsages whether to also remove all usages of the {@link CustomAttribute} - * @throws ValidationException if attribute usage exists and {@code force} is {@code false} */ @Transactional public void removeCustomAttribute(URI identifier, boolean removeUsages) {