From 308dcd4ce2a3f19c40397bcf44ace411dff1293e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 13:51:11 +0200 Subject: [PATCH 01/30] [Enhancement kbss-cvut/termit-ui#744] Introduce TermRemovalParams to allow removing terms to which references exists. Add inverse reference checking for term pre-removal. --- .../kbss/termit/persistence/dao/TermDao.java | 101 +++++++++++++++ .../persistence/dao/TermOccurrenceDao.java | 17 +++ .../cvut/kbss/termit/rest/TermController.java | 15 ++- .../business/TermOccurrenceService.java | 8 ++ .../termit/service/business/TermService.java | 16 +++ .../TermOccurrenceRepositoryService.java | 13 ++ .../repository/TermRepositoryService.java | 81 +++++++++--- .../term_removal/SubTermRemovalStrategy.java | 122 ++++++++++++++++++ .../term_removal/TermParamsApplier.java | 18 +++ .../term_removal/TermRemovalParams.java | 33 +++++ .../SubTermRemovalStrategyTest.java | 60 +++++++++ 11 files changed, 462 insertions(+), 22 deletions(-) create mode 100644 src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java create mode 100644 src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java create mode 100644 src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java create mode 100644 src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index d69cace89..a2c88c1e6 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -40,6 +40,7 @@ import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.TermInfoWithParents; import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.Vocabulary_; import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.persistence.context.DescriptorFactory; import cz.cvut.kbss.termit.persistence.context.VocabularyContextMapper; @@ -48,8 +49,15 @@ import cz.cvut.kbss.termit.service.snapshot.SnapshotProvider; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Utils; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.util.Values; +import org.eclipse.rdf4j.query.GraphQuery; +import org.eclipse.rdf4j.query.GraphQueryResult; +import org.eclipse.rdf4j.repository.RepositoryConnection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; @@ -77,6 +85,21 @@ public class TermDao extends BaseAssetDao implements SnapshotProvider> subTermsCache; private final VocabularyContextMapper contextMapper; @@ -1267,4 +1290,82 @@ public Set findWithAllAncestors(Set termUris) { throw new PersistenceException(e); } } + + /** + * Checks whether there is any triple in any vocabulary where the term is an object. + * Excluding vocabulary snapshots. + * + * @param term term to which references should be checked + * @return true if there is any triple where the term is an object + */ + public boolean referencesToTermExist(AbstractTerm term) { + Objects.requireNonNull(term.getUri(), "Term URI cannot be null"); + try { + return em.createNativeQuery("ASK " + REFERENCES_TO_TERM_WHERE_CLAUSE, Boolean.class) + .setParameter("term", term.getUri()) + .setParameter("vocabulary", Vocabulary_.entityClassIRI) + .setParameter("versionOfVocabulary", URI.create(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)) + .getSingleResult(); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to find references for term " + Utils.uriToString(term.getUri()), e); + } + } + + /** + * Finds statements from vocabulary graphs referencing the specified term as an object. + * + * @param term term whose incoming references should be returned + * @param pageable paging specification applied to the constructed RDF4J query + * @return page of statements referencing the specified term + */ + public Page findReferences(AbstractTerm term, Pageable pageable) { + Objects.requireNonNull(term.getUri(), "Term URI cannot be null"); + final String offsetLimitClause = " OFFSET " + pageable.getOffset() + " LIMIT " + pageable.getPageSize(); + + try { + final GraphQuery query; + try (RepositoryConnection con = em.unwrap(org.eclipse.rdf4j.repository.Repository.class).getConnection()) { + query = con.prepareGraphQuery(""" + CONSTRUCT { + ?other ?relation ?term . + } + """ + REFERENCES_TO_TERM_WHERE_CLAUSE + offsetLimitClause); + query.setBinding("term", Values.iri(term.getUri().toString())); + query.setBinding("vocabulary", Values.iri(Vocabulary_.entityClassIRI.toString())); + query.setBinding("versionOfVocabulary", + Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)); + try (GraphQueryResult result = query.evaluate()) { + return new PageImpl<>(result.stream().toList()); + } + } + } catch (RuntimeException e) { + throw new PersistenceException("Failed to find references to term " + Utils.uriToString(term.getUri()), e); + } + } + + /** + * Removes all triples from vocabularies where the given term is references as object. + * + * @param toRemove term to which references should be removed + */ + public void removeReferencesTo(AbstractTerm toRemove) { + Objects.requireNonNull(toRemove.getUri(), "Term URI cannot be null"); + + try { + em.createNativeQuery(""" + DELETE { + GRAPH ?context { + ?other ?relation ?term . + } + } + """ + REFERENCES_TO_TERM_WHERE_CLAUSE) + .setParameter("term", toRemove.getUri()) + .setParameter("vocabulary", Vocabulary_.entityClassIRI) + .setParameter("versionOfVocabulary", URI.create(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)) + .executeUpdate(); + throw new RuntimeException("force rollback"); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to remove references to term " + Utils.uriToString(toRemove.getUri()), e); + } + } } diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java index 0e7a1bf04..bd7713c31 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java @@ -313,4 +313,21 @@ public void removeAllOrphans() { removeAll(a, URI.create(Vocabulary.s_c_term_occurrence)); }); } + + /** + * Checks whether there are any occurrences targeting the given asset. + * + * @param target asset which occurrences should be looked up + * @return true if any occurrence targeting the asset exist + */ + public boolean existsTargeting(Asset target) { + Objects.requireNonNull(target, "Target cannot be null"); + Objects.requireNonNull(target.getUri(), "Target URI cannot be null"); + return em.createNativeQuery("ASK {" + + "?x a ?type ;" + + "?hasTerm ?term . }", Boolean.class) + .setParameter("type", typeUri) + .setParameter("hasTerm", URI.create(Vocabulary.s_p_is_assignment_of_term)) + .setParameter("term", target.getUri()).getSingleResult(); + } } diff --git a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java index 2666ec524..403a0f40f 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -38,6 +38,8 @@ import cz.cvut.kbss.termit.service.business.util.TermSelectionParams; import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportType; +import cz.cvut.kbss.termit.service.repository.term_removal.SubTermRemovalStrategy; +import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; @@ -510,9 +512,18 @@ public void removeTerm( @Parameter(description = ApiDoc.ID_TERM_LOCAL_NAME_DESCRIPTION, example = ApiDoc.ID_TERM_LOCAL_NAME_EXAMPLE) @PathVariable String termLocalName, @Parameter(description = ApiDoc.ID_NAMESPACE_DESCRIPTION, example = ApiDoc.ID_NAMESPACE_EXAMPLE) - @RequestParam(name = QueryParams.NAMESPACE, required = false) Optional namespace) { + @RequestParam(name = QueryParams.NAMESPACE, required = false) Optional namespace, + @Parameter(description = "Strategy to use for sub-terms handling.") + @RequestParam(name = "subTermsStrategy") SubTermRemovalStrategy subTermsStrategy, + @Parameter(description = "Whether occurrences should be removed. When false, the removal will fail if any occurrence exists.") + @RequestParam(name = "removeOccurrences") boolean removeOccurrences, + @Parameter(description = "Whether relationships referencing the term should be removed. When false, the removal will fail if any reference to the term exists.") + @RequestParam(name = "removeRelationships") boolean removeRelationships) { final URI termUri = getTermUri(localName, termLocalName, namespace); - termService.remove(termService.findRequired(termUri)); + final Term toRemove = termService.findRequired(termUri); + termService.remove( + new TermRemovalParams(toRemove, subTermsStrategy, removeOccurrences, removeRelationships) + ); LOG.debug("Term {} removed.", termUri); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java b/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java index ea4107c49..5c3994302 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java @@ -94,4 +94,12 @@ public interface TermOccurrenceService { * @param term Term whose occurrences to remove */ void removeAllOf(AbstractTerm term); + + /** + * Checks whether there are any occurrences targeting the given asset. + * + * @param target asset which occurrences should be looked up + * @return true if any occurrence targeting the asset exist + */ + boolean existsTargeting(Asset target); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java index 353861a96..bf93d28d6 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java @@ -49,6 +49,7 @@ import cz.cvut.kbss.termit.service.language.LanguageService; import cz.cvut.kbss.termit.service.repository.ChangeRecordService; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; +import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; import cz.cvut.kbss.termit.util.TypeAwareResource; import cz.cvut.kbss.termit.util.Utils; @@ -631,6 +632,21 @@ public void remove(@Nonnull Term term) { repositoryService.remove(term); } + /** + * Removes the specified term according to the removal parameters. + * + * @param termRemovalParams parameters describing how the term should be removed + */ + @Transactional + @PreAuthorize("@termAuthorizationService.canRemove(#termRemovalParams.termToRemove())") + public void remove(TermRemovalParams termRemovalParams) { + Objects.requireNonNull(termRemovalParams); + Objects.requireNonNull(termRemovalParams.termToRemove()); + Objects.requireNonNull(termRemovalParams.termToRemove().getVocabulary()); + final Vocabulary vocabulary = findVocabularyRequired(termRemovalParams.termToRemove().getVocabulary()); + repositoryService.remove(termRemovalParams, vocabulary); + } + /** * Executes text analysis on the specified term's definition. *

diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java index 307b24ca4..2054b29bc 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java @@ -175,4 +175,17 @@ public void removeAllOf(AbstractTerm term) { LOG.debug("Removing all occurrences of term {}.", term); termOccurrenceDao.removeAllOf(term); } + + /** + * Checks whether there are any occurrences targeting the given asset. + * + * @param target asset which occurrences should be looked up + * @return true if any occurrence targeting the asset exist + */ + @PreAuthorize("@termAuthorizationService.canRead(#target)") + @Transactional(readOnly = true) + @Override + public boolean existsTargeting(Asset target) { + return termOccurrenceDao.existsTargeting(target); + } } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index b26ce1d03..c0c9f9c22 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -18,7 +18,6 @@ package cz.cvut.kbss.termit.service.repository; import cz.cvut.kbss.jopa.model.MultilingualString; -import cz.cvut.kbss.jopa.vocabulary.SKOS; import cz.cvut.kbss.termit.dto.Snapshot; import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.dto.assignment.TermOccurrences; @@ -38,6 +37,7 @@ import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.TermOccurrenceService; +import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; import cz.cvut.kbss.termit.service.snapshot.SnapshotProvider; import cz.cvut.kbss.termit.service.term.AssertedInferredValueDifferentiator; import cz.cvut.kbss.termit.service.term.OrphanedInverseTermRelationshipRemover; @@ -45,6 +45,8 @@ import cz.cvut.kbss.termit.util.Utils; import jakarta.annotation.Nonnull; import jakarta.validation.Validator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -65,6 +67,7 @@ @Service public class TermRepositoryService extends BaseAssetRepositoryService implements SnapshotProvider { + private static final Logger LOG = LoggerFactory.getLogger(TermRepositoryService.class); private final IdentifierResolver idResolver; private final TermDao termDao; @@ -618,6 +621,57 @@ public Optional findTermVocabulary(URI termId) { return termDao.findTermVocabulary(termId); } + /** + * Removes a term according to the specified removal parameters. + * + * @param removalParams Params describing how the term should be removed + */ + @Transactional + public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { + Objects.requireNonNull(removalParams); + Objects.requireNonNull(vocabulary); + + final Term toRemove = removalParams.termToRemove(); + // ensure we are working with managed instance + removalParams = removalParams.withTerm(toRemove); + + LOG.debug("Removing term <{}>", toRemove.getUri()); + + LOG.debug("Applying sub-terms removal strategy for term <{}>: {}", toRemove.getUri(), removalParams.subTermsStrategy()); + removalParams.subTermsStrategy().apply(removalParams, vocabulary, this); + toRemove.getSubTerms().clear(); + + if (termOccurrenceService.existsTargeting(toRemove) && !removalParams.removeOccurrences()) { + throw new AssetRemovalException("Failed to remove term because of existing term occurrences"); + } + LOG.debug("Removing occurrences of term <{}>", toRemove.getUri()); + termOccurrenceService.removeAllOf(toRemove); + + if (removalParams.removeRelationships()) { + LOG.debug("Removing references to term <{}>", toRemove.getUri()); + termDao.removeReferencesTo(toRemove); + } + + preRemove(toRemove); + remove(toRemove); + postRemove(toRemove); + LOG.debug("Removed term <{}>", toRemove.getUri()); + } + + /** + * Removes the specified term from the repository. + * The term must not have any children, no occurrence must exist + * and there must be no references to the term. + * + * @param instance The instance to remove + * @see #remove(TermRemovalParams, Vocabulary) + * @see #forceRemove(Term) + */ + @Override + public void remove(Term instance) { + super.remove(instance); + } + /** * Checks that a term can be removed. *

@@ -643,16 +697,9 @@ protected void preRemove(@Nonnull Term instance) { if ((subTerms != null) && !subTerms.isEmpty()) { throw hasSubTermsException(subTerms); } - if (instance.getProperties() != null) { - Set props = instance.getProperties().keySet(); - List properties = props.stream().filter(s -> (s.startsWith(SKOS.NAMESPACE)) && !( - s.equalsIgnoreCase(SKOS.CHANGE_NOTE) - || s.equalsIgnoreCase(SKOS.EDITORIAL_NOTE) - || s.equalsIgnoreCase(SKOS.HISTORY_NOTE) - || s.equalsIgnoreCase(SKOS.NOTE))).collect(toList()); - if (!properties.isEmpty()) { - throw hasSkosRelationships(properties); - } + if (termDao.referencesToTermExist(instance)) { + throw new AssetRemovalException( + "Cannot delete the term. References to this term exist!", "error.term.remove.relationshipsExist"); } } @@ -664,7 +711,7 @@ private static TermItException annotationsExistException(List a "error.term.remove.annotationsExist").addParameter("resources", resources); } - private static TermItException hasSubTermsException(Set subTerms) { + public static TermItException hasSubTermsException(Set subTerms) { final String children = subTerms.stream().map(t -> t.getUri().toString()).collect(joining(",")); return new AssetRemovalException( "Cannot delete the term. It is a parent of other terms: " + children, @@ -672,14 +719,6 @@ private static TermItException hasSubTermsException(Set subTerms) { .addParameter("subTerms", children); } - private static TermItException hasSkosRelationships(List properties) { - final String propertiesStr = String.join(", ", properties); - return new AssetRemovalException( - "Cannot delete the term. It is linked to another term through properties " - + String.join(",", properties), "error.term.remove.skosRelationshipsExist") - .addParameter("properties", propertiesStr); - } - @Override protected void postRemove(@Nonnull Term instance) { super.postRemove(instance); @@ -697,6 +736,8 @@ protected void postRemove(@Nonnull Term instance) { * specified instance. * * @param instance Term to remove + * @see #remove(TermRemovalParams, Vocabulary) + * @see #remove(Term) */ @Transactional public void forceRemove(@Nonnull Term instance) { diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java new file mode 100644 index 000000000..2d7fb494a --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -0,0 +1,122 @@ +package cz.cvut.kbss.termit.service.repository.term_removal; + +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.util.HasIdentifier; +import cz.cvut.kbss.termit.service.repository.TermRepositoryService; + +import java.util.Collection; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Describes an operation how should be sub-terms handled during term removal + */ +public enum SubTermRemovalStrategy implements TermParamsApplier { + /** + * All sub-terms will be removed using the same {@link TermRemovalParams} + */ + CASCADE(CascadeRemoveApplier.INSTANCE), + + /** + * Sub-terms will be moved one level up, becoming children of the parent(s) of the term being removed. + * When the term being removed has no parents in the current vocabulary, + * the sub-terms will become root terms of the vocabulary. + */ + RECONNECT(ReconnectApplier.INSTANCE), + + /** + * If the term has sub-terms, the removal will fail + */ + FAIL(FailApplier.INSTANCE); + + private final TermParamsApplier applier; + + SubTermRemovalStrategy(TermParamsApplier applier) { + this.applier = Objects.requireNonNull(applier); + } + + @Override + public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, TermRepositoryService repositoryService) { + applier.apply(removalParams, vocabulary, repositoryService); + } + + /** + * Removes every child of the given term + */ + private static class CascadeRemoveApplier implements TermParamsApplier { + static final CascadeRemoveApplier INSTANCE = new CascadeRemoveApplier(); + + @Override + public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, + TermRepositoryService repositoryService) { + final Term term = removalParams.termToRemove(); + term.getSubTerms().forEach(subTermInfo -> { + final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); + repositoryService.remove(removalParams.withTerm(subTerm), vocabulary); + }); + } + } + + /** + * Moves every subterm one level up. + * Every child becomes child of its grandparent. + * If the term being removed has no parents in the current vocabulary, children become root terms. + */ + private static class ReconnectApplier implements TermParamsApplier { + static final ReconnectApplier INSTANCE = new ReconnectApplier(); + + @Override + public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, + TermRepositoryService repositoryService) { + final Term term = removalParams.termToRemove(); + if (!term.hasParentInSameVocabulary()) { + // term has no parents in the same vocabulary + makeRoots(term, vocabulary); + } + if (!term.getParentTerms().isEmpty() || !term.getExternalParentTerms().isEmpty()) { + // term has some parents to which children should be reconnected + reconnectToParents(term, repositoryService); + } + } + + private void makeRoots(Term term, Vocabulary vocabulary) { + term.getSubTerms().forEach(subTermInfo -> { + vocabulary.getRootTerms().add(subTermInfo.getUri()); + }); + } + + private void reconnectToParents(Term term, TermRepositoryService repositoryService) { + // local and external parents + final Set parents = Stream.of(term.getParentTerms(), term.getExternalParentTerms()) + .flatMap(Collection::stream) + .map(HasIdentifier::getUri) + .distinct() // in case of consolidated parents + .map(repositoryService::findRequired) + .collect(Collectors.toSet()); + // add every sub-term + term.getSubTerms().forEach(subTermInfo -> { + // as a sub-term of each parent + parents.forEach(parent -> parent.getSubTerms().add(subTermInfo)); + }); + } + } + + /** + * Throws an exception when the term to be removed has sub-terms. + */ + private static class FailApplier implements TermParamsApplier { + static final FailApplier INSTANCE = new FailApplier(); + @Override + public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, + TermRepositoryService repositoryService) { + final Term term = removalParams.termToRemove(); + if (!term.getSubTerms().isEmpty()) { + throw TermRepositoryService.hasSubTermsException(term.getSubTerms()); + } + } + } + +} diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java new file mode 100644 index 000000000..7ec6bcbba --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java @@ -0,0 +1,18 @@ +package cz.cvut.kbss.termit.service.repository.term_removal; + +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.service.repository.TermRepositoryService; + +/** + * Applier performing the given operation described by the parameters. + */ +public interface TermParamsApplier { + /** + * Applies the operation described by the parameters. + * + * @param removalParams Params describing how the term should be removed. + * @param vocabulary Vocabulary of the {@code term} + * @param repositoryService Service for interacting with the term repository + */ + void apply(TermRemovalParams removalParams, Vocabulary vocabulary, TermRepositoryService repositoryService); +} diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java new file mode 100644 index 000000000..bf1da1fe4 --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java @@ -0,0 +1,33 @@ +package cz.cvut.kbss.termit.service.repository.term_removal; + +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Vocabulary; + +/** + * Describes how should be a term removed + * @param termToRemove The Term that will be removed + * @param subTermsStrategy Strategy to use for sub-terms handling + * @param removeOccurrences Whether {@link cz.cvut.kbss.termit.model.assignment.TermOccurrence term occurrences} should be removed. + * When {@code false} and a term occurrence exists, the removal will fail + * and the term will not be removed. + * @param removeRelationships Whether relationships referencing the term should be removed. + * When {@code false} and the term is referenced in some relationship, the removal will fail + * and the term will not be removed. + * @see cz.cvut.kbss.termit.service.repository.TermRepositoryService#remove(TermRemovalParams, Vocabulary) + */ +public record TermRemovalParams( + Term termToRemove, + SubTermRemovalStrategy subTermsStrategy, + boolean removeOccurrences, + boolean removeRelationships +) { + /** + * Creates a copy of this params replacing the term to remove. + * + * @param term the new term to remove + * @return copy of the params with replaced term instance + */ + public TermRemovalParams withTerm(Term term) { + return new TermRemovalParams(term, subTermsStrategy, removeOccurrences, removeRelationships); + } +} diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java new file mode 100644 index 000000000..38bc8552e --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -0,0 +1,60 @@ +package cz.cvut.kbss.termit.service.repository.term_removal; + +import cz.cvut.kbss.termit.dto.TermInfo; +import cz.cvut.kbss.termit.environment.Generator; +import cz.cvut.kbss.termit.exception.TermItException; +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.service.repository.TermRepositoryService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@ExtendWith(MockitoExtension.class) +class SubTermRemovalStrategyTest { + + @Mock + private TermRepositoryService repositoryService; + + private Vocabulary vocabulary; + + private Term term; + + @BeforeEach + void setUp() { + vocabulary = Generator.generateVocabularyWithId(); + term = Generator.generateTermWithId(vocabulary.getUri()); + vocabulary.addRootTerm(term); + term.setSubTerms(new HashSet<>()); + term.setParentTerms(new HashSet<>()); + } + + private TermRemovalParams withStrategy(SubTermRemovalStrategy strategy) { + return new TermRemovalParams(term, strategy, false, false); + } + + @Test + void failThrowsWhenTermHasChildren() { + final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.FAIL); + final TermInfo child = Generator.generateTermInfoWithId(); + term.setSubTerms(Set.of(child)); + + final TermItException exception = assertThrows(TermItException.class, () -> params.subTermsStrategy().apply(params, vocabulary, repositoryService)); + assertEquals("error.term.remove.hasSubTerms", exception.getMessageId()); + } + + @Test + void failDoesNotThrowWhenTermHasNoChildren() { + final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.FAIL); + assertDoesNotThrow(() -> params.subTermsStrategy().apply(params, vocabulary, repositoryService)); + } +} From afcacb4a41090d783ae8bc408849beea34dfa11b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 14:18:32 +0200 Subject: [PATCH 02/30] [Test] Implement tests for SubTermRemovalStrategy --- .../kbss/termit/rest/TermControllerTest.java | 2 +- .../SubTermRemovalStrategyTest.java | 75 +++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java index a5daac06c..a39208eeb 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java @@ -855,7 +855,7 @@ void removeThrowsNotFoundWhenTermToRemoveDoesNotExist() throws Exception { mockMvc.perform( delete(PATH + VOCABULARY_NAME + "/terms/" + TERM_NAME)) .andExpect(status().isNotFound()); - verify(termServiceMock, never()).remove(any()); + verify(termServiceMock, never()).remove(any(Term.class)); } @Test diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java index 38bc8552e..d6a8695cd 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -18,6 +18,9 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class SubTermRemovalStrategyTest { @@ -36,6 +39,7 @@ void setUp() { vocabulary.addRootTerm(term); term.setSubTerms(new HashSet<>()); term.setParentTerms(new HashSet<>()); + term.setExternalParentTerms(new HashSet<>()); } private TermRemovalParams withStrategy(SubTermRemovalStrategy strategy) { @@ -57,4 +61,75 @@ void failDoesNotThrowWhenTermHasNoChildren() { final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.FAIL); assertDoesNotThrow(() -> params.subTermsStrategy().apply(params, vocabulary, repositoryService)); } + + @Test + void cascadeRemovesAllChildrenUsingSameRemovalParameters() { + final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.CASCADE); + final TermInfo firstChildInfo = Generator.generateTermInfoWithId(); + final TermInfo secondChildInfo = Generator.generateTermInfoWithId(); + + final Term firstChild = Generator.generateTermWithId(vocabulary.getUri()); + firstChild.setUri(firstChildInfo.getUri()); + + final Term secondChild = Generator.generateTermWithId(vocabulary.getUri()); + secondChild.setUri(secondChildInfo.getUri()); + + term.setSubTerms(Set.of(firstChildInfo, secondChildInfo)); + + when(repositoryService.findRequired(firstChildInfo.getUri())).thenReturn(firstChild); + when(repositoryService.findRequired(secondChildInfo.getUri())).thenReturn(secondChild); + + params.subTermsStrategy().apply(params, vocabulary, repositoryService); + + verify(repositoryService).findRequired(firstChildInfo.getUri()); + verify(repositoryService).findRequired(secondChildInfo.getUri()); + verify(repositoryService).remove(params.withTerm(firstChild), vocabulary); + verify(repositoryService).remove(params.withTerm(secondChild), vocabulary); + verifyNoMoreInteractions(repositoryService); + } + + @Test + void reconnectMakesChildrenRootTermsWhenRemovedTermHasNoParentsInSameVocabulary() { + final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.RECONNECT); + final TermInfo firstChild = Generator.generateTermInfoWithId(); + final TermInfo secondChild = Generator.generateTermInfoWithId(); + + term.setSubTerms(Set.of(firstChild, secondChild)); + + params.subTermsStrategy().apply(params, vocabulary, repositoryService); + + assertEquals(Set.of(term.getUri(), firstChild.getUri(), secondChild.getUri()), vocabulary.getRootTerms()); + verifyNoMoreInteractions(repositoryService); + } + + @Test + void reconnectLinksChildrenToAllParents() { + final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.RECONNECT); + + final TermInfo child = Generator.generateTermInfoWithId(); + final Term parent = Generator.generateTermWithId(vocabulary.getUri()); + final Vocabulary externalVocabulary = Generator.generateVocabularyWithId(); + final Term externalParent = Generator.generateTermWithId(externalVocabulary.getUri()); + + parent.setSubTerms(new HashSet<>()); + externalParent.setSubTerms(new HashSet<>()); + + term.setSubTerms(Set.of(child)); + term.setParentTerms(Set.of(parent.toTermInfo())); + term.setExternalParentTerms(Set.of(externalParent.toTermInfo())); + + when(repositoryService.findRequired(parent.getUri())).thenReturn(parent); + when(repositoryService.findRequired(externalParent.getUri())).thenReturn(externalParent); + + params.subTermsStrategy().apply(params, vocabulary, repositoryService); + + assertEquals(Set.of(child), parent.getSubTerms()); + assertEquals(Set.of(child), externalParent.getSubTerms()); + + assertEquals(Set.of(term.getUri()), vocabulary.getRootTerms(), "Children must not be added as root terms"); + + verify(repositoryService).findRequired(parent.getUri()); + verify(repositoryService).findRequired(externalParent.getUri()); + verifyNoMoreInteractions(repositoryService); + } } From 0a00d0d83b93fd005f75451d229dbb18ad193609 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 14:55:02 +0200 Subject: [PATCH 03/30] [Test] Implement tests for TermRepositoryService and fix missing null checks --- .../kbss/termit/persistence/dao/TermDao.java | 1 - .../repository/TermRepositoryService.java | 13 +- .../term_removal/SubTermRemovalStrategy.java | 14 +- .../repository/TermRepositoryServiceTest.java | 136 +++++++++++++++++- 4 files changed, 151 insertions(+), 13 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index a2c88c1e6..c96abaf2d 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -1363,7 +1363,6 @@ public void removeReferencesTo(AbstractTerm toRemove) { .setParameter("vocabulary", Vocabulary_.entityClassIRI) .setParameter("versionOfVocabulary", URI.create(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)) .executeUpdate(); - throw new RuntimeException("force rollback"); } catch (RuntimeException e) { throw new PersistenceException("Failed to remove references to term " + Utils.uriToString(toRemove.getUri()), e); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index c0c9f9c22..5f8af0ec3 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -629,17 +629,20 @@ public Optional findTermVocabulary(URI termId) { @Transactional public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { Objects.requireNonNull(removalParams); + Objects.requireNonNull(removalParams.termToRemove().getUri()); Objects.requireNonNull(vocabulary); - final Term toRemove = removalParams.termToRemove(); // ensure we are working with managed instance - removalParams = removalParams.withTerm(toRemove); + removalParams = removalParams.withTerm(findRequired(removalParams.termToRemove().getUri())); + final Term toRemove = removalParams.termToRemove(); LOG.debug("Removing term <{}>", toRemove.getUri()); LOG.debug("Applying sub-terms removal strategy for term <{}>: {}", toRemove.getUri(), removalParams.subTermsStrategy()); removalParams.subTermsStrategy().apply(removalParams, vocabulary, this); - toRemove.getSubTerms().clear(); + if (toRemove.getSubTerms() != null) { + toRemove.getSubTerms().clear(); + } if (termOccurrenceService.existsTargeting(toRemove) && !removalParams.removeOccurrences()) { throw new AssetRemovalException("Failed to remove term because of existing term occurrences"); @@ -652,9 +655,7 @@ public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { termDao.removeReferencesTo(toRemove); } - preRemove(toRemove); - remove(toRemove); - postRemove(toRemove); + this.remove(toRemove); // calls pre and post remove LOG.debug("Removed term <{}>", toRemove.getUri()); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java index 2d7fb494a..dfc82f6e0 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -53,10 +53,12 @@ private static class CascadeRemoveApplier implements TermParamsApplier { public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, TermRepositoryService repositoryService) { final Term term = removalParams.termToRemove(); - term.getSubTerms().forEach(subTermInfo -> { - final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); - repositoryService.remove(removalParams.withTerm(subTerm), vocabulary); - }); + if (term.getSubTerms() != null) { + term.getSubTerms().forEach(subTermInfo -> { + final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); + repositoryService.remove(removalParams.withTerm(subTerm), vocabulary); + }); + } } } @@ -76,7 +78,9 @@ public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, // term has no parents in the same vocabulary makeRoots(term, vocabulary); } - if (!term.getParentTerms().isEmpty() || !term.getExternalParentTerms().isEmpty()) { + final boolean hasParents = term.getParentTerms() != null && !term.getParentTerms().isEmpty(); + final boolean hasExternalParents = term.getExternalParentTerms() != null && !term.getExternalParentTerms().isEmpty(); + if (hasParents || hasExternalParents) { // term has some parents to which children should be reconnected reconnectToParents(term, repositoryService); } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index 139da7d97..c6b06878a 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -39,6 +39,8 @@ import cz.cvut.kbss.termit.model.selector.TextPositionSelector; import cz.cvut.kbss.termit.persistence.context.DescriptorFactory; import cz.cvut.kbss.termit.service.BaseServiceTestRunner; +import cz.cvut.kbss.termit.service.repository.term_removal.SubTermRemovalStrategy; +import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; import cz.cvut.kbss.termit.util.Constants; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.repository.Repository; @@ -63,8 +65,8 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.emptyCollectionOf; import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; @@ -464,6 +466,138 @@ void removeRemovesNonReferencedNonOccurringTerm() { assertNull(result); } + @Test + void removeWithParamsCascadesToNestedChildren() { + final Term parent = Generator.generateTermWithId(vocabulary.getUri()); + final Term child = Generator.generateTermWithId(vocabulary.getUri()); + final Term grandChild = Generator.generateTermWithId(vocabulary.getUri()); + + transactional(() -> { + em.persist(parent, descriptorFactory.termDescriptor(vocabulary)); + em.persist(child, descriptorFactory.termDescriptor(vocabulary)); + em.persist(grandChild, descriptorFactory.termDescriptor(vocabulary)); + }); + + transactional(() -> { + parent.setVocabulary(vocabulary.getUri()); + vocabulary.addRootTerm(parent); + em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); + em.merge(parent, descriptorFactory.termDescriptor(vocabulary)); + em.clear(); + + child.setVocabulary(vocabulary.getUri()); + child.addParentTerm(parent); + em.merge(child, descriptorFactory.termDescriptor(vocabulary)); + em.clear(); + + grandChild.setVocabulary(vocabulary.getUri()); + grandChild.addParentTerm(child); + em.merge(grandChild, descriptorFactory.termDescriptor(vocabulary)); + }); + + sut.remove(new TermRemovalParams(parent, SubTermRemovalStrategy.CASCADE, false, true), vocabulary); + + assertNull(em.find(Term.class, parent.getUri())); + assertNull(em.find(Term.class, child.getUri())); + assertNull(em.find(Term.class, grandChild.getUri())); + final Vocabulary result = em.find(Vocabulary.class, vocabulary.getUri(), + descriptorFactory.vocabularyDescriptor(vocabulary)); + assertTrue(result.getRootTerms().isEmpty()); + } + + @Test + void removeWithParamsThrowsWhenTermHasSuggestedOccurrencesAndRemoveOccurrencesIsFalse() { + enableRdfsInference(em); + final Term parent = Generator.generateTermWithId(vocabulary.getUri()); + final Term toRemove = Generator.generateTermWithId(vocabulary.getUri()); + final Term referencing = Generator.generateTermWithId(vocabulary.getUri()); + parent.setVocabulary(vocabulary.getUri()); + toRemove.setVocabulary(vocabulary.getUri()); + vocabulary.addRootTerm(referencing); + transactional(() -> { + vocabulary.addRootTerm(parent); + em.persist(parent, descriptorFactory.termDescriptor(parent)); + em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); + }); + toRemove.addParentTerm(parent); + final TermOccurrence occ = new TermDefinitionalOccurrence(toRemove.getUri(), + new DefinitionalOccurrenceTarget(referencing)); + occ.addType(cz.cvut.kbss.termit.util.Vocabulary.s_c_suggested_term_occurrence); + occ.getTarget().setSelectors(Set.of(new TextPositionSelector(0, 10))); + transactional(() -> { + em.persist(toRemove, descriptorFactory.termDescriptor(toRemove)); + em.persist(referencing, descriptorFactory.termDescriptor(referencing)); + em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); + em.persist(occ); + em.persist(occ.getTarget()); + }); + final Term loaded = sut.findRequired(toRemove.getUri()); + + assertThrows(AssetRemovalException.class, + () -> sut.remove(new TermRemovalParams(loaded, SubTermRemovalStrategy.FAIL, false, false), + vocabulary)); + assertNotNull(em.find(Term.class, toRemove.getUri())); + assertNotNull(em.find(TermDefinitionalOccurrence.class, occ.getUri())); + } + + @Test + void removeWithParamsRemovesSuggestedOccurrencesWhenRemoveOccurrencesIsTrue() { + enableRdfsInference(em); + final Term parent = Generator.generateTermWithId(vocabulary.getUri()); + final Term toRemove = Generator.generateTermWithId(vocabulary.getUri()); + final Term referencing = Generator.generateTermWithId(vocabulary.getUri()); + parent.setVocabulary(vocabulary.getUri()); + toRemove.setVocabulary(vocabulary.getUri()); + vocabulary.addRootTerm(referencing); + transactional(() -> { + vocabulary.addRootTerm(parent); + em.persist(parent, descriptorFactory.termDescriptor(parent)); + em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); + }); + toRemove.addParentTerm(parent); + final TermOccurrence occ = new TermDefinitionalOccurrence(toRemove.getUri(), + new DefinitionalOccurrenceTarget(referencing)); + occ.addType(cz.cvut.kbss.termit.util.Vocabulary.s_c_suggested_term_occurrence); + occ.getTarget().setSelectors(Set.of(new TextPositionSelector(0, 10))); + transactional(() -> { + em.persist(toRemove, descriptorFactory.termDescriptor(toRemove)); + em.persist(referencing, descriptorFactory.termDescriptor(referencing)); + em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); + em.persist(occ); + em.persist(occ.getTarget()); + }); + final Term loaded = sut.findRequired(toRemove.getUri()); + + assertDoesNotThrow( + () -> sut.remove(new TermRemovalParams(loaded, SubTermRemovalStrategy.FAIL, true, false), + vocabulary)); + assertNull(em.find(Term.class, toRemove.getUri())); + assertNull(em.find(TermDefinitionalOccurrence.class, occ.getUri())); + } + + @Test + void removeWithParamsThrowsWhenTermRelationshipsExistAndRemoveRelationshipsIsFalse() { + final Term toRemove = Generator.generateTermWithId(vocabulary.getUri()); + final Term related = Generator.generateTermWithId(vocabulary.getUri()); + toRemove.setVocabulary(vocabulary.getUri()); + related.setVocabulary(vocabulary.getUri()); + vocabulary.addRootTerm(toRemove); + vocabulary.addRootTerm(related); + transactional(() -> { + em.persist(toRemove, descriptorFactory.termDescriptor(vocabulary)); + em.persist(related, descriptorFactory.termDescriptor(vocabulary)); + em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); + generateRelatedInverse(toRemove, related, SKOS.RELATED); + }); + final Term loaded = sut.findRequired(toRemove.getUri()); + + final AssetRemovalException exception = assertThrows(AssetRemovalException.class, + () -> sut.remove(new TermRemovalParams(loaded, SubTermRemovalStrategy.FAIL, false, false), + vocabulary)); + assertEquals("error.term.remove.relationshipsExist", exception.getMessageId()); + assertNotNull(em.find(Term.class, toRemove.getUri())); + } + private void generateRelatedInverse(Term term, Term related, String property) { final Repository repo = em.unwrap(Repository.class); try (final RepositoryConnection conn = repo.getConnection()) { From cb7aaacd0deab1178565a73ff4811e3a9ecd0d8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 15:30:31 +0200 Subject: [PATCH 04/30] [Bug] Fix persistence context cache issue with keeping TermInfo instances managed during Term children recursive removal --- .../kbss/termit/persistence/dao/TermDao.java | 8 +++++ .../repository/TermRepositoryService.java | 19 ++++++++---- .../repository/TermRepositoryServiceTest.java | 29 +++++-------------- 3 files changed, 30 insertions(+), 26 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index c96abaf2d..db7ad4c7f 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -176,6 +176,14 @@ private void postLoad(Term r) { r.setInverseExactMatchTerms(loadInverseExactMatchTerms(r)); } + /** + * Flushes pending term changes and clears the persistence context. + */ + public void flushAndClear() { + em.flush(); + em.clear(); + } + /** * Loads terms whose relatedness to the specified term is inferred due to the symmetry of SKOS related. * diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index 5f8af0ec3..2d8e8e561 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -632,14 +632,23 @@ public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { Objects.requireNonNull(removalParams.termToRemove().getUri()); Objects.requireNonNull(vocabulary); - // ensure we are working with managed instance - removalParams = removalParams.withTerm(findRequired(removalParams.termToRemove().getUri())); - final Term toRemove = removalParams.termToRemove(); + // Refresh the instance from storage, then detach it before traversing term relationships. + // JOPA cannot manage the same individual as both Term and TermInfo, + // which would otherwise prevent loading a child whose parent is the term currently being removed. + final URI termUri = removalParams.termToRemove().getUri(); + removalParams = removalParams.withTerm(findRequired(termUri)); + termDao.detach(removalParams.termToRemove()); - LOG.debug("Removing term <{}>", toRemove.getUri()); + LOG.debug("Removing term <{}>", termUri); - LOG.debug("Applying sub-terms removal strategy for term <{}>: {}", toRemove.getUri(), removalParams.subTermsStrategy()); + LOG.debug("Applying sub-terms removal strategy for term <{}>", termUri); removalParams.subTermsStrategy().apply(removalParams, vocabulary, this); + + // Clear the persistence context to remove cached TermInfo instances + termDao.flushAndClear(); + + removalParams = removalParams.withTerm(findRequired(termUri)); + final Term toRemove = removalParams.termToRemove(); if (toRemove.getSubTerms() != null) { toRemove.getSubTerms().clear(); } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index c6b06878a..d52cf8014 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -472,29 +472,16 @@ void removeWithParamsCascadesToNestedChildren() { final Term child = Generator.generateTermWithId(vocabulary.getUri()); final Term grandChild = Generator.generateTermWithId(vocabulary.getUri()); - transactional(() -> { - em.persist(parent, descriptorFactory.termDescriptor(vocabulary)); - em.persist(child, descriptorFactory.termDescriptor(vocabulary)); - em.persist(grandChild, descriptorFactory.termDescriptor(vocabulary)); - }); - - transactional(() -> { - parent.setVocabulary(vocabulary.getUri()); - vocabulary.addRootTerm(parent); - em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); - em.merge(parent, descriptorFactory.termDescriptor(vocabulary)); - em.clear(); - - child.setVocabulary(vocabulary.getUri()); - child.addParentTerm(parent); - em.merge(child, descriptorFactory.termDescriptor(vocabulary)); - em.clear(); + transactional(() -> sut.addRootTermToVocabulary(parent, vocabulary)); + transactional(() -> sut.addChildTerm(child, parent)); + transactional(() -> sut.addChildTerm(grandChild, child)); - grandChild.setVocabulary(vocabulary.getUri()); - grandChild.addParentTerm(child); - em.merge(grandChild, descriptorFactory.termDescriptor(vocabulary)); - }); + // verify setup + assertNotNull(em.find(Term.class, parent.getUri())); + assertNotNull(em.find(Term.class, child.getUri())); + assertNotNull(em.find(Term.class, grandChild.getUri())); + // remove parent and all children sut.remove(new TermRemovalParams(parent, SubTermRemovalStrategy.CASCADE, false, true), vocabulary); assertNull(em.find(Term.class, parent.getUri())); From f8066047e92d9380b744816882f4d7437a333e9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 2 Sep 2026 15:40:54 +0200 Subject: [PATCH 05/30] [Ref] Fix TermController#removeTerm parameters being required, add default values and fix failing test --- .../java/cz/cvut/kbss/termit/rest/TermController.java | 6 +++--- .../repository/term_removal/TermRemovalParams.java | 10 ++++++++++ .../cz/cvut/kbss/termit/rest/TermControllerTest.java | 3 ++- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java index 403a0f40f..a7b86e5ed 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -514,11 +514,11 @@ public void removeTerm( @Parameter(description = ApiDoc.ID_NAMESPACE_DESCRIPTION, example = ApiDoc.ID_NAMESPACE_EXAMPLE) @RequestParam(name = QueryParams.NAMESPACE, required = false) Optional namespace, @Parameter(description = "Strategy to use for sub-terms handling.") - @RequestParam(name = "subTermsStrategy") SubTermRemovalStrategy subTermsStrategy, + @RequestParam(name = "subTermsStrategy", required = false) SubTermRemovalStrategy subTermsStrategy, @Parameter(description = "Whether occurrences should be removed. When false, the removal will fail if any occurrence exists.") - @RequestParam(name = "removeOccurrences") boolean removeOccurrences, + @RequestParam(name = "removeOccurrences", required = false) boolean removeOccurrences, @Parameter(description = "Whether relationships referencing the term should be removed. When false, the removal will fail if any reference to the term exists.") - @RequestParam(name = "removeRelationships") boolean removeRelationships) { + @RequestParam(name = "removeRelationships", required = false) boolean removeRelationships) { final URI termUri = getTermUri(localName, termLocalName, namespace); final Term toRemove = termService.findRequired(termUri); termService.remove( diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java index bf1da1fe4..40017d732 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java @@ -3,6 +3,8 @@ import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.Vocabulary; +import java.util.Objects; + /** * Describes how should be a term removed * @param termToRemove The Term that will be removed @@ -21,6 +23,14 @@ public record TermRemovalParams( boolean removeOccurrences, boolean removeRelationships ) { + public TermRemovalParams(Term termToRemove, SubTermRemovalStrategy subTermsStrategy, boolean removeOccurrences, + boolean removeRelationships) { + this.termToRemove = Objects.requireNonNull(termToRemove); + this.subTermsStrategy = subTermsStrategy != null ? subTermsStrategy : SubTermRemovalStrategy.FAIL; + this.removeOccurrences = removeOccurrences; + this.removeRelationships = removeRelationships; + } + /** * Creates a copy of this params replacing the term to remove. * diff --git a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java index a39208eeb..2c8675b42 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java @@ -45,6 +45,7 @@ import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportFormat; import cz.cvut.kbss.termit.service.export.ExportType; +import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; @@ -844,7 +845,7 @@ void removeRemovesTermWithSpecifiedIdentifier() throws Exception { when(termServiceMock.findRequired(termUri)).thenReturn(toRemove); mockMvc.perform(delete(PATH + VOCABULARY_NAME + "/terms/" + TERM_NAME)).andExpect(status().isNoContent()); - verify(termServiceMock).remove(toRemove); + verify(termServiceMock).remove(new TermRemovalParams(toRemove, null, false, false)); } @Test From 6e6938ffddb1fac5ffde47fe89ce567401e69424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 07:49:07 +0200 Subject: [PATCH 06/30] [Enhancement kbss-cvut/termit-ui#744] Add endpoint for finding references to terms --- .../kbss/termit/persistence/dao/TermDao.java | 89 ++++++++-- .../cvut/kbss/termit/rest/TermController.java | 28 ++++ .../termit/service/business/TermService.java | 14 ++ .../repository/TermRepositoryService.java | 14 ++ .../termit/persistence/dao/TermDaoTest.java | 158 ++++++++++++++++++ .../kbss/termit/rest/TermControllerTest.java | 40 +++++ 6 files changed, 327 insertions(+), 16 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index db7ad4c7f..9e145767f 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -49,10 +49,15 @@ import cz.cvut.kbss.termit.service.snapshot.SnapshotProvider; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Utils; +import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.util.Values; +import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.GraphQuery; import org.eclipse.rdf4j.query.GraphQueryResult; +import org.eclipse.rdf4j.query.Operation; +import org.eclipse.rdf4j.query.TupleQuery; +import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; @@ -86,16 +91,19 @@ public class TermDao extends BaseAssetDao implements SnapshotProvider +# )) } } """; @@ -1327,30 +1335,79 @@ public boolean referencesToTermExist(AbstractTerm term) { * @return page of statements referencing the specified term */ public Page findReferences(AbstractTerm term, Pageable pageable) { + Objects.requireNonNull(term, "Term cannot be null"); Objects.requireNonNull(term.getUri(), "Term URI cannot be null"); - final String offsetLimitClause = " OFFSET " + pageable.getOffset() + " LIMIT " + pageable.getPageSize(); + Objects.requireNonNull(pageable, "Pageable cannot be null"); try { - final GraphQuery query; try (RepositoryConnection con = em.unwrap(org.eclipse.rdf4j.repository.Repository.class).getConnection()) { - query = con.prepareGraphQuery(""" - CONSTRUCT { - ?other ?relation ?term . - } - """ + REFERENCES_TO_TERM_WHERE_CLAUSE + offsetLimitClause); - query.setBinding("term", Values.iri(term.getUri().toString())); - query.setBinding("vocabulary", Values.iri(Vocabulary_.entityClassIRI.toString())); - query.setBinding("versionOfVocabulary", - Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)); - try (GraphQueryResult result = query.evaluate()) { - return new PageImpl<>(result.stream().toList()); + final long totalCount = countReferences(con, term); + if (totalCount == 0 || pageable.getOffset() >= totalCount) { + return new PageImpl<>(List.of(), pageable, totalCount); } + + final List statements = findReferences(con, term, pageable); + return new PageImpl<>(statements, pageable, totalCount); } } catch (RuntimeException e) { throw new PersistenceException("Failed to find references to term " + Utils.uriToString(term.getUri()), e); } } + /** + * Counts the total amount of references to the specified term + * + * @param con the repository connection + * @param term the term to which references should be counted + * @return the total number of statements referencing the term as object + */ + private long countReferences(RepositoryConnection con, AbstractTerm term) { + final TupleQuery countQuery = con.prepareTupleQuery( + "SELECT (COUNT(*) AS ?count) " + REFERENCES_TO_TERM_WHERE_CLAUSE); + bindReferencesQueryParameters(countQuery, term); + countQuery.setIncludeInferred(false); + try (TupleQueryResult result = countQuery.evaluate()) { + final BindingSet bindings = result.next(); + return ((Literal) bindings.getValue("count")).longValue(); + } + } + + /** + * Finds a page contents of references to the specified term. + * + * @param con the repository connection + * @param term the term to which references should be found + * @param pageable page spec + * @return the list of statements referencing the term as object + */ + private List findReferences(RepositoryConnection con, AbstractTerm term, Pageable pageable) { + final GraphQuery query = con.prepareGraphQuery(""" + CONSTRUCT { + ?other ?relation ?term . + } + """ + REFERENCES_TO_TERM_WHERE_CLAUSE + + " OFFSET " + pageable.getOffset() + + " LIMIT " + pageable.getPageSize()); + bindReferencesQueryParameters(query, term); + query.setIncludeInferred(false); + try (GraphQueryResult result = query.evaluate()) { + return result.stream().toList(); + } + } + + /** + * Sets required query bindings for {@link #REFERENCES_TO_TERM_WHERE_CLAUSE}. + * + * @param query query operation + * @param term the term to which references should be found + */ + private void bindReferencesQueryParameters(Operation query, AbstractTerm term) { + query.setBinding("term", Values.iri(term.getUri().toString())); + query.setBinding("vocabulary", Values.iri(Vocabulary_.entityClassIRI.toString())); + query.setBinding("versionOfVocabulary", + Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)); + } + /** * Removes all triples from vocabularies where the given term is references as object. * diff --git a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java index a7b86e5ed..8463036a2 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -51,9 +51,11 @@ 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.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -527,6 +529,32 @@ public void removeTerm( LOG.debug("Term {} removed.", termUri); } + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, + description = "Gets statements referencing the term with the specified local name from the vocabulary with the specified identifier.") + @ApiResponses({ + @ApiResponse(responseCode = "200", description = "Statements referencing the term."), + @ApiResponse(responseCode = "404", description = "Vocabulary or term not found.") + }) + @GetMapping(value = "/vocabularies/{localName}/terms/{termLocalName}/references", + produces = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) + public ResponseEntity> getReferencesToTerm( + @Parameter(description = ApiDoc.ID_LOCAL_NAME_DESCRIPTION, example = ApiDoc.ID_LOCAL_NAME_EXAMPLE) + @PathVariable String localName, + @Parameter(description = ApiDoc.ID_TERM_LOCAL_NAME_DESCRIPTION, example = ApiDoc.ID_TERM_LOCAL_NAME_EXAMPLE) + @PathVariable String termLocalName, + @Parameter(description = ApiDoc.ID_NAMESPACE_DESCRIPTION, example = ApiDoc.ID_NAMESPACE_EXAMPLE) + @RequestParam(name = QueryParams.NAMESPACE, required = false) Optional namespace, + @Parameter(description = ApiDocConstants.PAGE_SIZE_DESCRIPTION) + @RequestParam(name = QueryParams.PAGE_SIZE, required = false) Integer pageSize, + @Parameter(description = ApiDocConstants.PAGE_NO_DESCRIPTION) + @RequestParam(name = QueryParams.PAGE, required = false) Integer pageNo) { + final Term term = getById(localName, termLocalName, namespace, false, false); + final Page result = termService.findReferences(term, createPageRequest(pageSize, pageNo)); + return ResponseEntity.ok() + .header(Constants.X_TOTAL_COUNT_HEADER, Long.toString(result.getTotalElements())) + .body(result.getContent()); + } + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, description = "Gets sub-terms of the term with the specified local name in the vocabulary with the specified identifier") @ApiResponses({ diff --git a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java index bf93d28d6..d6506d970 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java @@ -55,9 +55,11 @@ import cz.cvut.kbss.termit.util.Utils; import cz.cvut.kbss.termit.util.throttle.Throttle; import jakarta.annotation.Nonnull; +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.security.access.prepost.PostAuthorize; import org.springframework.security.access.prepost.PreAuthorize; @@ -487,6 +489,18 @@ public List findSubTerms(Term parent) { return repositoryService.findSubTerms(parent); } + /** + * Gets referenes to the given term. + * + * @param term the term to which references should be found + * @param pageable Page spec + * @return Page of statements where the given term is object + */ + @PreAuthorize("@termAuthorizationService.canRead(#term)") + public Page findReferences(Term term, Pageable pageable) { + return repositoryService.findReferences(term, pageable); + } + /** * Gets aggregated info about occurrences of the specified Term. * diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index 2d8e8e561..b69efb0ae 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -45,8 +45,10 @@ import cz.cvut.kbss.termit.util.Utils; import jakarta.annotation.Nonnull; import jakarta.validation.Validator; +import org.eclipse.rdf4j.model.Statement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -149,6 +151,18 @@ public Term findRequiredWithPopulatedCustomAttributes(@Nonnull URI id) { return result; } + /** + * Gets referenes to the given term. + * + * @param term the term to which references should be found + * @param pageable Page spec + * @return Page of statements where the given term is object + */ + @Transactional(readOnly = true) + public Page findReferences(@Nonnull Term term, @Nonnull Pageable pageable) { + return termDao.findReferences(term, pageable); + } + @Override protected void preUpdate(@Nonnull Term instance) { if (instance.getPrimaryLanguage() == null) { diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java index bcc5fbadf..cd40bec1f 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java @@ -43,8 +43,12 @@ import cz.cvut.kbss.termit.util.Constants; 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.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.XSD; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; @@ -54,6 +58,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.test.annotation.DirtiesContext; @@ -1519,6 +1524,112 @@ void findSubTermsRetrievesTermSubTerms() { result.stream().map(Asset::getUri).toList()); } + @Test + void findReferencesReturnsStatementsReferencingTermFromVocabularyGraphs() { + final Term term = Generator.generateTermWithId(vocabulary.getUri()); + addTermsAndSave(List.of(term), vocabulary); + + final Statement expectedOne = statement( + Values.iri(Environment.BASE_URI + "/term/source-1"), + Values.iri(SKOS.BROADER), + Values.iri(term.getUri().toString()) + ); + final Statement unexpected = statement( + Values.iri(Environment.BASE_URI + "/term/source-2"), + Values.iri(SKOS.RELATED), + Values.iri(Generator.generateUriString()) + ); + + withStatements(vocabulary.getUri(), expectedOne, unexpected); + + readOnlyTransactional(() -> { + final var result = sut.findReferences(term, PageRequest.of(0, 10)); + + // +1 for vocabulary hasTopConcept + assertEquals(2, result.getContent().size()); + assertEquals(2, result.getTotalElements()); + assertTrue(result.getContent().contains(expectedOne)); + assertFalse(result.getContent().contains(unexpected)); + }); + } + + @Test + void findReferencesRespectsPaging() { + final Term term = Generator.generateTermWithId(vocabulary.getUri()); + addTermsAndSave(List.of(term), vocabulary); + + final List expected = List.of( + statement( + Values.iri(Environment.BASE_URI + "/term/source-1"), + Values.iri(SKOS.BROADER), + Values.iri(term.getUri().toString()) + ), + statement( + Values.iri(Environment.BASE_URI + "/term/source-2"), + Values.iri(SKOS.RELATED), + Values.iri(term.getUri().toString()) + ), + statement( + Values.iri(Environment.BASE_URI + "/term/source-3"), + Values.iri(SKOS.EXACT_MATCH), + Values.iri(term.getUri().toString()) + ) + ); + + withStatements(vocabulary.getUri(), expected.toArray(Statement[]::new)); + + readOnlyTransactional(() -> { + final Page allReferences = sut.findReferences(term, PageRequest.of(0, 10)); + final Page firstPage = sut.findReferences(term, PageRequest.of(0, 2)); + final Page secondPage = sut.findReferences(term, PageRequest.of(1, 2)); + + // +1 for vocabulary hasTopConcept + final long totalElements = 4; + assertEquals(totalElements, allReferences.getNumberOfElements()); + assertEquals(totalElements, firstPage.getTotalElements()); + assertEquals(totalElements, secondPage.getTotalElements()); + assertEquals(2, firstPage.getSize()); + assertEquals(2, secondPage.getSize()); + assertEquals(List.of(allReferences.getContent().get(0), allReferences.getContent().get(1)), firstPage.getContent()); + assertEquals(List.of(allReferences.getContent().get(2), allReferences.getContent().get(3)), secondPage.getContent()); + }); + } + + @Test + void findReferencesExcludesStatementsFromVocabularySnapshotGraphs() { + final Term term = Generator.generateTermWithId(vocabulary.getUri()); + addTermsAndSave(List.of(term), vocabulary); + + final Statement expected = statement( + Values.iri(Environment.BASE_URI + "/term/source-live"), + Values.iri(SKOS.BROADER), + Values.iri(term.getUri().toString())); + final Statement snapshotReference = statement( + Values.iri(Environment.BASE_URI + "/term/source-snapshot"), + Values.iri(SKOS.RELATED), + Values.iri(term.getUri().toString())); + final Statement rootTermReference = statement( + Values.iri(vocabulary.getUri().toString()), + Values.iri(SKOS.HAS_TOP_CONCEPT), + Values.iri(term.getUri().toString())); + + final URI snapshotUri = URI.create(vocabulary.getUri().toString() + "/version/test"); + + withStatements(vocabulary.getUri(), expected); + withStatements(snapshotUri, snapshotReference); + persistVocabularySnapshotType(snapshotUri, vocabulary.getUri()); + + readOnlyTransactional(() -> { + final var result = sut.findReferences(term, PageRequest.of(0, 10)); + + assertEquals(2, result.getContent().size()); + assertEquals(2, result.getTotalElements()); + assertTrue(result.getContent().contains(expected)); + assertTrue(result.getContent().contains(rootTermReference)); + assertFalse(result.getContent().contains(snapshotReference)); + }); + } + @Test void findAllFlatWithoutVocabularyBySearchStringReturnsTermsWithMatchingLabel() { final Term t1 = Generator.generateTermWithId(vocabulary.getUri()); @@ -1620,4 +1731,51 @@ static Set mapToIdentifiers(Collection withIdentif return withIdentifier.stream().map(HasIdentifier::getUri) .collect(Collectors.toSet()); } + + /** + * Adds {@code snaphost a versionOfVocabulary} and {@code snaphost isVersionOfVocabulary vocabulary} statements + */ + private void persistVocabularySnapshotType(URI snapshotUri, URI vocabulary) { + transactional(() -> { + final Repository repo = em.unwrap(Repository.class); + try (RepositoryConnection conn = repo.getConnection()) { + final IRI snapshot = Values.iri(snapshotUri.toString()); + final IRI context = Values.iri(snapshotUri.toString()); + conn.add(snapshot, RDF.TYPE, Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary), + context); + conn.add(snapshot, + Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_p_is_version_of_vocabulary), + Values.iri(vocabulary.toString()), context); + } + }); + } + + /** + * Persists the given statements in the given context + * + * @param context context to which the statements should be persisted + * @param statements statements to persist + */ + protected void withStatements(URI context, Statement... statements) { + final IRI contextIri = Values.iri(context.toString()); + transactional(() -> { + final Repository repo = em.unwrap(Repository.class); + try (final RepositoryConnection connection = repo.getConnection()) { + for (Statement s : statements) { + connection.add(s.getSubject(), s.getPredicate(), s.getObject(), contextIri); + } + connection.commit(); + } + }); + } + + /** + * Creates RDF4J {@link Statement} + */ + protected static Statement statement(Resource subject, IRI predicate, Value object) { + return Values.getValueFactory().createStatement( + subject, + predicate, + object); + } } diff --git a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java index 2c8675b42..570b2924e 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java @@ -54,6 +54,8 @@ import cz.cvut.kbss.termit.util.Vocabulary; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.eclipse.rdf4j.model.Statement; +import org.eclipse.rdf4j.model.util.Values; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -62,6 +64,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpHeaders; @@ -271,6 +274,43 @@ void getSubTermsLoadsSubTermsOfParentTerm() throws Exception { verify(termServiceMock).findSubTerms(term); } + @Test + void getReferencesToTermLoadsReferencingStatements() throws Exception { + final URI termUri = initTermUriResolution(); + final Term term = Generator.generateTerm(); + term.setUri(termUri); + + when(termServiceMock.findRequired(termUri)).thenReturn(term); + final Pageable pageRequest = PageRequest.of(0, 5); + + final List references = List.of( + Values.getValueFactory().createStatement(Values.iri(Environment.BASE_URI + "/term/source-1"), + Values.iri(SKOS.BROADER), + Values.iri(termUri.toString())), + Values.getValueFactory().createStatement(Values.iri(Environment.BASE_URI + "/term/source-2"), + Values.iri(SKOS.RELATED), + Values.iri(termUri.toString())) + ); + when(termServiceMock.findReferences(term, pageRequest)).thenReturn( + new PageImpl<>(references, pageRequest, references.size()) + ); + + final MvcResult mvcResult = mockMvc.perform( + get(PATH + VOCABULARY_NAME + "/terms/" + TERM_NAME + "/references") + .param(PAGE, "0") + .param(PAGE_SIZE, "5")) + .andExpect(status().isOk()) + .andReturn(); + + final String expected = objectMapper.writeValueAsString(references); + + assertEquals(expected, mvcResult.getResponse().getContentAsString()); + assertEquals(Integer.toString(references.size()), + mvcResult.getResponse().getHeader(Constants.X_TOTAL_COUNT_HEADER)); + verify(termServiceMock).findRequired(termUri); + verify(termServiceMock).findReferences(term, pageRequest); + } + @Test void getSubTermsReturnsEmptyListForTermWithoutSubTerms() throws Exception { final URI termUri = initTermUriResolution(); From e57ef7d0ec5f3788535a185993c4137f11b490a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 08:40:46 +0200 Subject: [PATCH 07/30] [Test] Ensure remove term throws when term is referenced by other term --- .../kbss/termit/persistence/dao/TermDao.java | 6 +++--- .../termit/persistence/dao/TermDaoTest.java | 19 ++++++------------- .../repository/TermRepositoryServiceTest.java | 16 ++++++++++++++++ 3 files changed, 25 insertions(+), 16 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index 9e145767f..7bcddcc26 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -101,9 +101,9 @@ public class TermDao extends BaseAssetDao implements SnapshotProvider -# )) + FILTER (?relation NOT IN ( + + )) } } """; diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java index cd40bec1f..f8f288ddb 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java @@ -1545,9 +1545,8 @@ void findReferencesReturnsStatementsReferencingTermFromVocabularyGraphs() { readOnlyTransactional(() -> { final var result = sut.findReferences(term, PageRequest.of(0, 10)); - // +1 for vocabulary hasTopConcept - assertEquals(2, result.getContent().size()); - assertEquals(2, result.getTotalElements()); + assertEquals(1, result.getContent().size()); + assertEquals(1, result.getTotalElements()); assertTrue(result.getContent().contains(expectedOne)); assertFalse(result.getContent().contains(unexpected)); }); @@ -1583,15 +1582,14 @@ void findReferencesRespectsPaging() { final Page firstPage = sut.findReferences(term, PageRequest.of(0, 2)); final Page secondPage = sut.findReferences(term, PageRequest.of(1, 2)); - // +1 for vocabulary hasTopConcept - final long totalElements = 4; + final long totalElements = expected.size(); assertEquals(totalElements, allReferences.getNumberOfElements()); assertEquals(totalElements, firstPage.getTotalElements()); assertEquals(totalElements, secondPage.getTotalElements()); assertEquals(2, firstPage.getSize()); assertEquals(2, secondPage.getSize()); assertEquals(List.of(allReferences.getContent().get(0), allReferences.getContent().get(1)), firstPage.getContent()); - assertEquals(List.of(allReferences.getContent().get(2), allReferences.getContent().get(3)), secondPage.getContent()); + assertEquals(List.of(allReferences.getContent().get(2)), secondPage.getContent()); }); } @@ -1608,10 +1606,6 @@ void findReferencesExcludesStatementsFromVocabularySnapshotGraphs() { Values.iri(Environment.BASE_URI + "/term/source-snapshot"), Values.iri(SKOS.RELATED), Values.iri(term.getUri().toString())); - final Statement rootTermReference = statement( - Values.iri(vocabulary.getUri().toString()), - Values.iri(SKOS.HAS_TOP_CONCEPT), - Values.iri(term.getUri().toString())); final URI snapshotUri = URI.create(vocabulary.getUri().toString() + "/version/test"); @@ -1622,10 +1616,9 @@ void findReferencesExcludesStatementsFromVocabularySnapshotGraphs() { readOnlyTransactional(() -> { final var result = sut.findReferences(term, PageRequest.of(0, 10)); - assertEquals(2, result.getContent().size()); - assertEquals(2, result.getTotalElements()); + assertEquals(1, result.getContent().size()); + assertEquals(1, result.getTotalElements()); assertTrue(result.getContent().contains(expected)); - assertTrue(result.getContent().contains(rootTermReference)); assertFalse(result.getContent().contains(snapshotReference)); }); } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index d52cf8014..7f7f0c6cb 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -857,6 +857,22 @@ void removeRemovesHasTopConceptReferenceToRemovedTerm() { .setParameter("term", term).getSingleResult()); } + @Test + void removeThrowsWhenTermIsReferencedByOtherTerm() { + final Term term = Generator.generateTermWithId(vocabulary.getUri()); + final Term other = Generator.generateTermWithId(vocabulary.getUri()); + other.addRelatedTerm(new TermInfo(term)); + + transactional(() -> { + em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); + em.persist(term, descriptorFactory.termDescriptor(term)); + em.persist(other, descriptorFactory.termDescriptor(other)); + }); + + final AssetRemovalException exception = assertThrows(AssetRemovalException.class, () -> sut.remove(term)); + assertEquals("error.term.remove.relationshipsExist", exception.getMessageId()); + } + @Test void removeThrowsAssetRemovalExceptionWhenTermIsReferencedByConfirmedOccurrences() { enableRdfsInference(em); From bae66a9a8da7547a72a6c61bb3d65f12d772e420 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 10:28:06 +0200 Subject: [PATCH 08/30] [Bug] Copy types into TermInfo when constructing it from AbstractTerm and copy them back when constructing Term from TermInfo --- src/main/java/cz/cvut/kbss/termit/dto/TermInfo.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/dto/TermInfo.java b/src/main/java/cz/cvut/kbss/termit/dto/TermInfo.java index 07d43e20b..140dcf1b1 100644 --- a/src/main/java/cz/cvut/kbss/termit/dto/TermInfo.java +++ b/src/main/java/cz/cvut/kbss/termit/dto/TermInfo.java @@ -75,6 +75,7 @@ public TermInfo(AbstractTerm term) { this.label = new MultilingualString(term.getLabel().getValue()); this.vocabulary = term.getVocabulary(); this.state = term.getState(); + this.types = term.getTypes(); } public TermInfo(TermInfo other) { @@ -92,6 +93,7 @@ public Term toTerm() { result.setLabel(getLabel()); result.setVocabulary(getVocabulary()); result.setState(getState()); + result.setTypes(getTypes()); return result; } From 5f0376a7bfd059537b37e449bc1a95315931c496 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 12:35:26 +0200 Subject: [PATCH 09/30] [Enhancement kbss-cvut/termit-ui#744] Fix persistent context issues when removing term with subterms --- .../repository/TermRepositoryService.java | 20 +++++---- .../term_removal/SubTermRemovalStrategy.java | 28 ++++++++----- .../repository/TermRepositoryServiceTest.java | 24 ++++++++++- .../SubTermRemovalStrategyTest.java | 42 +++++++++++++++---- 4 files changed, 86 insertions(+), 28 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index b69efb0ae..6555eba4c 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -264,6 +264,12 @@ private void addTermAsRootToVocabulary(Term instance, URI vocabularyIri) { toUpdate.addRootTerm(instance); } + /** + * Creates new term from the {@code instance} and sets its {@code parentTerm} + * + * @param instance a new Term to persist + * @param parentTerm the parent term to set for the {@code instance} + */ @Transactional public void addChildTerm(Term instance, Term parentTerm) { Objects.requireNonNull(instance); @@ -650,22 +656,18 @@ public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { // JOPA cannot manage the same individual as both Term and TermInfo, // which would otherwise prevent loading a child whose parent is the term currently being removed. final URI termUri = removalParams.termToRemove().getUri(); + Term toRemove = findRequired(termUri); removalParams = removalParams.withTerm(findRequired(termUri)); - termDao.detach(removalParams.termToRemove()); + termDao.detach(toRemove); LOG.debug("Removing term <{}>", termUri); LOG.debug("Applying sub-terms removal strategy for term <{}>", termUri); removalParams.subTermsStrategy().apply(removalParams, vocabulary, this); - - // Clear the persistence context to remove cached TermInfo instances termDao.flushAndClear(); - removalParams = removalParams.withTerm(findRequired(termUri)); - final Term toRemove = removalParams.termToRemove(); - if (toRemove.getSubTerms() != null) { - toRemove.getSubTerms().clear(); - } + toRemove.consolidateParents(); + toRemove.getParentTerms().clear(); if (termOccurrenceService.existsTargeting(toRemove) && !removalParams.removeOccurrences()) { throw new AssetRemovalException("Failed to remove term because of existing term occurrences"); @@ -678,6 +680,8 @@ public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { termDao.removeReferencesTo(toRemove); } + toRemove = update(toRemove); + termDao.flushAndClear(); this.remove(toRemove); // calls pre and post remove LOG.debug("Removed term <{}>", toRemove.getUri()); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java index dfc82f6e0..2d76ee1cd 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -1,8 +1,8 @@ package cz.cvut.kbss.termit.service.repository.term_removal; +import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.Vocabulary; -import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; import java.util.Collection; @@ -76,7 +76,7 @@ public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, final Term term = removalParams.termToRemove(); if (!term.hasParentInSameVocabulary()) { // term has no parents in the same vocabulary - makeRoots(term, vocabulary); + makeRoots(term, vocabulary, repositoryService); } final boolean hasParents = term.getParentTerms() != null && !term.getParentTerms().isEmpty(); final boolean hasExternalParents = term.getExternalParentTerms() != null && !term.getExternalParentTerms().isEmpty(); @@ -86,24 +86,30 @@ public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, } } - private void makeRoots(Term term, Vocabulary vocabulary) { + private void makeRoots(Term term, Vocabulary vocabulary, TermRepositoryService repositoryService) { term.getSubTerms().forEach(subTermInfo -> { - vocabulary.getRootTerms().add(subTermInfo.getUri()); + final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); + repositoryService.addRootTermToVocabulary(subTerm, vocabulary); }); } private void reconnectToParents(Term term, TermRepositoryService repositoryService) { // local and external parents - final Set parents = Stream.of(term.getParentTerms(), term.getExternalParentTerms()) - .flatMap(Collection::stream) - .map(HasIdentifier::getUri) - .distinct() // in case of consolidated parents - .map(repositoryService::findRequired) - .collect(Collectors.toSet()); + final Set parents = Stream.of(term.getParentTerms(), term.getExternalParentTerms()) + .flatMap(Collection::stream) + .collect(Collectors.toSet()); + + final TermInfo oldParentInfo = new TermInfo(term); // add every sub-term term.getSubTerms().forEach(subTermInfo -> { + final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); + subTerm.getParentTerms().removeIf(oldParentInfo::equals); // as a sub-term of each parent - parents.forEach(parent -> parent.getSubTerms().add(subTermInfo)); + parents.forEach(parent -> { + subTerm.getParentTerms().add(parent); + }); + subTerm.splitExternalAndInternalParents(); + repositoryService.update(subTerm); }); } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index 7f7f0c6cb..700aa19b2 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -466,6 +466,24 @@ void removeRemovesNonReferencedNonOccurringTerm() { assertNull(result); } + @Test + void removeWithParamsReconnectsChildrenToParents() { + final Term parent = Generator.generateTermWithId(vocabulary.getUri()); + final Term toRemove = Generator.generateTermWithId(vocabulary.getUri()); + final Term child = Generator.generateTermWithId(vocabulary.getUri()); + + transactional(() -> sut.addRootTermToVocabulary(parent, vocabulary)); + transactional(() -> sut.addChildTerm(toRemove, parent)); + transactional(() -> sut.addChildTerm(child, toRemove)); + transactional(() -> em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary))); + + sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.RECONNECT, false, false), vocabulary); + + final Term updatedParent = sut.findRequired(parent.getUri()); + assertFalse(updatedParent.getSubTerms().contains(new TermInfo(toRemove))); + assertTrue(updatedParent.getSubTerms().contains(new TermInfo(child))); + } + @Test void removeWithParamsCascadesToNestedChildren() { final Term parent = Generator.generateTermWithId(vocabulary.getUri()); @@ -570,12 +588,14 @@ void removeWithParamsThrowsWhenTermRelationshipsExistAndRemoveRelationshipsIsFal related.setVocabulary(vocabulary.getUri()); vocabulary.addRootTerm(toRemove); vocabulary.addRootTerm(related); + transactional(() -> { em.persist(toRemove, descriptorFactory.termDescriptor(vocabulary)); em.persist(related, descriptorFactory.termDescriptor(vocabulary)); em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); - generateRelatedInverse(toRemove, related, SKOS.RELATED); + generateRelatedInverse(toRemove, related, Environment.BASE_URI + "/example-custom-attribute"); }); + final Term loaded = sut.findRequired(toRemove.getUri()); final AssetRemovalException exception = assertThrows(AssetRemovalException.class, @@ -866,6 +886,8 @@ void removeThrowsWhenTermIsReferencedByOtherTerm() { transactional(() -> { em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); em.persist(term, descriptorFactory.termDescriptor(term)); + em.flush(); + em.clear(); em.persist(other, descriptorFactory.termDescriptor(other)); }); diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java index d6a8695cd..86e9a8155 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -18,6 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -40,6 +42,16 @@ void setUp() { term.setSubTerms(new HashSet<>()); term.setParentTerms(new HashSet<>()); term.setExternalParentTerms(new HashSet<>()); + + lenient().when(repositoryService.findRequired(term.getUri())).thenReturn(term); + + lenient().doAnswer(answer -> { + Term t = answer.getArgument(0,Term.class); + Vocabulary voc = answer.getArgument(1, Vocabulary.class); + t.setVocabulary(voc.getUri()); + voc.addRootTerm(t); + return null; + }).when(repositoryService).addRootTermToVocabulary(any(), any()); } private TermRemovalParams withStrategy(SubTermRemovalStrategy strategy) { @@ -96,35 +108,37 @@ void reconnectMakesChildrenRootTermsWhenRemovedTermHasNoParentsInSameVocabulary( term.setSubTerms(Set.of(firstChild, secondChild)); + when(repositoryService.findRequired(firstChild.getUri())).thenReturn(firstChild.toTerm()); + when(repositoryService.findRequired(secondChild.getUri())).thenReturn(secondChild.toTerm()); + params.subTermsStrategy().apply(params, vocabulary, repositoryService); assertEquals(Set.of(term.getUri(), firstChild.getUri(), secondChild.getUri()), vocabulary.getRootTerms()); - verifyNoMoreInteractions(repositoryService); } @Test void reconnectLinksChildrenToAllParents() { final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.RECONNECT); - final TermInfo child = Generator.generateTermInfoWithId(); + final Term child = Generator.generateTermWithId(vocabulary.getUri()); + final TermInfo childInfo = new TermInfo(child); final Term parent = Generator.generateTermWithId(vocabulary.getUri()); final Vocabulary externalVocabulary = Generator.generateVocabularyWithId(); final Term externalParent = Generator.generateTermWithId(externalVocabulary.getUri()); - parent.setSubTerms(new HashSet<>()); - externalParent.setSubTerms(new HashSet<>()); + makeParent(child, term); + makeParent(term, parent); - term.setSubTerms(Set.of(child)); - term.setParentTerms(Set.of(parent.toTermInfo())); term.setExternalParentTerms(Set.of(externalParent.toTermInfo())); + when(repositoryService.findRequired(child.getUri())).thenReturn(child); when(repositoryService.findRequired(parent.getUri())).thenReturn(parent); when(repositoryService.findRequired(externalParent.getUri())).thenReturn(externalParent); params.subTermsStrategy().apply(params, vocabulary, repositoryService); - assertEquals(Set.of(child), parent.getSubTerms()); - assertEquals(Set.of(child), externalParent.getSubTerms()); + assertEquals(Set.of(childInfo), parent.getSubTerms()); + assertEquals(Set.of(childInfo), externalParent.getSubTerms()); assertEquals(Set.of(term.getUri()), vocabulary.getRootTerms(), "Children must not be added as root terms"); @@ -132,4 +146,16 @@ void reconnectLinksChildrenToAllParents() { verify(repositoryService).findRequired(externalParent.getUri()); verifyNoMoreInteractions(repositoryService); } + + private void makeParent(Term childTerm, Term parentTerm) { + if (childTerm.getParentTerms() == null) { + childTerm.setParentTerms(new HashSet<>()); + } + if (parentTerm.getSubTerms() == null) { + parentTerm.setSubTerms(new HashSet<>()); + } + + childTerm.getParentTerms().add(new TermInfo(parentTerm)); + parentTerm.getSubTerms().add(new TermInfo(childTerm)); + } } From 894e3f267c725354d232e1bb6a90da153539b0e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 12:47:18 +0200 Subject: [PATCH 10/30] [Test] Fix invalid verification of parent terms in reconnectLinksChildrenToAllParents test --- .../term_removal/SubTermRemovalStrategyTest.java | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java index 86e9a8155..3a871fde1 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -121,7 +121,6 @@ void reconnectLinksChildrenToAllParents() { final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.RECONNECT); final Term child = Generator.generateTermWithId(vocabulary.getUri()); - final TermInfo childInfo = new TermInfo(child); final Term parent = Generator.generateTermWithId(vocabulary.getUri()); final Vocabulary externalVocabulary = Generator.generateVocabularyWithId(); final Term externalParent = Generator.generateTermWithId(externalVocabulary.getUri()); @@ -129,21 +128,20 @@ void reconnectLinksChildrenToAllParents() { makeParent(child, term); makeParent(term, parent); + vocabulary.getRootTerms().clear(); + vocabulary.addRootTerm(parent); + term.setExternalParentTerms(Set.of(externalParent.toTermInfo())); when(repositoryService.findRequired(child.getUri())).thenReturn(child); - when(repositoryService.findRequired(parent.getUri())).thenReturn(parent); - when(repositoryService.findRequired(externalParent.getUri())).thenReturn(externalParent); - params.subTermsStrategy().apply(params, vocabulary, repositoryService); - assertEquals(Set.of(childInfo), parent.getSubTerms()); - assertEquals(Set.of(childInfo), externalParent.getSubTerms()); + assertEquals(Set.of(parent.toTermInfo()), child.getParentTerms(), "Child must be assigned to the parent of the removed term"); + assertEquals(Set.of(externalParent.toTermInfo()), child.getExternalParentTerms()); - assertEquals(Set.of(term.getUri()), vocabulary.getRootTerms(), "Children must not be added as root terms"); + assertEquals(Set.of(parent.getUri()), vocabulary.getRootTerms(), "Vocabulary root terms must remain unchanged"); - verify(repositoryService).findRequired(parent.getUri()); - verify(repositoryService).findRequired(externalParent.getUri()); + verify(repositoryService).update(child); verifyNoMoreInteractions(repositoryService); } From bbf0465c80945dc778ff21579d58c8cedf51aaac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 13:36:13 +0200 Subject: [PATCH 11/30] [Test] Refactor tests for new remove term with params method to improve code quality --- .../kbss/termit/persistence/dao/TermDao.java | 1 + .../repository/TermRepositoryServiceTest.java | 116 ++++++++++-------- 2 files changed, 67 insertions(+), 50 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index 7bcddcc26..6422002f6 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -92,6 +92,7 @@ public class TermDao extends BaseAssetDao implements SnapshotProvider { - vocabulary.addRootTerm(parent); - em.persist(parent, descriptorFactory.termDescriptor(parent)); - em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); - }); - toRemove.addParentTerm(parent); + vocabulary.addRootTerm(toRemove); + final TermOccurrence occ = new TermDefinitionalOccurrence(toRemove.getUri(), - new DefinitionalOccurrenceTarget(referencing)); + new DefinitionalOccurrenceTarget(referencing)); occ.addType(cz.cvut.kbss.termit.util.Vocabulary.s_c_suggested_term_occurrence); occ.getTarget().setSelectors(Set.of(new TextPositionSelector(0, 10))); + occ.setUri(occurrenceUri); + transactional(() -> { em.persist(toRemove, descriptorFactory.termDescriptor(toRemove)); em.persist(referencing, descriptorFactory.termDescriptor(referencing)); @@ -536,52 +540,38 @@ void removeWithParamsThrowsWhenTermHasSuggestedOccurrencesAndRemoveOccurrencesIs em.persist(occ); em.persist(occ.getTarget()); }); - final Term loaded = sut.findRequired(toRemove.getUri()); - assertThrows(AssetRemovalException.class, - () -> sut.remove(new TermRemovalParams(loaded, SubTermRemovalStrategy.FAIL, false, false), - vocabulary)); + return sut.findRequired(toRemove.getUri()); + } + + @Test + void removeWithParamsThrowsWhenTermHasSuggestedOccurrencesAndRemoveOccurrencesIsFalse() { + final URI occurrenceUri = Generator.generateUri(); + final Term toRemove = prepareTermWithSuggestedOccurrence(occurrenceUri); + + assertThrows(AssetRemovalException.class, () -> + sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, + false, false), vocabulary)); assertNotNull(em.find(Term.class, toRemove.getUri())); - assertNotNull(em.find(TermDefinitionalOccurrence.class, occ.getUri())); + assertNotNull(em.find(TermDefinitionalOccurrence.class, occurrenceUri)); } @Test void removeWithParamsRemovesSuggestedOccurrencesWhenRemoveOccurrencesIsTrue() { - enableRdfsInference(em); - final Term parent = Generator.generateTermWithId(vocabulary.getUri()); - final Term toRemove = Generator.generateTermWithId(vocabulary.getUri()); - final Term referencing = Generator.generateTermWithId(vocabulary.getUri()); - parent.setVocabulary(vocabulary.getUri()); - toRemove.setVocabulary(vocabulary.getUri()); - vocabulary.addRootTerm(referencing); - transactional(() -> { - vocabulary.addRootTerm(parent); - em.persist(parent, descriptorFactory.termDescriptor(parent)); - em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); - }); - toRemove.addParentTerm(parent); - final TermOccurrence occ = new TermDefinitionalOccurrence(toRemove.getUri(), - new DefinitionalOccurrenceTarget(referencing)); - occ.addType(cz.cvut.kbss.termit.util.Vocabulary.s_c_suggested_term_occurrence); - occ.getTarget().setSelectors(Set.of(new TextPositionSelector(0, 10))); - transactional(() -> { - em.persist(toRemove, descriptorFactory.termDescriptor(toRemove)); - em.persist(referencing, descriptorFactory.termDescriptor(referencing)); - em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); - em.persist(occ); - em.persist(occ.getTarget()); - }); - final Term loaded = sut.findRequired(toRemove.getUri()); + final URI occurrenceUri = Generator.generateUri(); + final Term toRemove = prepareTermWithSuggestedOccurrence(occurrenceUri); - assertDoesNotThrow( - () -> sut.remove(new TermRemovalParams(loaded, SubTermRemovalStrategy.FAIL, true, false), - vocabulary)); + sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, true, false), vocabulary); assertNull(em.find(Term.class, toRemove.getUri())); - assertNull(em.find(TermDefinitionalOccurrence.class, occ.getUri())); + assertNull(em.find(TermDefinitionalOccurrence.class, occurrenceUri)); } - @Test - void removeWithParamsThrowsWhenTermRelationshipsExistAndRemoveRelationshipsIsFalse() { + /** + * Prepares and persists two terms referencing each other + * + * @return the created terms + */ + private List prepareTermsWithRelationship() { final Term toRemove = Generator.generateTermWithId(vocabulary.getUri()); final Term related = Generator.generateTermWithId(vocabulary.getUri()); toRemove.setVocabulary(vocabulary.getUri()); @@ -594,15 +584,41 @@ void removeWithParamsThrowsWhenTermRelationshipsExistAndRemoveRelationshipsIsFal em.persist(related, descriptorFactory.termDescriptor(vocabulary)); em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary)); generateRelatedInverse(toRemove, related, Environment.BASE_URI + "/example-custom-attribute"); + generateRelatedInverse(related, toRemove, Environment.BASE_URI + "/different-example-custom-attribute"); }); - final Term loaded = sut.findRequired(toRemove.getUri()); + return List.of(sut.findRequired(toRemove.getUri()), + sut.findRequired(related.getUri())); + } + + @Test + void removeWithParamsThrowsWhenTermRelationshipsExistAndRemoveRelationshipsIsFalse() { + final List terms = prepareTermsWithRelationship(); + final Term toRemove = terms.getFirst(); + final Term related = terms.getLast(); + assertNotEquals(toRemove, related); final AssetRemovalException exception = assertThrows(AssetRemovalException.class, - () -> sut.remove(new TermRemovalParams(loaded, SubTermRemovalStrategy.FAIL, false, false), - vocabulary)); + () -> sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, + false, false), vocabulary)); assertEquals("error.term.remove.relationshipsExist", exception.getMessageId()); + // none of the terms must be removed because of the exception assertNotNull(em.find(Term.class, toRemove.getUri())); + assertNotNull(em.find(Term.class, related.getUri())); + } + + @Test + void removeWithParamsRemovesTermRelationshipsWhenRemoveRelationshipsIsTrue() { + final List terms = prepareTermsWithRelationship(); + final Term toRemove = terms.getFirst(); + final Term related = terms.getLast(); + assertNotEquals(toRemove, related); + + sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, + false, true), vocabulary); + + assertNull(em.find(Term.class, toRemove.getUri()), "The term must be removed"); + assertNotNull(em.find(Term.class, related.getUri()), "The other term must not be removed"); } private void generateRelatedInverse(Term term, Term related, String property) { From 2c9a77a35f2e8e69b50ec2c5142e548c32d20d55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 14:18:07 +0200 Subject: [PATCH 12/30] [Enhancement kbss-cvut/termit-ui#744] Update SubTermRemovalStrategy to delegate vocabulary root terms handling to term repository service --- .../term_removal/SubTermRemovalStrategy.java | 26 ++++++++++++++----- .../SubTermRemovalStrategyTest.java | 25 +++++++++++++----- 2 files changed, 39 insertions(+), 12 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java index 2d76ee1cd..bb7408e3d 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -74,10 +74,12 @@ private static class ReconnectApplier implements TermParamsApplier { public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, TermRepositoryService repositoryService) { final Term term = removalParams.termToRemove(); - if (!term.hasParentInSameVocabulary()) { - // term has no parents in the same vocabulary - makeRoots(term, vocabulary, repositoryService); + final TermInfo termInfo = new TermInfo(term); + + if (term.getSubTerms() != null && !term.getSubTerms().isEmpty()) { + removeParent(term.getSubTerms(), termInfo, repositoryService); } + final boolean hasParents = term.getParentTerms() != null && !term.getParentTerms().isEmpty(); final boolean hasExternalParents = term.getExternalParentTerms() != null && !term.getExternalParentTerms().isEmpty(); if (hasParents || hasExternalParents) { @@ -86,10 +88,22 @@ public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, } } - private void makeRoots(Term term, Vocabulary vocabulary, TermRepositoryService repositoryService) { - term.getSubTerms().forEach(subTermInfo -> { + /** + * Removes the given parent from every given children. + * + * @param children children from which the {@code parentToRemove} should be removed + * @param parentToRemove the parent that should be removed from {@code children} + * @param repositoryService the {@link TermRepositoryService} to retrieve and update children terms + */ + private void removeParent(Collection children, TermInfo parentToRemove, TermRepositoryService repositoryService) { + children.forEach(subTermInfo -> { final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); - repositoryService.addRootTermToVocabulary(subTerm, vocabulary); + + final Collection childParents = subTerm.getParentTerms(); + if (childParents != null && !childParents.isEmpty()) { + childParents.removeIf(parentToRemove::equals); + repositoryService.update(subTerm); + } }); } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java index 3a871fde1..bd53d0edc 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -19,7 +19,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -101,19 +103,30 @@ void cascadeRemovesAllChildrenUsingSameRemovalParameters() { } @Test - void reconnectMakesChildrenRootTermsWhenRemovedTermHasNoParentsInSameVocabulary() { + void reconnectUpdatesChildrenToHandleVocabularyRootTermAddition() { final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.RECONNECT); final TermInfo firstChild = Generator.generateTermInfoWithId(); final TermInfo secondChild = Generator.generateTermInfoWithId(); - term.setSubTerms(Set.of(firstChild, secondChild)); + final Term firstChildTerm = firstChild.toTerm(); + final Term secondChildTerm = secondChild.toTerm(); - when(repositoryService.findRequired(firstChild.getUri())).thenReturn(firstChild.toTerm()); - when(repositoryService.findRequired(secondChild.getUri())).thenReturn(secondChild.toTerm()); + makeParent(firstChildTerm, term); + makeParent(secondChildTerm, term); + + firstChild.setVocabulary(vocabulary.getUri()); + secondChild.setVocabulary(Generator.generateUri()); + + when(repositoryService.findRequired(firstChild.getUri())).thenReturn(firstChildTerm); + when(repositoryService.findRequired(secondChild.getUri())).thenReturn(secondChildTerm); params.subTermsStrategy().apply(params, vocabulary, repositoryService); - assertEquals(Set.of(term.getUri(), firstChild.getUri(), secondChild.getUri()), vocabulary.getRootTerms()); + verify(repositoryService, atLeastOnce()).findRequired(any()); + // repository post-update handles root term assignment + verify(repositoryService).update(firstChildTerm); + verify(repositoryService).update(secondChildTerm); + verifyNoMoreInteractions(repositoryService); } @Test @@ -141,7 +154,7 @@ void reconnectLinksChildrenToAllParents() { assertEquals(Set.of(parent.getUri()), vocabulary.getRootTerms(), "Vocabulary root terms must remain unchanged"); - verify(repositoryService).update(child); + verify(repositoryService, times(2)).update(child); verifyNoMoreInteractions(repositoryService); } From 3f2137f4eee1bd0a79d733939338ffb0fc24291b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 14:46:59 +0200 Subject: [PATCH 13/30] [Enhancement kbss-cvut/termit-ui#744] Refactor sub term reconnecting removal strategy to eliminate double children update causing test instability --- .../term_removal/SubTermRemovalStrategy.java | 57 +++++++++++-------- .../repository/TermRepositoryServiceTest.java | 6 +- .../SubTermRemovalStrategyTest.java | 4 +- 3 files changed, 39 insertions(+), 28 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java index bb7408e3d..305b8039e 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -3,13 +3,13 @@ import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; import java.util.Collection; +import java.util.Collections; import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; +import java.util.Optional; /** * Describes an operation how should be sub-terms handled during term removal @@ -76,16 +76,30 @@ public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, final Term term = removalParams.termToRemove(); final TermInfo termInfo = new TermInfo(term); - if (term.getSubTerms() != null && !term.getSubTerms().isEmpty()) { - removeParent(term.getSubTerms(), termInfo, repositoryService); - } + final Collection subTerms = Optional.ofNullable(term.getSubTerms()) + .map(children -> children.stream() + .map(HasIdentifier::getUri) + .map(repositoryService::findRequired) + .map(t -> { + t.consolidateParents(); + return t; + }) + .toList()) + .orElse(Collections.emptyList()); + + removeParent(subTerms, termInfo); final boolean hasParents = term.getParentTerms() != null && !term.getParentTerms().isEmpty(); final boolean hasExternalParents = term.getExternalParentTerms() != null && !term.getExternalParentTerms().isEmpty(); if (hasParents || hasExternalParents) { // term has some parents to which children should be reconnected - reconnectToParents(term, repositoryService); + reconnectToParents(subTerms, term); } + + subTerms.forEach(subTerm -> { + subTerm.splitExternalAndInternalParents(); + repositoryService.update(subTerm); + }); } /** @@ -93,37 +107,32 @@ public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, * * @param children children from which the {@code parentToRemove} should be removed * @param parentToRemove the parent that should be removed from {@code children} - * @param repositoryService the {@link TermRepositoryService} to retrieve and update children terms */ - private void removeParent(Collection children, TermInfo parentToRemove, TermRepositoryService repositoryService) { - children.forEach(subTermInfo -> { - final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); - + private void removeParent(Collection children, TermInfo parentToRemove) { + children.forEach(subTerm -> { final Collection childParents = subTerm.getParentTerms(); if (childParents != null && !childParents.isEmpty()) { childParents.removeIf(parentToRemove::equals); - repositoryService.update(subTerm); } }); } - private void reconnectToParents(Term term, TermRepositoryService repositoryService) { - // local and external parents - final Set parents = Stream.of(term.getParentTerms(), term.getExternalParentTerms()) - .flatMap(Collection::stream) - .collect(Collectors.toSet()); - + /** + * Adds every parent of {@code term} as parent of every sub-term from {@code subTerms}. + * Removes the {@code term} from parents of {@code subTerms}. + * + * @param subTerms sub-terms whose parents should be modified + * @param term the parent of {@code subTerms} + */ + private void reconnectToParents(Collection subTerms, Term term) { final TermInfo oldParentInfo = new TermInfo(term); // add every sub-term - term.getSubTerms().forEach(subTermInfo -> { - final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); + subTerms.forEach(subTerm -> { subTerm.getParentTerms().removeIf(oldParentInfo::equals); // as a sub-term of each parent - parents.forEach(parent -> { + term.getParentTerms().forEach(parent -> { subTerm.getParentTerms().add(parent); }); - subTerm.splitExternalAndInternalParents(); - repositoryService.update(subTerm); }); } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index a5e89c7e8..61c6974e5 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -481,8 +481,10 @@ void removeWithParamsReconnectsChildrenToParents() { sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.RECONNECT, false, false), vocabulary); final Term updatedParent = sut.findRequired(parent.getUri()); - assertFalse(updatedParent.getSubTerms().contains(new TermInfo(toRemove))); - assertTrue(updatedParent.getSubTerms().contains(new TermInfo(child))); + assertFalse(updatedParent.getSubTerms().stream().anyMatch(new TermInfo(toRemove)::equals), + "Term to remove must be removed from its parent"); + assertTrue(updatedParent.getSubTerms().stream().anyMatch(new TermInfo(child)::equals), + "Child of removed term must be reconnected to the parent"); } @Test diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java index bd53d0edc..1775cdd99 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -21,7 +21,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.lenient; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -140,6 +139,7 @@ void reconnectLinksChildrenToAllParents() { makeParent(child, term); makeParent(term, parent); + makeParent(term, externalParent); vocabulary.getRootTerms().clear(); vocabulary.addRootTerm(parent); @@ -154,7 +154,7 @@ void reconnectLinksChildrenToAllParents() { assertEquals(Set.of(parent.getUri()), vocabulary.getRootTerms(), "Vocabulary root terms must remain unchanged"); - verify(repositoryService, times(2)).update(child); + verify(repositoryService).update(child); verifyNoMoreInteractions(repositoryService); } From 050c86688b8b7ecd4f238e23a9be3124253f9365 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 4 Sep 2026 15:22:59 +0200 Subject: [PATCH 14/30] [Ref] Include contexts in term reference statements --- .../kbss/termit/persistence/dao/TermDao.java | 26 +++++++++++------ .../termit/persistence/dao/TermDaoTest.java | 29 ++++++++++++------- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index 6422002f6..2cc752e8e 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -49,12 +49,12 @@ import cz.cvut.kbss.termit.service.snapshot.SnapshotProvider; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Utils; +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.util.Values; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.GraphQuery; -import org.eclipse.rdf4j.query.GraphQueryResult; import org.eclipse.rdf4j.query.Operation; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; @@ -1382,18 +1382,26 @@ private long countReferences(RepositoryConnection con, AbstractTerm term) { * @return the list of statements referencing the term as object */ private List findReferences(RepositoryConnection con, AbstractTerm term, Pageable pageable) { - final GraphQuery query = con.prepareGraphQuery(""" - CONSTRUCT { - ?other ?relation ?term . - } - """ + REFERENCES_TO_TERM_WHERE_CLAUSE + + final TupleQuery query = con.prepareTupleQuery( + "SELECT ?other ?relation ?term ?context " + REFERENCES_TO_TERM_WHERE_CLAUSE + " OFFSET " + pageable.getOffset() + " LIMIT " + pageable.getPageSize()); bindReferencesQueryParameters(query, term); query.setIncludeInferred(false); - try (GraphQueryResult result = query.evaluate()) { - return result.stream().toList(); + + final List statements = new ArrayList<>(pageable.getPageSize()); + try (TupleQueryResult result = query.evaluate()) { + while (result.hasNext()) { + final BindingSet bindings = result.next(); + statements.add(Values.getValueFactory().createStatement( + (Resource) bindings.getValue("other"), + (IRI) bindings.getValue("relation"), + bindings.getValue("term"), + (Resource) bindings.getValue("context") + )); + } } + return statements; } /** diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java index f8f288ddb..710f72a1d 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/TermDaoTest.java @@ -1532,12 +1532,14 @@ void findReferencesReturnsStatementsReferencingTermFromVocabularyGraphs() { final Statement expectedOne = statement( Values.iri(Environment.BASE_URI + "/term/source-1"), Values.iri(SKOS.BROADER), - Values.iri(term.getUri().toString()) + Values.iri(term.getUri().toString()), + Values.iri(vocabulary.getUri().toString()) ); final Statement unexpected = statement( Values.iri(Environment.BASE_URI + "/term/source-2"), Values.iri(SKOS.RELATED), - Values.iri(Generator.generateUriString()) + Values.iri(Generator.generateUriString()), + Values.iri(vocabulary.getUri().toString()) ); withStatements(vocabulary.getUri(), expectedOne, unexpected); @@ -1561,17 +1563,20 @@ void findReferencesRespectsPaging() { statement( Values.iri(Environment.BASE_URI + "/term/source-1"), Values.iri(SKOS.BROADER), - Values.iri(term.getUri().toString()) + Values.iri(term.getUri().toString()), + Values.iri(vocabulary.getUri().toString()) ), statement( Values.iri(Environment.BASE_URI + "/term/source-2"), Values.iri(SKOS.RELATED), - Values.iri(term.getUri().toString()) + Values.iri(term.getUri().toString()), + Values.iri(vocabulary.getUri().toString()) ), statement( Values.iri(Environment.BASE_URI + "/term/source-3"), Values.iri(SKOS.EXACT_MATCH), - Values.iri(term.getUri().toString()) + Values.iri(term.getUri().toString()), + Values.iri(vocabulary.getUri().toString()) ) ); @@ -1601,13 +1606,14 @@ void findReferencesExcludesStatementsFromVocabularySnapshotGraphs() { final Statement expected = statement( Values.iri(Environment.BASE_URI + "/term/source-live"), Values.iri(SKOS.BROADER), - Values.iri(term.getUri().toString())); + Values.iri(term.getUri().toString()), + Values.iri(vocabulary.getUri().toString())); + final URI snapshotUri = URI.create(vocabulary.getUri().toString() + "/version/test"); final Statement snapshotReference = statement( Values.iri(Environment.BASE_URI + "/term/source-snapshot"), Values.iri(SKOS.RELATED), - Values.iri(term.getUri().toString())); - - final URI snapshotUri = URI.create(vocabulary.getUri().toString() + "/version/test"); + Values.iri(term.getUri().toString()), + Values.iri(snapshotUri.toString())); withStatements(vocabulary.getUri(), expected); withStatements(snapshotUri, snapshotReference); @@ -1765,10 +1771,11 @@ protected void withStatements(URI context, Statement... statements) { /** * Creates RDF4J {@link Statement} */ - protected static Statement statement(Resource subject, IRI predicate, Value object) { + protected static Statement statement(Resource subject, IRI predicate, Value object, Resource context) { return Values.getValueFactory().createStatement( subject, predicate, - object); + object, + context); } } From 08b65de5b085f4809fb77bccd405e3f905c06ba1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 7 Sep 2026 07:34:51 +0200 Subject: [PATCH 15/30] [Ref] Fix fetching term from database twice during term removal --- .../kbss/termit/service/repository/TermRepositoryService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index 6555eba4c..d7beb68d2 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -657,7 +657,7 @@ public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { // which would otherwise prevent loading a child whose parent is the term currently being removed. final URI termUri = removalParams.termToRemove().getUri(); Term toRemove = findRequired(termUri); - removalParams = removalParams.withTerm(findRequired(termUri)); + removalParams = removalParams.withTerm(toRemove); termDao.detach(toRemove); LOG.debug("Removing term <{}>", termUri); From a633193232f86a4cf8807c56088a3d6efaf8ec22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 7 Sep 2026 10:06:04 +0200 Subject: [PATCH 16/30] [Ref] Remove unused Vocabulary parameter from remove term with params method --- .../termit/service/business/TermService.java | 4 ++-- .../repository/TermRepositoryService.java | 7 ++++--- .../term_removal/SubTermRemovalStrategy.java | 16 ++++++---------- .../term_removal/TermParamsApplier.java | 4 +--- 4 files changed, 13 insertions(+), 18 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java index d6506d970..f9230f07b 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java @@ -657,8 +657,8 @@ public void remove(TermRemovalParams termRemovalParams) { Objects.requireNonNull(termRemovalParams); Objects.requireNonNull(termRemovalParams.termToRemove()); Objects.requireNonNull(termRemovalParams.termToRemove().getVocabulary()); - final Vocabulary vocabulary = findVocabularyRequired(termRemovalParams.termToRemove().getVocabulary()); - repositoryService.remove(termRemovalParams, vocabulary); + + repositoryService.remove(termRemovalParams); } /** diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index d7beb68d2..5aba2f2c3 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -205,6 +205,8 @@ private void pruneAndNormalizeTranslations(Term instance) { @Override protected void postUpdate(@Nonnull Term instance) { final Vocabulary vocabulary = vocabularyService.findRequired(instance.getVocabulary()); + // Jopa should always set at least empty collection + Objects.requireNonNull(vocabulary.getRootTerms(), "Vocabulary must have root terms collection"); if (instance.hasParentInSameVocabulary()) { vocabulary.removeRootTerm(instance); } else { @@ -647,10 +649,9 @@ public Optional findTermVocabulary(URI termId) { * @param removalParams Params describing how the term should be removed */ @Transactional - public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { + public void remove(TermRemovalParams removalParams) { Objects.requireNonNull(removalParams); Objects.requireNonNull(removalParams.termToRemove().getUri()); - Objects.requireNonNull(vocabulary); // Refresh the instance from storage, then detach it before traversing term relationships. // JOPA cannot manage the same individual as both Term and TermInfo, @@ -663,7 +664,7 @@ public void remove(TermRemovalParams removalParams, Vocabulary vocabulary) { LOG.debug("Removing term <{}>", termUri); LOG.debug("Applying sub-terms removal strategy for term <{}>", termUri); - removalParams.subTermsStrategy().apply(removalParams, vocabulary, this); + removalParams.subTermsStrategy().apply(removalParams, this); termDao.flushAndClear(); toRemove.consolidateParents(); diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java index 305b8039e..0b1b3553f 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -2,7 +2,6 @@ import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.model.Term; -import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; @@ -39,8 +38,8 @@ public enum SubTermRemovalStrategy implements TermParamsApplier { } @Override - public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, TermRepositoryService repositoryService) { - applier.apply(removalParams, vocabulary, repositoryService); + public void apply(TermRemovalParams removalParams, TermRepositoryService repositoryService) { + applier.apply(removalParams, repositoryService); } /** @@ -50,13 +49,12 @@ private static class CascadeRemoveApplier implements TermParamsApplier { static final CascadeRemoveApplier INSTANCE = new CascadeRemoveApplier(); @Override - public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, - TermRepositoryService repositoryService) { + public void apply(TermRemovalParams removalParams, TermRepositoryService repositoryService) { final Term term = removalParams.termToRemove(); if (term.getSubTerms() != null) { term.getSubTerms().forEach(subTermInfo -> { final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); - repositoryService.remove(removalParams.withTerm(subTerm), vocabulary); + repositoryService.remove(removalParams.withTerm(subTerm)); }); } } @@ -71,8 +69,7 @@ private static class ReconnectApplier implements TermParamsApplier { static final ReconnectApplier INSTANCE = new ReconnectApplier(); @Override - public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, - TermRepositoryService repositoryService) { + public void apply(TermRemovalParams removalParams, TermRepositoryService repositoryService) { final Term term = removalParams.termToRemove(); final TermInfo termInfo = new TermInfo(term); @@ -143,8 +140,7 @@ private void reconnectToParents(Collection subTerms, Term term) { private static class FailApplier implements TermParamsApplier { static final FailApplier INSTANCE = new FailApplier(); @Override - public void apply(TermRemovalParams removalParams, Vocabulary vocabulary, - TermRepositoryService repositoryService) { + public void apply(TermRemovalParams removalParams, TermRepositoryService repositoryService) { final Term term = removalParams.termToRemove(); if (!term.getSubTerms().isEmpty()) { throw TermRepositoryService.hasSubTermsException(term.getSubTerms()); diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java index 7ec6bcbba..b1d93b691 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java @@ -1,6 +1,5 @@ package cz.cvut.kbss.termit.service.repository.term_removal; -import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; /** @@ -11,8 +10,7 @@ public interface TermParamsApplier { * Applies the operation described by the parameters. * * @param removalParams Params describing how the term should be removed. - * @param vocabulary Vocabulary of the {@code term} * @param repositoryService Service for interacting with the term repository */ - void apply(TermRemovalParams removalParams, Vocabulary vocabulary, TermRepositoryService repositoryService); + void apply(TermRemovalParams removalParams, TermRepositoryService repositoryService); } From c1b8dc3ba564db4c2d723110f47e74249950f643 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 7 Sep 2026 12:10:04 +0200 Subject: [PATCH 17/30] [Enhancement kbss-cvut/termit-ui#744] Order references to term by subject predicate and context --- src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index 2cc752e8e..ddc3dbff9 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -1384,6 +1384,7 @@ private long countReferences(RepositoryConnection con, AbstractTerm term) { private List findReferences(RepositoryConnection con, AbstractTerm term, Pageable pageable) { final TupleQuery query = con.prepareTupleQuery( "SELECT ?other ?relation ?term ?context " + REFERENCES_TO_TERM_WHERE_CLAUSE + + " ORDER BY ?other ?relation ?context" + " OFFSET " + pageable.getOffset() + " LIMIT " + pageable.getPageSize()); bindReferencesQueryParameters(query, term); From 531cfad9f37495efd4d8f0e68ce61665c3da8d81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 7 Sep 2026 14:58:47 +0200 Subject: [PATCH 18/30] [Test] Fix term removal with params test compilation after updating method signatures by removing vocabulary parameter --- .../repository/TermRepositoryServiceTest.java | 12 ++++++------ .../term_removal/SubTermRemovalStrategyTest.java | 14 +++++++------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index 61c6974e5..6382e3d47 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -478,7 +478,7 @@ void removeWithParamsReconnectsChildrenToParents() { transactional(() -> sut.addChildTerm(child, toRemove)); transactional(() -> em.merge(vocabulary, descriptorFactory.vocabularyDescriptor(vocabulary))); - sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.RECONNECT, false, false), vocabulary); + sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.RECONNECT, false, false)); final Term updatedParent = sut.findRequired(parent.getUri()); assertFalse(updatedParent.getSubTerms().stream().anyMatch(new TermInfo(toRemove)::equals), @@ -503,7 +503,7 @@ void removeWithParamsCascadesToNestedChildren() { assertNotNull(em.find(Term.class, grandChild.getUri())); // remove parent and all children - sut.remove(new TermRemovalParams(parent, SubTermRemovalStrategy.CASCADE, false, true), vocabulary); + sut.remove(new TermRemovalParams(parent, SubTermRemovalStrategy.CASCADE, false, true)); assertNull(em.find(Term.class, parent.getUri())); assertNull(em.find(Term.class, child.getUri())); @@ -553,7 +553,7 @@ void removeWithParamsThrowsWhenTermHasSuggestedOccurrencesAndRemoveOccurrencesIs assertThrows(AssetRemovalException.class, () -> sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, - false, false), vocabulary)); + false, false))); assertNotNull(em.find(Term.class, toRemove.getUri())); assertNotNull(em.find(TermDefinitionalOccurrence.class, occurrenceUri)); } @@ -563,7 +563,7 @@ void removeWithParamsRemovesSuggestedOccurrencesWhenRemoveOccurrencesIsTrue() { final URI occurrenceUri = Generator.generateUri(); final Term toRemove = prepareTermWithSuggestedOccurrence(occurrenceUri); - sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, true, false), vocabulary); + sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, true, false)); assertNull(em.find(Term.class, toRemove.getUri())); assertNull(em.find(TermDefinitionalOccurrence.class, occurrenceUri)); } @@ -602,7 +602,7 @@ void removeWithParamsThrowsWhenTermRelationshipsExistAndRemoveRelationshipsIsFal final AssetRemovalException exception = assertThrows(AssetRemovalException.class, () -> sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, - false, false), vocabulary)); + false, false))); assertEquals("error.term.remove.relationshipsExist", exception.getMessageId()); // none of the terms must be removed because of the exception assertNotNull(em.find(Term.class, toRemove.getUri())); @@ -617,7 +617,7 @@ void removeWithParamsRemovesTermRelationshipsWhenRemoveRelationshipsIsTrue() { assertNotEquals(toRemove, related); sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, - false, true), vocabulary); + false, true)); assertNull(em.find(Term.class, toRemove.getUri()), "The term must be removed"); assertNotNull(em.find(Term.class, related.getUri()), "The other term must not be removed"); diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java index 1775cdd99..cd97237aa 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -65,14 +65,14 @@ void failThrowsWhenTermHasChildren() { final TermInfo child = Generator.generateTermInfoWithId(); term.setSubTerms(Set.of(child)); - final TermItException exception = assertThrows(TermItException.class, () -> params.subTermsStrategy().apply(params, vocabulary, repositoryService)); + final TermItException exception = assertThrows(TermItException.class, () -> params.subTermsStrategy().apply(params, repositoryService)); assertEquals("error.term.remove.hasSubTerms", exception.getMessageId()); } @Test void failDoesNotThrowWhenTermHasNoChildren() { final TermRemovalParams params = withStrategy(SubTermRemovalStrategy.FAIL); - assertDoesNotThrow(() -> params.subTermsStrategy().apply(params, vocabulary, repositoryService)); + assertDoesNotThrow(() -> params.subTermsStrategy().apply(params, repositoryService)); } @Test @@ -92,12 +92,12 @@ void cascadeRemovesAllChildrenUsingSameRemovalParameters() { when(repositoryService.findRequired(firstChildInfo.getUri())).thenReturn(firstChild); when(repositoryService.findRequired(secondChildInfo.getUri())).thenReturn(secondChild); - params.subTermsStrategy().apply(params, vocabulary, repositoryService); + params.subTermsStrategy().apply(params, repositoryService); verify(repositoryService).findRequired(firstChildInfo.getUri()); verify(repositoryService).findRequired(secondChildInfo.getUri()); - verify(repositoryService).remove(params.withTerm(firstChild), vocabulary); - verify(repositoryService).remove(params.withTerm(secondChild), vocabulary); + verify(repositoryService).remove(params.withTerm(firstChild)); + verify(repositoryService).remove(params.withTerm(secondChild)); verifyNoMoreInteractions(repositoryService); } @@ -119,7 +119,7 @@ void reconnectUpdatesChildrenToHandleVocabularyRootTermAddition() { when(repositoryService.findRequired(firstChild.getUri())).thenReturn(firstChildTerm); when(repositoryService.findRequired(secondChild.getUri())).thenReturn(secondChildTerm); - params.subTermsStrategy().apply(params, vocabulary, repositoryService); + params.subTermsStrategy().apply(params, repositoryService); verify(repositoryService, atLeastOnce()).findRequired(any()); // repository post-update handles root term assignment @@ -147,7 +147,7 @@ void reconnectLinksChildrenToAllParents() { term.setExternalParentTerms(Set.of(externalParent.toTermInfo())); when(repositoryService.findRequired(child.getUri())).thenReturn(child); - params.subTermsStrategy().apply(params, vocabulary, repositoryService); + params.subTermsStrategy().apply(params, repositoryService); assertEquals(Set.of(parent.toTermInfo()), child.getParentTerms(), "Child must be assigned to the parent of the removed term"); assertEquals(Set.of(externalParent.toTermInfo()), child.getExternalParentTerms()); From 38ab3912a7a60f4f75d3bfe1bea4b88b42137861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 7 Sep 2026 15:09:44 +0200 Subject: [PATCH 19/30] [Test] Fix fialing tests by adding empty hashset as root terms for generated vocabularies --- src/test/java/cz/cvut/kbss/termit/environment/Generator.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/cz/cvut/kbss/termit/environment/Generator.java b/src/test/java/cz/cvut/kbss/termit/environment/Generator.java index 9282e22f6..06e81d1c9 100644 --- a/src/test/java/cz/cvut/kbss/termit/environment/Generator.java +++ b/src/test/java/cz/cvut/kbss/termit/environment/Generator.java @@ -258,6 +258,7 @@ public static cz.cvut.kbss.termit.model.Vocabulary generateVocabulary() { vocabulary.setLabel(MultilingualString.create("Vocabulary" + randomInt(), primaryLanguage)); vocabulary.setDescription(MultilingualString.create( "Description of vocabulary " + vocabulary.getPrimaryLabel(), primaryLanguage)); + vocabulary.setRootTerms(new HashSet<>()); return vocabulary; } From c2c3dc4c9977fd4fec9720c06ffc41a523d726da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 14 Sep 2026 15:18:36 +0200 Subject: [PATCH 20/30] [Bug] Replace unwrapping entity manager to Repository with unwrapping directly to RepositoryConnection --- .../kbss/termit/persistence/dao/BaseDao.java | 24 +++++++++++++++++++ .../kbss/termit/persistence/dao/TermDao.java | 17 ++++++------- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java index 93b7d2985..0854e3092 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java @@ -26,6 +26,9 @@ import cz.cvut.kbss.termit.model.util.EntityToOwlClassMapper; import cz.cvut.kbss.termit.model.util.HasIdentifier; import jakarta.annotation.Nonnull; +import org.eclipse.rdf4j.repository.RepositoryConnection; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; @@ -40,6 +43,7 @@ */ public abstract class BaseDao implements GenericDao, ApplicationEventPublisherAware { + private static final Logger LOG = LoggerFactory.getLogger(BaseDao.class); protected final Class type; protected final URI typeUri; @@ -162,4 +166,24 @@ protected Descriptor getDescriptor() { public void setApplicationEventPublisher(@Nonnull ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } + + /** + * Unwraps the supplied entity manager to {@link RepositoryConnection} within the current active transaction. + * + * @param entityManager the entity manager to unwrap + * @return open repository connection with active current transaction + * @implSpec The connection is managed by the {@link EntityManager} and must not be used with try-auto-close statement. + */ + public static RepositoryConnection unwrapToConnection(EntityManager entityManager) { + if (!entityManager.isOpen() || !entityManager.getTransaction().isActive()) { + throw new IllegalStateException("Entity manager is not open(" + entityManager.isOpen() + + ") or there is no active transaction (" + entityManager.getTransaction().isActive() + ")!"); + } + final RepositoryConnection connection = entityManager.unwrap(RepositoryConnection.class); + if (connection != null && connection.isActive()) { + return connection; + } + entityManager.createNativeQuery("ASK {}", Boolean.class).getSingleResult(); // force em to open a connection + return Objects.requireNonNull(entityManager.unwrap(RepositoryConnection.class), "Failed to acquire repository connection"); + } } diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index ddc3dbff9..b4564b7e0 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -1341,15 +1341,16 @@ public Page findReferences(AbstractTerm term, Pageable pageable) { Objects.requireNonNull(pageable, "Pageable cannot be null"); try { - try (RepositoryConnection con = em.unwrap(org.eclipse.rdf4j.repository.Repository.class).getConnection()) { - final long totalCount = countReferences(con, term); - if (totalCount == 0 || pageable.getOffset() >= totalCount) { - return new PageImpl<>(List.of(), pageable, totalCount); - } - - final List statements = findReferences(con, term, pageable); - return new PageImpl<>(statements, pageable, totalCount); + RepositoryConnection con = unwrapToConnection(em); + // On purpose not using auto-closable with try statement to prevent closing the connection here + // the connection is managed by Entity Manager + final long totalCount = countReferences(con, term); + if (totalCount == 0 || pageable.getOffset() >= totalCount) { + return new PageImpl<>(List.of(), pageable, totalCount); } + + final List statements = findReferences(con, term, pageable); + return new PageImpl<>(statements, pageable, totalCount); } catch (RuntimeException e) { throw new PersistenceException("Failed to find references to term " + Utils.uriToString(term.getUri()), e); } From 582474c7e6dc9590743308f5bdf4eba0ab7bb546 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 14 Sep 2026 16:14:47 +0200 Subject: [PATCH 21/30] [Ref] Rename TermParamsApplier to TermRemovalParamsApplier --- .../term_removal/SubTermRemovalStrategy.java | 12 ++++++------ ...amsApplier.java => TermRemovalParamsApplier.java} | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) rename src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/{TermParamsApplier.java => TermRemovalParamsApplier.java} (92%) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java index 0b1b3553f..89492549d 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -13,7 +13,7 @@ /** * Describes an operation how should be sub-terms handled during term removal */ -public enum SubTermRemovalStrategy implements TermParamsApplier { +public enum SubTermRemovalStrategy implements TermRemovalParamsApplier { /** * All sub-terms will be removed using the same {@link TermRemovalParams} */ @@ -31,9 +31,9 @@ public enum SubTermRemovalStrategy implements TermParamsApplier { */ FAIL(FailApplier.INSTANCE); - private final TermParamsApplier applier; + private final TermRemovalParamsApplier applier; - SubTermRemovalStrategy(TermParamsApplier applier) { + SubTermRemovalStrategy(TermRemovalParamsApplier applier) { this.applier = Objects.requireNonNull(applier); } @@ -45,7 +45,7 @@ public void apply(TermRemovalParams removalParams, TermRepositoryService reposit /** * Removes every child of the given term */ - private static class CascadeRemoveApplier implements TermParamsApplier { + private static class CascadeRemoveApplier implements TermRemovalParamsApplier { static final CascadeRemoveApplier INSTANCE = new CascadeRemoveApplier(); @Override @@ -65,7 +65,7 @@ public void apply(TermRemovalParams removalParams, TermRepositoryService reposit * Every child becomes child of its grandparent. * If the term being removed has no parents in the current vocabulary, children become root terms. */ - private static class ReconnectApplier implements TermParamsApplier { + private static class ReconnectApplier implements TermRemovalParamsApplier { static final ReconnectApplier INSTANCE = new ReconnectApplier(); @Override @@ -137,7 +137,7 @@ private void reconnectToParents(Collection subTerms, Term term) { /** * Throws an exception when the term to be removed has sub-terms. */ - private static class FailApplier implements TermParamsApplier { + private static class FailApplier implements TermRemovalParamsApplier { static final FailApplier INSTANCE = new FailApplier(); @Override public void apply(TermRemovalParams removalParams, TermRepositoryService repositoryService) { diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java similarity index 92% rename from src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java rename to src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java index b1d93b691..5d27b7c8e 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermParamsApplier.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java @@ -5,7 +5,7 @@ /** * Applier performing the given operation described by the parameters. */ -public interface TermParamsApplier { +public interface TermRemovalParamsApplier { /** * Applies the operation described by the parameters. * From 939aa40fd705c81adff2757f0bc78df2ac3dead9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 15 Sep 2026 10:28:39 +0200 Subject: [PATCH 22/30] [Ref] Do not call term update during term removal --- .../termit/service/repository/TermRepositoryService.java | 2 -- .../repository/term_removal/SubTermRemovalStrategy.java | 5 +++++ .../repository/term_removal/SubTermRemovalStrategyTest.java | 4 +++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index 5aba2f2c3..5ff370a3c 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -681,8 +681,6 @@ public void remove(TermRemovalParams removalParams) { termDao.removeReferencesTo(toRemove); } - toRemove = update(toRemove); - termDao.flushAndClear(); this.remove(toRemove); // calls pre and post remove LOG.debug("Removed term <{}>", toRemove.getUri()); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java index 89492549d..e066b17ae 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java @@ -56,6 +56,7 @@ public void apply(TermRemovalParams removalParams, TermRepositoryService reposit final Term subTerm = repositoryService.findRequired(subTermInfo.getUri()); repositoryService.remove(removalParams.withTerm(subTerm)); }); + term.getSubTerms().clear(); } } } @@ -97,6 +98,10 @@ public void apply(TermRemovalParams removalParams, TermRepositoryService reposit subTerm.splitExternalAndInternalParents(); repositoryService.update(subTerm); }); + + if (term.getSubTerms() != null) { + term.getSubTerms().clear(); // they were reconnected + } } /** diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java index cd97237aa..5976b8b00 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java @@ -87,7 +87,9 @@ void cascadeRemovesAllChildrenUsingSameRemovalParameters() { final Term secondChild = Generator.generateTermWithId(vocabulary.getUri()); secondChild.setUri(secondChildInfo.getUri()); - term.setSubTerms(Set.of(firstChildInfo, secondChildInfo)); + term.setSubTerms(new HashSet<>()); + term.getSubTerms().add(firstChildInfo); + term.getSubTerms().add(secondChildInfo); when(repositoryService.findRequired(firstChildInfo.getUri())).thenReturn(firstChild); when(repositoryService.findRequired(secondChildInfo.getUri())).thenReturn(secondChild); From cbd83026265bf3c72b8189cc7e5aec797f5e3c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 15 Sep 2026 10:39:20 +0200 Subject: [PATCH 23/30] [Ref] Simplify occurrence removal during term removal --- .../persistence/dao/TermOccurrenceDao.java | 17 ----------------- .../service/business/TermOccurrenceService.java | 8 -------- .../TermOccurrenceRepositoryService.java | 13 ------------- .../repository/TermRepositoryService.java | 10 +++------- .../repository/TermRepositoryServiceTest.java | 12 ------------ 5 files changed, 3 insertions(+), 57 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java index bd7713c31..0e7a1bf04 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermOccurrenceDao.java @@ -313,21 +313,4 @@ public void removeAllOrphans() { removeAll(a, URI.create(Vocabulary.s_c_term_occurrence)); }); } - - /** - * Checks whether there are any occurrences targeting the given asset. - * - * @param target asset which occurrences should be looked up - * @return true if any occurrence targeting the asset exist - */ - public boolean existsTargeting(Asset target) { - Objects.requireNonNull(target, "Target cannot be null"); - Objects.requireNonNull(target.getUri(), "Target URI cannot be null"); - return em.createNativeQuery("ASK {" + - "?x a ?type ;" + - "?hasTerm ?term . }", Boolean.class) - .setParameter("type", typeUri) - .setParameter("hasTerm", URI.create(Vocabulary.s_p_is_assignment_of_term)) - .setParameter("term", target.getUri()).getSingleResult(); - } } diff --git a/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java b/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java index 5c3994302..ea4107c49 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/business/TermOccurrenceService.java @@ -94,12 +94,4 @@ public interface TermOccurrenceService { * @param term Term whose occurrences to remove */ void removeAllOf(AbstractTerm term); - - /** - * Checks whether there are any occurrences targeting the given asset. - * - * @param target asset which occurrences should be looked up - * @return true if any occurrence targeting the asset exist - */ - boolean existsTargeting(Asset target); } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java index 2054b29bc..307b24ca4 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermOccurrenceRepositoryService.java @@ -175,17 +175,4 @@ public void removeAllOf(AbstractTerm term) { LOG.debug("Removing all occurrences of term {}.", term); termOccurrenceDao.removeAllOf(term); } - - /** - * Checks whether there are any occurrences targeting the given asset. - * - * @param target asset which occurrences should be looked up - * @return true if any occurrence targeting the asset exist - */ - @PreAuthorize("@termAuthorizationService.canRead(#target)") - @Transactional(readOnly = true) - @Override - public boolean existsTargeting(Asset target) { - return termOccurrenceDao.existsTargeting(target); - } } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index 5ff370a3c..1bf85e326 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -667,14 +667,10 @@ public void remove(TermRemovalParams removalParams) { removalParams.subTermsStrategy().apply(removalParams, this); termDao.flushAndClear(); - toRemove.consolidateParents(); - toRemove.getParentTerms().clear(); - - if (termOccurrenceService.existsTargeting(toRemove) && !removalParams.removeOccurrences()) { - throw new AssetRemovalException("Failed to remove term because of existing term occurrences"); + if (removalParams.removeOccurrences()) { + LOG.debug("Removing occurrences of term <{}>", toRemove.getUri()); + termOccurrenceService.removeAllOf(toRemove); } - LOG.debug("Removing occurrences of term <{}>", toRemove.getUri()); - termOccurrenceService.removeAllOf(toRemove); if (removalParams.removeRelationships()) { LOG.debug("Removing references to term <{}>", toRemove.getUri()); diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index 6382e3d47..f60673d58 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -546,18 +546,6 @@ private Term prepareTermWithSuggestedOccurrence(URI occurrenceUri) { return sut.findRequired(toRemove.getUri()); } - @Test - void removeWithParamsThrowsWhenTermHasSuggestedOccurrencesAndRemoveOccurrencesIsFalse() { - final URI occurrenceUri = Generator.generateUri(); - final Term toRemove = prepareTermWithSuggestedOccurrence(occurrenceUri); - - assertThrows(AssetRemovalException.class, () -> - sut.remove(new TermRemovalParams(toRemove, SubTermRemovalStrategy.FAIL, - false, false))); - assertNotNull(em.find(Term.class, toRemove.getUri())); - assertNotNull(em.find(TermDefinitionalOccurrence.class, occurrenceUri)); - } - @Test void removeWithParamsRemovesSuggestedOccurrencesWhenRemoveOccurrencesIsTrue() { final URI occurrenceUri = Generator.generateUri(); From 72f8e55849bae333b7365215cc289557b0a9e407 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 15 Sep 2026 11:01:58 +0200 Subject: [PATCH 24/30] [Enhancement] Evict parents of removed term from entity manager factory cache --- .../cvut/kbss/termit/persistence/dao/TermDao.java | 15 +++++++++++++++ .../service/repository/TermRepositoryService.java | 2 ++ 2 files changed, 17 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index b4564b7e0..714aa1c8e 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -27,6 +27,7 @@ import cz.cvut.kbss.jopa.vocabulary.SKOS; import cz.cvut.kbss.termit.asset.provenance.ModifiesData; import cz.cvut.kbss.termit.dto.Snapshot; +import cz.cvut.kbss.termit.dto.TermDescription; import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.dto.listing.FlatTermDto; import cz.cvut.kbss.termit.dto.listing.TermDto; @@ -1443,4 +1444,18 @@ public void removeReferencesTo(AbstractTerm toRemove) { throw new PersistenceException("Failed to remove references to term " + Utils.uriToString(toRemove.getUri()), e); } } + + /** + * Evict specified instances from the Jopa's Entity Manager Factory cache. + * + * @param terms terms to evict from the cache + */ + public void evictFromCache(Collection terms) { + if (terms == null || terms.isEmpty()) { + return; + } + terms.forEach(term -> { + em.getEntityManagerFactory().getCache().evict(TermDescription.class, term.getUri(), term.getVocabulary()); + }); + } } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index 1bf85e326..be0720706 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -750,6 +750,8 @@ protected void postRemove(@Nonnull Term instance) { v.removeRootTerm(instance); } termOccurrenceService.removeAllOf(instance); + instance.consolidateParents(); + termDao.evictFromCache(instance.getParentTerms()); } /** From 44b7658213985501000600accfb7c02e04e2012c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 16 Sep 2026 07:51:51 +0200 Subject: [PATCH 25/30] [Test] Add test ensuring that when a root term is removed, its children becomes root terms --- .../repository/TermRepositoryServiceTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index f60673d58..4a6f4a02f 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -611,6 +611,25 @@ void removeWithParamsRemovesTermRelationshipsWhenRemoveRelationshipsIsTrue() { assertNotNull(em.find(Term.class, related.getUri()), "The other term must not be removed"); } + @Test + void removeWithParamsPromotesChildToRootTermWhenItsParentRootTermIsRemoved() { + final Term root = Generator.generateTermWithId(vocabulary.getUri()); + final Term child = Generator.generateTermWithId(vocabulary.getUri()); + final Term childB = Generator.generateTermWithId(vocabulary.getUri()); + transactional(() -> sut.addRootTermToVocabulary(root, vocabulary)); + transactional(() -> sut.addChildTerm(child, root)); + transactional(() -> sut.addChildTerm(childB, root)); + + sut.remove(new TermRemovalParams(root, SubTermRemovalStrategy.RECONNECT, false, false)); + + final Vocabulary result = em.find(Vocabulary.class, vocabulary.getUri(), + descriptorFactory.vocabularyDescriptor(vocabulary)); + assertTrue(result.getRootTerms().contains(child.getUri()), + "Child of removed root term must become a root term"); + assertTrue(result.getRootTerms().contains(childB.getUri()), + "Second child of removed root term must become a root term"); + } + private void generateRelatedInverse(Term term, Term related, String property) { final Repository repo = em.unwrap(Repository.class); try (final RepositoryConnection conn = repo.getConnection()) { From 74c244c0faef13bcac2f12a485605d4c4c07b5ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 16 Sep 2026 08:23:13 +0200 Subject: [PATCH 26/30] [Docs] Fix method references in javadoc in TermRepositoryService --- .../kbss/termit/service/repository/TermRepositoryService.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index be0720706..1d6568e19 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -687,7 +687,7 @@ public void remove(TermRemovalParams removalParams) { * and there must be no references to the term. * * @param instance The instance to remove - * @see #remove(TermRemovalParams, Vocabulary) + * @see #remove(TermRemovalParams) * @see #forceRemove(Term) */ @Override @@ -761,7 +761,7 @@ protected void postRemove(@Nonnull Term instance) { * specified instance. * * @param instance Term to remove - * @see #remove(TermRemovalParams, Vocabulary) + * @see #remove(TermRemovalParams) * @see #remove(Term) */ @Transactional From 50adae1b03b8133cf3ab5a1c4c91051637aab4f7 Mon Sep 17 00:00:00 2001 From: lukaskabc Date: Thu, 17 Sep 2026 07:08:27 +0200 Subject: [PATCH 27/30] [Ref] Update javadocs for term removal params and its applier Co-authored-by: Martin Ledvinka --- .../service/repository/term_removal/TermRemovalParams.java | 2 +- .../repository/term_removal/TermRemovalParamsApplier.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java index 40017d732..ad63b7954 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java @@ -6,7 +6,7 @@ import java.util.Objects; /** - * Describes how should be a term removed + * Describes how a term should be removed * @param termToRemove The Term that will be removed * @param subTermsStrategy Strategy to use for sub-terms handling * @param removeOccurrences Whether {@link cz.cvut.kbss.termit.model.assignment.TermOccurrence term occurrences} should be removed. diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java index 5d27b7c8e..e34ccd33d 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java @@ -3,11 +3,11 @@ import cz.cvut.kbss.termit.service.repository.TermRepositoryService; /** - * Applier performing the given operation described by the parameters. + * Removes terms and executes any necessary related operations. */ public interface TermRemovalParamsApplier { /** - * Applies the operation described by the parameters. + * Removes a term, performing additional operations based on the specified parameters. * * @param removalParams Params describing how the term should be removed. * @param repositoryService Service for interacting with the term repository From 0d0340e4696ead54f00a6104c2b49b6e72cfe41a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 21 Sep 2026 07:22:09 +0200 Subject: [PATCH 28/30] [Ref] Replace RDF4J usage in TermDao#countReferences with JOPA native query and hardcode skos:ConceptScheme to query string instead of parameter binding. --- .../kbss/termit/persistence/dao/BaseDao.java | 21 ------- .../kbss/termit/persistence/dao/TermDao.java | 60 ++++++++----------- .../repository/TermRepositoryService.java | 2 - 3 files changed, 24 insertions(+), 59 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java index 0854e3092..8a00cec35 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java @@ -26,7 +26,6 @@ import cz.cvut.kbss.termit.model.util.EntityToOwlClassMapper; import cz.cvut.kbss.termit.model.util.HasIdentifier; import jakarta.annotation.Nonnull; -import org.eclipse.rdf4j.repository.RepositoryConnection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; @@ -166,24 +165,4 @@ protected Descriptor getDescriptor() { public void setApplicationEventPublisher(@Nonnull ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } - - /** - * Unwraps the supplied entity manager to {@link RepositoryConnection} within the current active transaction. - * - * @param entityManager the entity manager to unwrap - * @return open repository connection with active current transaction - * @implSpec The connection is managed by the {@link EntityManager} and must not be used with try-auto-close statement. - */ - public static RepositoryConnection unwrapToConnection(EntityManager entityManager) { - if (!entityManager.isOpen() || !entityManager.getTransaction().isActive()) { - throw new IllegalStateException("Entity manager is not open(" + entityManager.isOpen() + - ") or there is no active transaction (" + entityManager.getTransaction().isActive() + ")!"); - } - final RepositoryConnection connection = entityManager.unwrap(RepositoryConnection.class); - if (connection != null && connection.isActive()) { - return connection; - } - entityManager.createNativeQuery("ASK {}", Boolean.class).getSingleResult(); // force em to open a connection - return Objects.requireNonNull(entityManager.unwrap(RepositoryConnection.class), "Failed to acquire repository connection"); - } } diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java index 15d409b33..b8c1dcf53 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/TermDao.java @@ -41,7 +41,6 @@ import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.TermInfoWithParents; import cz.cvut.kbss.termit.model.Vocabulary; -import cz.cvut.kbss.termit.model.Vocabulary_; import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.persistence.context.DescriptorFactory; import cz.cvut.kbss.termit.persistence.context.VocabularyContextMapper; @@ -51,12 +50,10 @@ import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Utils; 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.util.Values; import org.eclipse.rdf4j.query.BindingSet; -import org.eclipse.rdf4j.query.Operation; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.RepositoryConnection; @@ -94,6 +91,9 @@ public class TermDao extends BaseAssetDao implements SnapshotProvider implements SnapshotProvider . FILTER (?relation NOT IN ( )) @@ -1330,7 +1330,6 @@ public boolean referencesToTermExist(AbstractTerm term) { try { return em.createNativeQuery("ASK " + REFERENCES_TO_TERM_WHERE_CLAUSE, Boolean.class) .setParameter("term", term.getUri()) - .setParameter("vocabulary", Vocabulary_.entityClassIRI) .setParameter("versionOfVocabulary", URI.create(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)) .getSingleResult(); } catch (RuntimeException e) { @@ -1351,15 +1350,12 @@ public Page findReferences(AbstractTerm term, Pageable pageable) { Objects.requireNonNull(pageable, "Pageable cannot be null"); try { - RepositoryConnection con = unwrapToConnection(em); - // On purpose not using auto-closable with try statement to prevent closing the connection here - // the connection is managed by Entity Manager - final long totalCount = countReferences(con, term); + final long totalCount = countReferences(term); if (totalCount == 0 || pageable.getOffset() >= totalCount) { return new PageImpl<>(List.of(), pageable, totalCount); } - final List statements = findReferences(con, term, pageable); + final List statements = findReferencesInternal(term, pageable); return new PageImpl<>(statements, pageable, totalCount); } catch (RuntimeException e) { throw new PersistenceException("Failed to find references to term " + Utils.uriToString(term.getUri()), e); @@ -1369,36 +1365,42 @@ public Page findReferences(AbstractTerm term, Pageable pageable) { /** * Counts the total amount of references to the specified term * - * @param con the repository connection * @param term the term to which references should be counted * @return the total number of statements referencing the term as object */ - private long countReferences(RepositoryConnection con, AbstractTerm term) { - final TupleQuery countQuery = con.prepareTupleQuery( - "SELECT (COUNT(*) AS ?count) " + REFERENCES_TO_TERM_WHERE_CLAUSE); - bindReferencesQueryParameters(countQuery, term); - countQuery.setIncludeInferred(false); - try (TupleQueryResult result = countQuery.evaluate()) { - final BindingSet bindings = result.next(); - return ((Literal) bindings.getValue("count")).longValue(); + private long countReferences(AbstractTerm term) { + try { + return em.createNativeQuery("SELECT (COUNT(*) AS ?count) " + REFERENCES_TO_TERM_WHERE_CLAUSE, Long.class) + .setParameter("term", term.getUri()) + .setParameter("versionOfVocabulary", cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary) + .getSingleResult(); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to count references to term " + Utils.uriToString(term.getUri()), e); } } /** * Finds a page contents of references to the specified term. * - * @param con the repository connection * @param term the term to which references should be found * @param pageable page spec * @return the list of statements referencing the term as object */ - private List findReferences(RepositoryConnection con, AbstractTerm term, Pageable pageable) { + private List findReferencesInternal(AbstractTerm term, Pageable pageable) { + // On purpose not using auto-closable with try statement to prevent closing the connection here + // the connection is managed by Entity Manager + final RepositoryConnection con = em.unwrap(RepositoryConnection.class); + // The connection is guaranteed to be open by first counting the total references count final TupleQuery query = con.prepareTupleQuery( "SELECT ?other ?relation ?term ?context " + REFERENCES_TO_TERM_WHERE_CLAUSE + " ORDER BY ?other ?relation ?context" + " OFFSET " + pageable.getOffset() + " LIMIT " + pageable.getPageSize()); - bindReferencesQueryParameters(query, term); + + query.setBinding("term", Values.iri(term.getUri().toString())); + query.setBinding("versionOfVocabulary", + Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)); + query.setIncludeInferred(false); final List statements = new ArrayList<>(pageable.getPageSize()); @@ -1416,19 +1418,6 @@ private List findReferences(RepositoryConnection con, AbstractTerm te return statements; } - /** - * Sets required query bindings for {@link #REFERENCES_TO_TERM_WHERE_CLAUSE}. - * - * @param query query operation - * @param term the term to which references should be found - */ - private void bindReferencesQueryParameters(Operation query, AbstractTerm term) { - query.setBinding("term", Values.iri(term.getUri().toString())); - query.setBinding("vocabulary", Values.iri(Vocabulary_.entityClassIRI.toString())); - query.setBinding("versionOfVocabulary", - Values.iri(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)); - } - /** * Removes all triples from vocabularies where the given term is references as object. * @@ -1446,7 +1435,6 @@ public void removeReferencesTo(AbstractTerm toRemove) { } """ + REFERENCES_TO_TERM_WHERE_CLAUSE) .setParameter("term", toRemove.getUri()) - .setParameter("vocabulary", Vocabulary_.entityClassIRI) .setParameter("versionOfVocabulary", URI.create(cz.cvut.kbss.termit.util.Vocabulary.s_c_version_of_vocabulary)) .executeUpdate(); } catch (RuntimeException e) { diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index 1d6568e19..e337f517b 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -205,8 +205,6 @@ private void pruneAndNormalizeTranslations(Term instance) { @Override protected void postUpdate(@Nonnull Term instance) { final Vocabulary vocabulary = vocabularyService.findRequired(instance.getVocabulary()); - // Jopa should always set at least empty collection - Objects.requireNonNull(vocabulary.getRootTerms(), "Vocabulary must have root terms collection"); if (instance.hasParentInSameVocabulary()) { vocabulary.removeRootTerm(instance); } else { From ca96be69e9d40c612f3ff06390bd6a61694ee551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 21 Sep 2026 07:37:56 +0200 Subject: [PATCH 29/30] [Ref] Remove unused logger from BaseDao --- src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java index 8a00cec35..93b7d2985 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/BaseDao.java @@ -26,8 +26,6 @@ import cz.cvut.kbss.termit.model.util.EntityToOwlClassMapper; import cz.cvut.kbss.termit.model.util.HasIdentifier; import jakarta.annotation.Nonnull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; @@ -42,7 +40,6 @@ */ public abstract class BaseDao implements GenericDao, ApplicationEventPublisherAware { - private static final Logger LOG = LoggerFactory.getLogger(BaseDao.class); protected final Class type; protected final URI typeUri; From 2e25f12fcc0746bd545464a656a11f68a066b7ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 21 Sep 2026 07:54:18 +0200 Subject: [PATCH 30/30] [Ref] Rename term_removal package to removal --- src/main/java/cz/cvut/kbss/termit/rest/TermController.java | 4 ++-- .../cz/cvut/kbss/termit/service/business/TermService.java | 2 +- .../kbss/termit/service/repository/TermRepositoryService.java | 2 +- .../{term_removal => removal}/SubTermRemovalStrategy.java | 2 +- .../{term_removal => removal}/TermRemovalParams.java | 2 +- .../{term_removal => removal}/TermRemovalParamsApplier.java | 2 +- .../java/cz/cvut/kbss/termit/rest/TermControllerTest.java | 2 +- .../termit/service/repository/TermRepositoryServiceTest.java | 4 ++-- .../{term_removal => removal}/SubTermRemovalStrategyTest.java | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) rename src/main/java/cz/cvut/kbss/termit/service/repository/{term_removal => removal}/SubTermRemovalStrategy.java (99%) rename src/main/java/cz/cvut/kbss/termit/service/repository/{term_removal => removal}/TermRemovalParams.java (96%) rename src/main/java/cz/cvut/kbss/termit/service/repository/{term_removal => removal}/TermRemovalParamsApplier.java (90%) rename src/test/java/cz/cvut/kbss/termit/service/repository/{term_removal => removal}/SubTermRemovalStrategyTest.java (99%) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java index 8463036a2..9ee1e2c42 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -38,8 +38,8 @@ import cz.cvut.kbss.termit.service.business.util.TermSelectionParams; import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportType; -import cz.cvut.kbss.termit.service.repository.term_removal.SubTermRemovalStrategy; -import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; +import cz.cvut.kbss.termit.service.repository.removal.SubTermRemovalStrategy; +import cz.cvut.kbss.termit.service.repository.removal.TermRemovalParams; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; diff --git a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java index f9230f07b..e5f8ae716 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/business/TermService.java @@ -49,7 +49,7 @@ import cz.cvut.kbss.termit.service.language.LanguageService; import cz.cvut.kbss.termit.service.repository.ChangeRecordService; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; -import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; +import cz.cvut.kbss.termit.service.repository.removal.TermRemovalParams; import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; import cz.cvut.kbss.termit.util.TypeAwareResource; import cz.cvut.kbss.termit.util.Utils; diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java index e337f517b..b5ac97340 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/TermRepositoryService.java @@ -37,7 +37,7 @@ import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.TermOccurrenceService; -import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; +import cz.cvut.kbss.termit.service.repository.removal.TermRemovalParams; import cz.cvut.kbss.termit.service.snapshot.SnapshotProvider; import cz.cvut.kbss.termit.service.term.AssertedInferredValueDifferentiator; import cz.cvut.kbss.termit.service.term.OrphanedInverseTermRelationshipRemover; diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java b/src/main/java/cz/cvut/kbss/termit/service/repository/removal/SubTermRemovalStrategy.java similarity index 99% rename from src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java rename to src/main/java/cz/cvut/kbss/termit/service/repository/removal/SubTermRemovalStrategy.java index e066b17ae..27f81250b 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategy.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/removal/SubTermRemovalStrategy.java @@ -1,4 +1,4 @@ -package cz.cvut.kbss.termit.service.repository.term_removal; +package cz.cvut.kbss.termit.service.repository.removal; import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.model.Term; diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java b/src/main/java/cz/cvut/kbss/termit/service/repository/removal/TermRemovalParams.java similarity index 96% rename from src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java rename to src/main/java/cz/cvut/kbss/termit/service/repository/removal/TermRemovalParams.java index ad63b7954..56b29aeca 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParams.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/removal/TermRemovalParams.java @@ -1,4 +1,4 @@ -package cz.cvut.kbss.termit.service.repository.term_removal; +package cz.cvut.kbss.termit.service.repository.removal; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.Vocabulary; diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java b/src/main/java/cz/cvut/kbss/termit/service/repository/removal/TermRemovalParamsApplier.java similarity index 90% rename from src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java rename to src/main/java/cz/cvut/kbss/termit/service/repository/removal/TermRemovalParamsApplier.java index e34ccd33d..1ddab8873 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/term_removal/TermRemovalParamsApplier.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/removal/TermRemovalParamsApplier.java @@ -1,4 +1,4 @@ -package cz.cvut.kbss.termit.service.repository.term_removal; +package cz.cvut.kbss.termit.service.repository.removal; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; diff --git a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java index 570b2924e..80ddd4d63 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java @@ -45,7 +45,7 @@ import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportFormat; import cz.cvut.kbss.termit.service.export.ExportType; -import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; +import cz.cvut.kbss.termit.service.repository.removal.TermRemovalParams; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java index 4a6f4a02f..0219535ca 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/TermRepositoryServiceTest.java @@ -39,8 +39,8 @@ import cz.cvut.kbss.termit.model.selector.TextPositionSelector; import cz.cvut.kbss.termit.persistence.context.DescriptorFactory; import cz.cvut.kbss.termit.service.BaseServiceTestRunner; -import cz.cvut.kbss.termit.service.repository.term_removal.SubTermRemovalStrategy; -import cz.cvut.kbss.termit.service.repository.term_removal.TermRemovalParams; +import cz.cvut.kbss.termit.service.repository.removal.SubTermRemovalStrategy; +import cz.cvut.kbss.termit.service.repository.removal.TermRemovalParams; import cz.cvut.kbss.termit.util.Constants; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.repository.Repository; diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/removal/SubTermRemovalStrategyTest.java similarity index 99% rename from src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java rename to src/test/java/cz/cvut/kbss/termit/service/repository/removal/SubTermRemovalStrategyTest.java index 5976b8b00..1dec01074 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/term_removal/SubTermRemovalStrategyTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/removal/SubTermRemovalStrategyTest.java @@ -1,4 +1,4 @@ -package cz.cvut.kbss.termit.service.repository.term_removal; +package cz.cvut.kbss.termit.service.repository.removal; import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.environment.Generator;