From d01287863cbe4612011b337edbdb09ede44a26e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 18 Sep 2026 12:48:19 +0200 Subject: [PATCH 01/27] [Ref] Add HasProperties interface for entities with JOPA's properties collection --- src/main/java/cz/cvut/kbss/termit/model/Term.java | 5 ++++- .../java/cz/cvut/kbss/termit/model/Vocabulary.java | 5 ++++- .../cvut/kbss/termit/model/util/HasProperties.java | 14 ++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 src/main/java/cz/cvut/kbss/termit/model/util/HasProperties.java diff --git a/src/main/java/cz/cvut/kbss/termit/model/Term.java b/src/main/java/cz/cvut/kbss/termit/model/Term.java index 310f0796b..54008d4cc 100644 --- a/src/main/java/cz/cvut/kbss/termit/model/Term.java +++ b/src/main/java/cz/cvut/kbss/termit/model/Term.java @@ -33,6 +33,7 @@ import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.model.assignment.TermDefinitionSource; import cz.cvut.kbss.termit.model.changetracking.Audited; +import cz.cvut.kbss.termit.model.util.HasProperties; import cz.cvut.kbss.termit.model.util.HasTypes; import cz.cvut.kbss.termit.model.util.SupportsSnapshots; import cz.cvut.kbss.termit.validation.Disjoint; @@ -49,7 +50,7 @@ @Disjoint({"parentTerms", "related"}) @Disjoint({"parentTerms", "relatedMatch"}) @Disjoint({"parentTerms", "exactMatchTerms"}) -public class Term extends AbstractTerm implements SupportsSnapshots, HasTypes { +public class Term extends AbstractTerm implements SupportsSnapshots, HasTypes, HasProperties { @OWLAnnotationProperty(iri = SKOS.ALT_LABEL) private Set altLabels; @@ -252,10 +253,12 @@ public void setDefinitionSource(TermDefinitionSource definitionSource) { this.definitionSource = definitionSource; } + @Override public Map> getProperties() { return properties; } + @Override public void setProperties(Map> properties) { this.properties = properties; } diff --git a/src/main/java/cz/cvut/kbss/termit/model/Vocabulary.java b/src/main/java/cz/cvut/kbss/termit/model/Vocabulary.java index ab87eea70..49bd02db5 100644 --- a/src/main/java/cz/cvut/kbss/termit/model/Vocabulary.java +++ b/src/main/java/cz/cvut/kbss/termit/model/Vocabulary.java @@ -33,6 +33,7 @@ import cz.cvut.kbss.termit.model.changetracking.Audited; import cz.cvut.kbss.termit.model.resource.Document; import cz.cvut.kbss.termit.model.util.AssetVisitor; +import cz.cvut.kbss.termit.model.util.HasProperties; import cz.cvut.kbss.termit.model.util.HasTypes; import cz.cvut.kbss.termit.model.util.SupportsSnapshots; import cz.cvut.kbss.termit.model.util.validation.HasPrimaryLanguage; @@ -53,7 +54,7 @@ @OWLClass(iri = SKOS.CONCEPT_SCHEME) @JsonLdAttributeOrder({"uri", "label", "description"}) public class Vocabulary extends Asset - implements HasTypes, SupportsSnapshots, HasPrimaryLanguage, Serializable { + implements HasTypes, HasProperties, SupportsSnapshots, HasPrimaryLanguage, Serializable { @ParticipationConstraints(nonEmpty = true) @OWLAnnotationProperty(iri = DC.Terms.TITLE) @@ -233,10 +234,12 @@ public void removeRootTerm(Term toRemove) { } } + @Override public Map> getProperties() { return properties; } + @Override public void setProperties(Map> properties) { this.properties = properties; } diff --git a/src/main/java/cz/cvut/kbss/termit/model/util/HasProperties.java b/src/main/java/cz/cvut/kbss/termit/model/util/HasProperties.java new file mode 100644 index 000000000..14522e0ef --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/model/util/HasProperties.java @@ -0,0 +1,14 @@ +package cz.cvut.kbss.termit.model.util; + +import java.util.Map; +import java.util.Set; + +/** + * Implemented by entities with {@link cz.cvut.kbss.jopa.model.annotations.Properties Properties} attribute. + */ +public interface HasProperties { + + Map> getProperties(); + + void setProperties(Map> properties); +} From ae68a9051647198794f319f7697a18288b2e79ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 18 Sep 2026 12:50:24 +0200 Subject: [PATCH 02/27] [Enhancement kbss-cvut/termit-ui#790] Implement update change record rollbacking service --- .../UpdateChangeRecordRollbackException.java | 14 ++ .../dao/changetracking/ChangeRollbackDao.java | 161 +++++++++++++++ .../changetracking/ChangeRollbackService.java | 183 ++++++++++++++++++ .../MetamodelRollbackValidator.java | 114 +++++++++++ 4 files changed, 472 insertions(+) create mode 100644 src/main/java/cz/cvut/kbss/termit/exception/UpdateChangeRecordRollbackException.java create mode 100644 src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java create mode 100644 src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java create mode 100644 src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java diff --git a/src/main/java/cz/cvut/kbss/termit/exception/UpdateChangeRecordRollbackException.java b/src/main/java/cz/cvut/kbss/termit/exception/UpdateChangeRecordRollbackException.java new file mode 100644 index 000000000..83972142f --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/exception/UpdateChangeRecordRollbackException.java @@ -0,0 +1,14 @@ +package cz.cvut.kbss.termit.exception; + +/** + * Indicates a failure during {@link cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord UpdateChangeRecord} + * rollback + */ +public class UpdateChangeRecordRollbackException extends TermItException { + public UpdateChangeRecordRollbackException() { + } + + public UpdateChangeRecordRollbackException(String message) { + super(message); + } +} diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java new file mode 100644 index 000000000..e6907de80 --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java @@ -0,0 +1,161 @@ +package cz.cvut.kbss.termit.persistence.dao.changetracking; + +import cz.cvut.kbss.jopa.model.EntityManager; +import cz.cvut.kbss.jopa.model.IRI; +import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.jopa.utils.EntityPropertiesUtils; +import cz.cvut.kbss.termit.exception.PersistenceException; +import cz.cvut.kbss.termit.exception.UpdateChangeRecordRollbackException; +import cz.cvut.kbss.termit.model.Asset; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.util.HasProperties; +import cz.cvut.kbss.termit.util.Utils; +import org.springframework.stereotype.Repository; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +@Repository +public class ChangeRollbackDao { + private final EntityManager em; + + public ChangeRollbackDao(EntityManager em) { + this.em = em; + } + + /** + * Checks whether an entity with the given identifier exists + * + * @param entityIdentifier the identifier of the entity + * @return {@code true} when the entity exists, {@code false} otherwise. + */ + public boolean entityExists(URI entityIdentifier) { + Objects.requireNonNull(entityIdentifier); + try { + return em.createNativeQuery("ASK { ?x a ?type }", Boolean.class) + .setParameter("x", entityIdentifier) + .getSingleResult(); + } catch (RuntimeException e) { + throw new PersistenceException("Failed check existence of entity " + + Utils.uriToString(entityIdentifier), e); + } + } + + /** + * Resolves the entity class from {@link cz.cvut.kbss.jopa.model.metamodel.Metamodel Metamodel} + * and tries to find attribute matching the changed attribute IRI. + * + * @param entityType the type of the changed entity + * @param record the change record + * @return The attribute if any attribute matching the IRI was found + */ + public Optional> resolveClassAttribute(Class entityType, UpdateChangeRecord record) { + final IRI changedAttributeIRI = IRI.create(record.getChangedAttribute().toString()); + return em.getMetamodel().entity(entityType).getAttributes().stream() + .filter(attribute -> changedAttributeIRI.equals(attribute.getIRI())) + .findAny(); + } + + /** + * Sets the given {@code originalValue} as the new value of the changed Java attribute. + * The required class of the value is inspected from the {@code classAttribute} and identifiers + * are mapped to the respective entity objects when required. + * + * @param originalValue the value to set + * @param changedAsset the changed entity + * @param classAttribute the changed Java attribute + */ + public void rollbackClassAttribute(Set originalValue, Asset changedAsset, Attribute classAttribute) { + final Set mappedOriginalValue = resolveEntityReferences(originalValue, classAttribute); + final Object newValue = getNewValue(mappedOriginalValue, classAttribute); + EntityPropertiesUtils.setFieldValue(classAttribute.getJavaField(), changedAsset, newValue); + } + + /** + * Maps the given values to their respective entity reference objects when the {@code classAttribute} + * holds entity objects. + * + * @param values Values to map + * @param classAttribute the attribute description + * @return Mapped {@code values} when the value type of the {@code classAttribute} is a Jopa entity type. + * Unchanged {@code values} otherwise. + */ + private Set resolveEntityReferences(Set values, Attribute classAttribute) { + final Class valueType = classAttribute.getValueJavaType(); + if (values == null || !isEntityClass(valueType)) { + return values; + } + + return values.stream().map(identifier -> em.getReference(valueType, identifier)) + .collect(Collectors.toSet()); + } + + /** + * Checks whether metamodel contains the given entity class. + * + * @param clazz Class to check + * @return {@code true} when the metamodel contains the given entity {@code class}, {@code false} otherwise. + */ + private boolean isEntityClass(Class clazz) { + try { + return em.getMetamodel().entity(clazz) != null; + } catch (IllegalArgumentException e) { + return false; + } + } + + /** + * Maps the given {@code originalValue} to a collection or a single value based on the {@code classAttribute}. + * + * @param originalValue the original value + * @param classAttribute the Java attribute + * @return a mapped collection when attribute is a collection, + * the first value from the {@code originalValue} when the attribute is singular, + * {@code null} otherwise + */ + private Object getNewValue(Set originalValue, Attribute classAttribute) { + if (classAttribute.isCollection()) { + Class collectionClass = classAttribute.getJavaType(); + if (List.class.equals(collectionClass)) { + return new ArrayList<>(originalValue); + } + if (Collection.class.equals(collectionClass) || Set.class.equals(collectionClass)) { + return originalValue; + } + throw new UpdateChangeRecordRollbackException("Unsupported attribute type: " + collectionClass.getName()); + } + + if (originalValue == null || originalValue.isEmpty()) { + return null; + } else { + assert originalValue.size() == 1; + return originalValue.iterator().next(); + } + } + + public void rollbackNativeProperty(Set originalValue, Asset changedAsset, URI changedAttributeUri) { + if (originalValue != null && !originalValue.isEmpty()) { + getProperties(changedAsset).put(changedAttributeUri.toString(), originalValue); + } else { + getProperties(changedAsset).remove(changedAttributeUri.toString()); + } + } + + private Map> getProperties(Asset asset) { + if (asset instanceof HasProperties withProperties) { + if (withProperties.getProperties() == null) { + withProperties.setProperties(new HashMap<>()); + } + return withProperties.getProperties(); + } + throw new IllegalArgumentException("Asset does not implement HasProperties interface! " + Utils.uriToString(asset.getUri())); + } +} diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java new file mode 100644 index 000000000..d9fb9cfde --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -0,0 +1,183 @@ +package cz.cvut.kbss.termit.service.changetracking; + +import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.termit.exception.UpdateChangeRecordRollbackException; +import cz.cvut.kbss.termit.model.Asset; +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.util.HasProperties; +import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import cz.cvut.kbss.termit.service.repository.TermRepositoryService; +import cz.cvut.kbss.termit.service.repository.VocabularyRepositoryService; +import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; +import cz.cvut.kbss.termit.service.security.authorization.VocabularyAuthorizationService; +import cz.cvut.kbss.termit.util.Utils; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +/** + * Service capable of performing rollback of {@link UpdateChangeRecord} + */ +@Service +public class ChangeRollbackService { + private final MetamodelRollbackValidator rollbackValidator; + private final ChangeRollbackDao rollbackDao; + private final TermRepositoryService termService; + private final VocabularyRepositoryService vocabularyService; + private final TermAuthorizationService termAuthorizationService; + private final VocabularyAuthorizationService vocabularyAuthorizationService; + + public ChangeRollbackService(MetamodelRollbackValidator rollbackValidator, + ChangeRollbackDao rollbackDao, + TermRepositoryService termService, + VocabularyRepositoryService vocabularyService, + TermAuthorizationService termAuthorizationService, + VocabularyAuthorizationService vocabularyAuthorizationService) { + this.rollbackValidator = rollbackValidator; + this.rollbackDao = rollbackDao; + this.termService = termService; + this.vocabularyService = vocabularyService; + this.termAuthorizationService = termAuthorizationService; + this.vocabularyAuthorizationService = vocabularyAuthorizationService; + } + + /** + * Checks whether the {@link UpdateChangeRecord} can be rolled back by the current user. + * + * @param record the change record to check + * @return {@code true} when the change record can be rolled back and the current user is authorized to do so, + * {@code false} otherwise. + */ + @Transactional + public boolean canRollback(UpdateChangeRecord record) { + final Asset changedObject = resolveChangedAsset(record); + if (changedObject == null) { + return false; // unknown entity class + } + return canRollback(record, changedObject) && isModificationAuthorized(changedObject); + } + + /** + * Checks whether the {@link UpdateChangeRecord} of the {@code changedObject} can be rolled back. + * + * @param record the change record + * @param changedObject the changed entity + * @return {@code true} when the change record can be rolled back, {@code false} otherwise. + */ + private boolean canRollback(UpdateChangeRecord record, Asset changedObject) { + final Class> entityClass = resolveEntityClass(changedObject); + if (!HasProperties.class.isAssignableFrom(entityClass)) { + return false; + } + return rollbackValidator.canRollback(record, entityClass); + } + + /** + * Rolls back the change by setting the changed attribute to the original value. + * + * @param record the record to rollback + */ + @Transactional + public void rollback(UpdateChangeRecord record) { + final Asset changedAsset = resolveChangedAssetRequired(record); + + if (!canRollback(record, changedAsset)) { + throw new UpdateChangeRecordRollbackException("Update change record cannot be rolled back"); + } + + ensureModificationAuthorized(changedAsset); + doRollback(record, changedAsset); + } + + /** + * Resolves the Java field of the entity class and updates its value. + * When the attribute is not resolved to a specific Java field, the attribute is updated via + * {@link cz.cvut.kbss.jopa.model.annotations.Properties @Properties} field. + * + * @param record the record to rollback + * @param changedAsset the changed entity + */ + private void doRollback(UpdateChangeRecord record, Asset changedAsset) { + final Class> entityClass = resolveEntityClass(changedAsset); + final Attribute classAttribute = rollbackDao.resolveClassAttribute(entityClass, record).orElse(null); + if (classAttribute != null) { + rollbackDao.rollbackClassAttribute(record.getOriginalValue(), changedAsset, classAttribute); + } else { + rollbackDao.rollbackNativeProperty(record.getOriginalValue(), changedAsset, record.getChangedAttribute()); + } + updateChangedAsset(changedAsset); + } + + /** + * Resolves instances of {@link Term}, {@link Vocabulary} and their subclasses to their respective main entity classes. + * + * @param asset the entity whose main class should be resolved + * @return the resolved main entity class + * @throws UpdateChangeRecordRollbackException when the {@code asset} is not instance of supported entity class. + */ + private Class> resolveEntityClass(Asset asset) { + if (asset instanceof Term) { + return Term.class; + } + if (asset instanceof Vocabulary) { + return Vocabulary.class; + } + throw unsupportedAssetType(asset); + } + + private Asset resolveChangedAssetRequired(UpdateChangeRecord record) { + final Asset changedAsset = resolveChangedAsset(record); + if (changedAsset == null) { + throw new UpdateChangeRecordRollbackException("Rollback not supported for asset " + + Utils.uriToString(record.getChangedEntity())); + } + return changedAsset; + } + + private Asset resolveChangedAsset(UpdateChangeRecord record) { + Optional vocabulary = vocabularyService.find(record.getChangedEntity()); + if (vocabulary.isPresent()) { + return vocabulary.get(); + } + Optional term = termService.find(record.getChangedEntity()); + if (term.isPresent()) { + return term.get(); + } + return null; + } + + private void ensureModificationAuthorized(Asset asset) { + if (!isModificationAuthorized(asset)) { + throw new AccessDeniedException("Not authorized to roll back changes to the asset."); + } + } + + private boolean isModificationAuthorized(Asset asset) { + if (asset instanceof Term term) { + return termAuthorizationService.canModify(term); + } + if (asset instanceof Vocabulary vocabulary) { + return vocabularyAuthorizationService.canModify(vocabulary); + } + return false; + } + + private void updateChangedAsset(Asset asset) { + if (asset instanceof Term term) { + termService.update(term); + } else if (asset instanceof Vocabulary vocabulary) { + vocabularyService.update(vocabulary); + } else { + throw unsupportedAssetType(asset); + } + } + + private UpdateChangeRecordRollbackException unsupportedAssetType(Asset asset) { + return new UpdateChangeRecordRollbackException("The type of Asset " + Utils.uriToString(asset.getUri()) + + " is not supported"); + } +} diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java new file mode 100644 index 000000000..d96bde7f7 --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java @@ -0,0 +1,114 @@ +package cz.cvut.kbss.termit.service.changetracking; + +import cz.cvut.kbss.jopa.model.MultilingualString; +import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.net.URI; +import java.time.temporal.Temporal; +import java.time.temporal.TemporalAmount; +import java.util.Collection; +import java.util.Date; +import java.util.Objects; +import java.util.UUID; +import java.util.stream.Stream; + +/** + * Validator supporting the rollback validation of change records of {@link Term} and {@link Vocabulary}. + */ +@Component +public class MetamodelRollbackValidator { + private static final Class[] PRIMITIVE_CLASSES = { + // not including URI - can represent a reference to another entity + Number.class, + String.class, // TermIt is not using Strings as identifiers + Boolean.class, + Temporal.class, + Date.class, + TemporalAmount.class, + UUID.class, + MultilingualString.class + }; + + private final ChangeRollbackDao changeRollbackDao; + + public MetamodelRollbackValidator(ChangeRollbackDao changeRollbackDao) { + this.changeRollbackDao = changeRollbackDao; + } + + /** + * Checks whether the record can be rolled back. + * + * @param record the change record to check + * @return {@code true} if the change record is associated with existing {@link Term} or {@link Vocabulary} + * and can be rolled back, {@code false} otherwise. + */ + @Transactional(readOnly = true) + public boolean canRollback(UpdateChangeRecord record, Class entityClass) { + if (allValuesArePrimitives(record)) { + return true; + } + + return canRollbackEntityClass(entityClass, record); + } + + private boolean allValuesArePrimitives(UpdateChangeRecord record) { + return Stream.of(record.getOriginalValue(), record.getNewValue()) + .filter(Objects::nonNull) + .flatMap(Collection::stream) + .map(Object::getClass) + .allMatch(MetamodelRollbackValidator::isPrimitive); + } + + private static boolean isPrimitive(Class clazz) { + if (clazz.isPrimitive()) { + return true; + } + for (Class primitiveClass : PRIMITIVE_CLASSES) { + if (primitiveClass.isAssignableFrom(clazz)) { + return true; + } + } + return false; + } + + private boolean canRollbackEntityClass(Class entityClass, UpdateChangeRecord record) { + return changeRollbackDao.resolveClassAttribute(entityClass, record) + .map(Attribute::getValueJavaType) + .map(clazz -> canRollbackAttributeWithType(clazz, record)) + .orElse(false); + } + + private boolean canRollbackAttributeWithType(Class attributeValueClass, UpdateChangeRecord record) { + if (isPrimitive(attributeValueClass)) { + return true; + } + if (record.getOriginalValue() == null) { + return true; + } + for (Object originalValue : record.getOriginalValue()) { + // assumes that every URI field must be valid entity reference + if (originalValue instanceof URI entityIdentifier && !canRollbackToEntityReference(entityIdentifier)) { + return false; + } + } + return true; + } + + /** + * + * @param referencedEntity the identifier of entity + * @return {@code true} when the change record can safely be rolled back, {@code false} otherwise + */ + private boolean canRollbackToEntityReference(URI referencedEntity) { + if (referencedEntity == null) { + return true; + } + return changeRollbackDao.entityExists(referencedEntity); + } +} From 6de470ef23b8666865707c658c735c2d5d007b21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Mon, 21 Sep 2026 11:19:05 +0200 Subject: [PATCH 03/27] [Test kbss-cvut/termit-ui#790] Implement tests for change rollback dao --- .../changetracking/ChangeRollbackDaoTest.java | 212 ++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDaoTest.java diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDaoTest.java new file mode 100644 index 000000000..bb4c0a565 --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDaoTest.java @@ -0,0 +1,212 @@ +package cz.cvut.kbss.termit.persistence.dao.changetracking; + +import cz.cvut.kbss.jopa.model.EntityManager; +import cz.cvut.kbss.jopa.model.MultilingualString; +import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.termit.dto.TermInfo; +import cz.cvut.kbss.termit.dto.VocabularyDto; +import cz.cvut.kbss.termit.environment.Generator; +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Term_; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.Vocabulary_; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.resource.Document; +import cz.cvut.kbss.termit.model.util.HasIdentifier; +import cz.cvut.kbss.termit.persistence.dao.BaseDaoTestRunner; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import java.net.URI; +import java.util.HashMap; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ChangeRollbackDaoTest extends BaseDaoTestRunner { + + @Autowired + private EntityManager em; + + @Autowired + private ChangeRollbackDao sut; + + @Test + void entityExistsReturnsTrueForExistingEntity() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + transactional(() -> em.persist(vocabulary)); + + assertTrue(sut.entityExists(vocabulary.getUri())); + } + + @Test + void entityExistsReturnsFalseForNonExistingEntity() { + assertFalse(sut.entityExists(Generator.generateUri())); + } + + @Test + void resolveClassAttributeFindsMappedAttributeByIdentifier() { + final UpdateChangeRecord record = recordForAttribute(Term_.definitionPropertyIRI.toURI()); + + final Optional> result = sut.resolveClassAttribute(Term.class, record); + + assertTrue(result.isPresent()); + assertEquals(Term_.definition, result.get()); + } + + @Test + void resolveClassAttributeReturnsEmptyForUnknownProperty() { + final UpdateChangeRecord record = recordForAttribute(Generator.generateUri()); + assertTrue(sut.resolveClassAttribute(Term.class, record).isEmpty()); + } + + @Test + void resolveClassAttributeThrowsForUnknownEntityClass() { + final UpdateChangeRecord record = recordForAttribute(Term_.labelPropertyIRI.toURI()); + assertThrows(IllegalArgumentException.class, () -> sut.resolveClassAttribute(VocabularyDto.class, record)); + } + + @Test + void rollbackClassAttributeRestoresSingularValue() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + vocabulary.setPrimaryLanguage("en"); + final String originalLanguage = "cs"; + + sut.rollbackClassAttribute(Set.of(originalLanguage), vocabulary, Vocabulary_.primaryLanguage); + + assertEquals(originalLanguage, vocabulary.getPrimaryLanguage()); + } + + @Test + void rollbackClassAttributeRestoresMultilingualValue() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + vocabulary.setLabel(MultilingualString.create("Slovník", "cs")); + final MultilingualString originalLabel = MultilingualString.create("Vocabulary", "en"); + + sut.rollbackClassAttribute(Set.of(originalLabel), vocabulary, Vocabulary_.label); + + assertEquals(originalLabel, vocabulary.getLabel()); + } + + @Test + void rollbackClassAttributeSetsSingularValueToNullWhenOriginalValueWasNull() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + + sut.rollbackClassAttribute(null, vocabulary, Vocabulary_.label); + + assertNull(vocabulary.getLabel()); + } + + @Test + void rollbackClassAttributeSetsSingularValueToNullWhenOriginalValueWasEmpty() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + + sut.rollbackClassAttribute(Set.of(), vocabulary, Vocabulary_.label); + + assertNull(vocabulary.getLabel()); + } + + @Test + void rollbackClassAttributeRestoresSetCollectionValue() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + vocabulary.setImportedVocabularies(Set.of(Generator.generateUri())); + final Set originalImported = Set.of(Generator.generateUri()); + + sut.rollbackClassAttribute(originalImported, vocabulary, Vocabulary_.importedVocabularies); + + assertEquals(originalImported, vocabulary.getImportedVocabularies()); + } + + @Test + void rollbackClassAttributeResolvesEntityReferences() { + final Term term = Generator.generateTermWithId(); + term.setParentTerms(Set.of(Generator.generateTermInfoWithId())); + + final Set originalParents = Set.of(Generator.generateTermInfoWithId(), Generator.generateTermInfoWithId()); + transactional(() -> { + originalParents.forEach(em::persist); + }); + + final Set parentIdentifiers = originalParents.stream().map(HasIdentifier::getUri).collect(Collectors.toUnmodifiableSet()); + + sut.rollbackClassAttribute(parentIdentifiers, term, Term_.parentTerms); + + assertEquals(originalParents, term.getParentTerms()); + } + + @Test + void rollbackNativePropertyRestoresSingleOriginalValue() { + final Term term = Generator.generateTermWithId(); + final URI property = Generator.generateUri(); + + term.setProperties(new HashMap<>()); + term.getProperties().put(property.toString(), Set.of("custom term property")); + + final Set originalValues = Set.of("original"); + + sut.rollbackNativeProperty(originalValues, term, property); + + assertEquals(originalValues, term.getProperties().get(property.toString())); + } + + @Test + void rollbackNativePropertyDoesNotModifyOtherNativeProperties() { + final Term term = Generator.generateTermWithId(); + final URI anotherProperty = Generator.generateUri(); + final Set anotherPropertyValues = Set.of(new Object(), new Object()); + term.setProperties(new HashMap<>()); + term.getProperties().put(anotherProperty.toString(), anotherPropertyValues); + + final URI property = Generator.generateUri(); + final Set originalValues = Set.of("original"); + + sut.rollbackNativeProperty(originalValues, term, property); + + assertEquals(originalValues, term.getProperties().get(property.toString())); + assertEquals(anotherPropertyValues, term.getProperties().get(anotherProperty.toString())); + } + + @Test + void rollbackNativePropertyRemovesPropertyThatDidNotOriginallyExist() { + final Term term = Generator.generateTermWithId(); + final URI property = Generator.generateUri(); + term.setProperties(new HashMap<>()); + term.getProperties().put(property.toString(), Set.of("added")); + + sut.rollbackNativeProperty(null, term, property); + + assertFalse(term.getProperties().containsKey(property.toString())); + } + + @Test + void rollbackNativePropertyRemovesPropertyWhenOriginalValueIsEmptySet() { + final Term term = Generator.generateTermWithId(); + final URI property = Generator.generateUri(); + term.setProperties(new HashMap<>()); + term.getProperties().put(property.toString(), Set.of("added")); + + sut.rollbackNativeProperty(Set.of(), term, property); + + assertFalse(term.getProperties().containsKey(property.toString())); + } + + @Test + void rollbackNativePropertyRejectsAssetWithoutProperties() { + final Document document = Generator.generateDocumentWithId(); + + assertThrows(IllegalArgumentException.class, + () -> sut.rollbackNativeProperty(Set.of("original"), document, Generator.generateUri())); + } + + private static UpdateChangeRecord recordForAttribute(URI changedAttribute) { + final UpdateChangeRecord record = new UpdateChangeRecord(); + record.setChangedAttribute(changedAttribute); + return record; + } +} From 0048e353705cc1aa146f33598e809589756c0996 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 09:17:19 +0200 Subject: [PATCH 04/27] [Enhancement kbss-cvut/termit-ui#790] Add MultilingualString and Void types to primitives in MetamodelRollbackValidator and fix ChangeRollbackDao reporting entity existance from inferred statements --- .../persistence/dao/changetracking/ChangeRollbackDao.java | 2 ++ .../service/changetracking/MetamodelRollbackValidator.java | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java index e6907de80..1c4fb5408 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java @@ -3,6 +3,7 @@ import cz.cvut.kbss.jopa.model.EntityManager; import cz.cvut.kbss.jopa.model.IRI; import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.jopa.query.QueryHints; import cz.cvut.kbss.jopa.utils.EntityPropertiesUtils; import cz.cvut.kbss.termit.exception.PersistenceException; import cz.cvut.kbss.termit.exception.UpdateChangeRecordRollbackException; @@ -42,6 +43,7 @@ public boolean entityExists(URI entityIdentifier) { try { return em.createNativeQuery("ASK { ?x a ?type }", Boolean.class) .setParameter("x", entityIdentifier) + .setHint(QueryHints.DISABLE_INFERENCE, "true") .getSingleResult(); } catch (RuntimeException e) { throw new PersistenceException("Failed check existence of entity " + diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java index d96bde7f7..8cefbbcf5 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java @@ -32,7 +32,9 @@ public class MetamodelRollbackValidator { Date.class, TemporalAmount.class, UUID.class, - MultilingualString.class + MultilingualString.class, + Void.TYPE, + Void.class }; private final ChangeRollbackDao changeRollbackDao; From 35ed4fddb6b992d7d635170665e2570c3a48a5d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 09:22:26 +0200 Subject: [PATCH 05/27] [Test kbss-cvut/termit-ui#790] Implement tests for metamodel rollback validator --- .../MetamodelRollbackValidatorTest.java | 153 ++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 src/test/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidatorTest.java diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidatorTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidatorTest.java new file mode 100644 index 000000000..6fa5184da --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidatorTest.java @@ -0,0 +1,153 @@ +package cz.cvut.kbss.termit.service.changetracking; + +import cz.cvut.kbss.jopa.model.MultilingualString; +import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.termit.environment.Generator; +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.net.URI; +import java.time.Instant; +import java.util.Date; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class MetamodelRollbackValidatorTest { + + @Mock + private ChangeRollbackDao changeRollbackDao; + + @Mock + private Attribute attribute; + + @InjectMocks + private MetamodelRollbackValidator sut; + + private static Stream> primitiveOriginalValues() { + return Stream.of( + Set.of("original", "another original"), + Set.of(1, 2), + Set.of(true, false), + Set.of(MultilingualString.create("str value", "en")), + Set.of(new Date()), + Set.of(Instant.now(), Instant.now().plusSeconds(100)) + ); + } + + @ParameterizedTest + @MethodSource("primitiveOriginalValues") + void canRollbackReturnsTrueWhenAllChangedValuesArePrimitive(Set originalValues) { + final UpdateChangeRecord record = recordForChange(originalValues, Set.of("updated", "another updated")); + + assertTrue(sut.canRollback(record, Term.class)); + verifyNoInteractions(changeRollbackDao); + } + + @Test + void canRollbackSupportsPrimitiveValueAddedToPreviouslyNullAttribute() { + final UpdateChangeRecord record = recordForChange(null, Set.of("added")); + + assertTrue(sut.canRollback(record, Term.class)); + verifyNoInteractions(changeRollbackDao); + } + + @Test + void canRollbackSupportsPrimitiveValueAddedToPreviouslyEmptyAttribute() { + final UpdateChangeRecord record = recordForChange(Set.of(), Set.of("added")); + + assertTrue(sut.canRollback(record, Term.class)); + verifyNoInteractions(changeRollbackDao); + } + + @Test + void canRollbackReturnsFalseWhenChangedAttributeCannotBeResolved() { + final UpdateChangeRecord record = recordForChange(Set.of(Generator.generateUri()), Set.of(Generator.generateUri())); + when(changeRollbackDao.resolveClassAttribute(Term.class, record)).thenReturn(Optional.empty()); + + assertFalse(sut.canRollback(record, Term.class)); + } + + @Test + void canRollbackReturnsTrueWhenAllOriginalEntityReferencesExist() { + final URI firstReference = Generator.generateUri(); + final URI secondReference = Generator.generateUri(); + final UpdateChangeRecord record = recordForChange(Set.of(firstReference, secondReference), + Set.of(Generator.generateUri())); + mockReferenceAttribute(record); + when(changeRollbackDao.entityExists(firstReference)).thenReturn(true); + when(changeRollbackDao.entityExists(secondReference)).thenReturn(true); + + assertTrue(sut.canRollback(record, Term.class)); + } + + @Test + void canRollbackReturnsFalseWhenOriginalEntityReferenceNoLongerExists() { + final URI missingReference = Generator.generateUri(); + final URI existingReference = Generator.generateUri(); + final UpdateChangeRecord record = recordForChange(Set.of(existingReference, missingReference), Set.of(Generator.generateUri())); + mockReferenceAttribute(record); + lenient().when(changeRollbackDao.entityExists(existingReference)).thenReturn(true); + when(changeRollbackDao.entityExists(missingReference)).thenReturn(false); + + assertFalse(sut.canRollback(record, Term.class)); + } + + @Test + void canRollbackRestoresRemovedMultilingualLabel() { + final UpdateChangeRecord record = recordForChange(Set.of(MultilingualString.create("Original", "en")), Set.of()); + + assertTrue(sut.canRollback(record, Term.class)); + verifyNoInteractions(changeRollbackDao); + } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void canRollbackChecksForEntityReferenceExistence(boolean entityExists) { + final URI reference = Generator.generateUri(); + final URI existingReference = Generator.generateUri(); + final UpdateChangeRecord record = recordForChange(Set.of(existingReference, reference), null); + + doReturn(Optional.of(attribute)).when(changeRollbackDao).resolveClassAttribute(Vocabulary.class, record); + doReturn(URI.class).when(attribute).getValueJavaType(); + + lenient().when(changeRollbackDao.entityExists(existingReference)).thenReturn(true); + when(changeRollbackDao.entityExists(reference)).thenReturn(entityExists); + + assertEquals(entityExists, sut.canRollback(record, Vocabulary.class)); + verify(changeRollbackDao).entityExists(reference); + } + + private void mockReferenceAttribute(UpdateChangeRecord record) { + doReturn(Optional.of(attribute)).when(changeRollbackDao).resolveClassAttribute(Term.class, record); + doReturn(URI.class).when(attribute).getValueJavaType(); + } + + private static UpdateChangeRecord recordForChange(Set originalValue, Set newValue) { + final UpdateChangeRecord record = new UpdateChangeRecord(); + record.setChangedAttribute(Generator.generateUri()); + record.setOriginalValue(originalValue); + record.setNewValue(newValue); + return record; + } +} From 134a5bc6b992459bc645df57bd04d3ea819f0544 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 12:33:36 +0200 Subject: [PATCH 06/27] [Enhancement kbss-cvut/termit-ui#790] Implement support for rollbacking custom attributes referencing terms and possibly vocabularies --- .../changetracking/ChangeRollbackService.java | 4 +- ...kValidator.java => RollbackValidator.java} | 61 +++++++++++++++---- .../repository/DataRepositoryService.java | 12 ++++ ...orTest.java => RollbackValidatorTest.java} | 4 +- 4 files changed, 66 insertions(+), 15 deletions(-) rename src/main/java/cz/cvut/kbss/termit/service/changetracking/{MetamodelRollbackValidator.java => RollbackValidator.java} (56%) rename src/test/java/cz/cvut/kbss/termit/service/changetracking/{MetamodelRollbackValidatorTest.java => RollbackValidatorTest.java} (98%) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index d9fb9cfde..b30502329 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -24,14 +24,14 @@ */ @Service public class ChangeRollbackService { - private final MetamodelRollbackValidator rollbackValidator; + private final RollbackValidator rollbackValidator; private final ChangeRollbackDao rollbackDao; private final TermRepositoryService termService; private final VocabularyRepositoryService vocabularyService; private final TermAuthorizationService termAuthorizationService; private final VocabularyAuthorizationService vocabularyAuthorizationService; - public ChangeRollbackService(MetamodelRollbackValidator rollbackValidator, + public ChangeRollbackService(RollbackValidator rollbackValidator, ChangeRollbackDao rollbackDao, TermRepositoryService termService, VocabularyRepositoryService vocabularyService, diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java similarity index 56% rename from src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java rename to src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java index 8cefbbcf5..fa9e69105 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidator.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java @@ -2,10 +2,14 @@ import cz.cvut.kbss.jopa.model.MultilingualString; import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.jopa.vocabulary.RDFS; +import cz.cvut.kbss.jopa.vocabulary.SKOS; +import cz.cvut.kbss.termit.model.CustomAttribute; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import cz.cvut.kbss.termit.service.repository.DataRepositoryService; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @@ -22,7 +26,7 @@ * Validator supporting the rollback validation of change records of {@link Term} and {@link Vocabulary}. */ @Component -public class MetamodelRollbackValidator { +public class RollbackValidator { private static final Class[] PRIMITIVE_CLASSES = { // not including URI - can represent a reference to another entity Number.class, @@ -38,9 +42,11 @@ public class MetamodelRollbackValidator { }; private final ChangeRollbackDao changeRollbackDao; + private final DataRepositoryService dataRepositoryService; - public MetamodelRollbackValidator(ChangeRollbackDao changeRollbackDao) { + public RollbackValidator(ChangeRollbackDao changeRollbackDao, DataRepositoryService dataRepositoryService) { this.changeRollbackDao = changeRollbackDao; + this.dataRepositoryService = dataRepositoryService; } /** @@ -56,7 +62,17 @@ public boolean canRollback(UpdateChangeRecord record, Class entityClass) { return true; } - return canRollbackEntityClass(entityClass, record); + final Class javaFieldValueClass = changeRollbackDao.resolveClassAttribute(entityClass, record) + .map(Attribute::getValueJavaType) + .orElse(null); + + // Java Entity class has field matching the changed attribute + if (javaFieldValueClass != null) { + return canRollbackAttributeWithType(javaFieldValueClass, record); + } + + // The value change does not match any Java entity class field + return canRollbackNativeProperty(record); } private boolean allValuesArePrimitives(UpdateChangeRecord record) { @@ -64,7 +80,7 @@ private boolean allValuesArePrimitives(UpdateChangeRecord record) { .filter(Objects::nonNull) .flatMap(Collection::stream) .map(Object::getClass) - .allMatch(MetamodelRollbackValidator::isPrimitive); + .allMatch(RollbackValidator::isPrimitive); } private static boolean isPrimitive(Class clazz) { @@ -79,13 +95,6 @@ private static boolean isPrimitive(Class clazz) { return false; } - private boolean canRollbackEntityClass(Class entityClass, UpdateChangeRecord record) { - return changeRollbackDao.resolveClassAttribute(entityClass, record) - .map(Attribute::getValueJavaType) - .map(clazz -> canRollbackAttributeWithType(clazz, record)) - .orElse(false); - } - private boolean canRollbackAttributeWithType(Class attributeValueClass, UpdateChangeRecord record) { if (isPrimitive(attributeValueClass)) { return true; @@ -103,6 +112,7 @@ private boolean canRollbackAttributeWithType(Class attributeValueClass, Updat } /** + * Checks that the given entity has asserted type in the repository (the entity exists). * * @param referencedEntity the identifier of entity * @return {@code true} when the change record can safely be rolled back, {@code false} otherwise @@ -113,4 +123,33 @@ private boolean canRollbackToEntityReference(URI referencedEntity) { } return changeRollbackDao.entityExists(referencedEntity); } + + /** + * Checks whether a matching custom attribute exists for the changed attribute and permits rollback based on its range. + * + * @param record the change record to check + * @return {@code true} if the custom attribute exists and its range permits rollback, {@code false} otherwise + */ + private boolean canRollbackNativeProperty(UpdateChangeRecord record) { + return dataRepositoryService.findCustomAttribute(record.getChangedAttribute()) + .map(attr -> canRollbackCustomAttributeWithReferenceRange(attr, record)) + .orElse(false); // custom attribute does not exist + } + + /** + * Checks whether the record can be rolled back based on the custom attribute range. + * + * @param attribute the custom attribute changed by the record + * @param record the change record to check + * @return {@code true} if the range permits rollback, including the validity of references where required, + * {@code false} otherwise + */ + private boolean canRollbackCustomAttributeWithReferenceRange(CustomAttribute attribute, UpdateChangeRecord record) { + return switch (attribute.getRange().toString()) { + case RDFS.RESOURCE -> true; + case SKOS.CONCEPT -> canRollbackAttributeWithType(Term.class, record); + case SKOS.CONCEPT_SCHEME -> canRollbackAttributeWithType(Vocabulary.class, record); + default -> false; + }; + } } diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java index 4342a6c0c..7e95ba8ed 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/DataRepositoryService.java @@ -98,6 +98,18 @@ public List findCustomAttributesByDomainAndRange(@Nonnull URI d CustomAttributeSpecifications.hasRange(range))); } + /** + * Finds a custom attribute with the specified identifier. + * + * @param attributeUri Attribute identifier + * @return Matching custom attribute or empty if no such attribute exists + */ + @Transactional(readOnly = true) + public Optional findCustomAttribute(URI attributeUri) { + Objects.requireNonNull(attributeUri); + return dataDao.findCustomAttribute(attributeUri); + } + /** * Gets basic metadata about a resource with the specified identifier. * diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidatorTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java similarity index 98% rename from src/test/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidatorTest.java rename to src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java index 6fa5184da..e5db13687 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/MetamodelRollbackValidatorTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java @@ -33,7 +33,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class MetamodelRollbackValidatorTest { +class RollbackValidatorTest { @Mock private ChangeRollbackDao changeRollbackDao; @@ -42,7 +42,7 @@ class MetamodelRollbackValidatorTest { private Attribute attribute; @InjectMocks - private MetamodelRollbackValidator sut; + private RollbackValidator sut; private static Stream> primitiveOriginalValues() { return Stream.of( From 40a19dc5d5f04812b0d96d3b7a97569585f4f8c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 12:45:43 +0200 Subject: [PATCH 07/27] [Test kbss-cvut/termit-ui#790] Implement tests for ChangeRollbackServiceTest --- .../ChangeRollbackIntegrationTest.java | 284 ++++++++++++++++++ .../ChangeRollbackServiceTest.java | 153 ++++++++++ 2 files changed, 437 insertions(+) create mode 100644 src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java create mode 100644 src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java new file mode 100644 index 000000000..3f3362139 --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java @@ -0,0 +1,284 @@ +package cz.cvut.kbss.termit.service.changetracking; + +import cz.cvut.kbss.jopa.model.EntityManager; +import cz.cvut.kbss.jopa.model.MultilingualString; +import cz.cvut.kbss.jopa.vocabulary.RDFS; +import cz.cvut.kbss.termit.dto.TermInfo; +import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; +import cz.cvut.kbss.termit.environment.Environment; +import cz.cvut.kbss.termit.environment.Generator; +import cz.cvut.kbss.termit.exception.UpdateChangeRecordRollbackException; +import cz.cvut.kbss.termit.model.Asset; +import cz.cvut.kbss.termit.model.CustomAttribute; +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Term_; +import cz.cvut.kbss.termit.model.User; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.Vocabulary_; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; +import cz.cvut.kbss.termit.security.model.UserRole; +import cz.cvut.kbss.termit.service.BaseServiceTestRunner; +import cz.cvut.kbss.termit.service.business.RudService; +import cz.cvut.kbss.termit.service.business.TermService; +import cz.cvut.kbss.termit.service.business.VocabularyService; +import cz.cvut.kbss.termit.service.document.TextAnalysisService; +import cz.cvut.kbss.termit.service.repository.ChangeRecordService; +import cz.cvut.kbss.termit.service.repository.DataRepositoryService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; + +import java.net.URI; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; + + +class ChangeRollbackIntegrationTest extends BaseServiceTestRunner { + private static final URI PROPERTY = URI.create("http://example.com/property"); + private static final URI URI_PROPERTY = URI.create("http://example.com/property/uri"); + private static final URI PROPERTY_B = URI.create("http://example.com/property/b"); + + @Autowired + private EntityManager em; + + @Autowired + private TermService termService; + + @Autowired + private VocabularyService vocabularyService; + + @Autowired + private ChangeRollbackService sut; + + @MockitoSpyBean + private ChangeTracker changeTracker; + + @Autowired + private ChangeRecordService changeRecordService; + + @Autowired + private DataRepositoryService dataRepositoryService; + + @MockitoBean + private TextAnalysisService textAnalysisService; // no-op analysis service + + private Vocabulary vocabulary; + + private Term term; + private Term termB; + private Term termC; + private Term termD; + + final Set originalPropertyValue = Set.of("first value", "second value"); + + @BeforeEach + void setUp() { + enableRdfsInference(em); + + final User author = Generator.generateUserWithId(); + author.addType(UserRole.ADMIN.getType()); + Environment.setCurrentUser(author); + + transactional(() -> em.persist(author)); + + vocabulary = Generator.generateVocabularyWithId(); + term = Generator.generateTermWithId(vocabulary.getUri()); + termB = Generator.generateTermWithId(vocabulary.getUri()); + termC = Generator.generateTermWithId(vocabulary.getUri()); + termD = Generator.generateTermWithId(vocabulary.getUri()); + + term.setProperties(new HashMap<>()); + + term.getProperties().put(PROPERTY.toString(), new HashSet<>(originalPropertyValue)); + term.getProperties().put(URI_PROPERTY.toString(), new HashSet<>(Set.of(PROPERTY))); + + term.setRelated(new HashSet<>()); + term.getRelated().add(termB.toTermInfo()); + term.getRelated().add(termC.toTermInfo()); + + vocabularyService.persist(vocabulary); + + termService.persistRoot(termB, vocabulary); + termService.persistRoot(termC, vocabulary); + termService.persistRoot(termD, vocabulary); + + termService.persistRoot(term, vocabulary); + } + + private static ChangeRecordFilterDto changeFilter() { + final ChangeRecordFilterDto filter = new ChangeRecordFilterDto(); + filter.setChangeType(UpdateChangeRecord_.entityClassIRI.toURI()); + return filter; + } + + private MultilingualString makeCopy(MultilingualString original) { + return new MultilingualString(original.getValue()); + } + + private UpdateChangeRecord getRecord(Asset changedAsset) { + return (UpdateChangeRecord) changeRecordService + .getChanges(changedAsset, changeFilter()).getFirst(); + } + + private > T update(T entity, RudService service) { + service.update(entity); + return service.findRequired(entity.getUri()); + } + + @Test + void rollbackVocabularyLabelPersistsOriginalValue() { + final MultilingualString originalValue = makeCopy(vocabulary.getLabel()); + + vocabulary.setLabel(Environment.LANGUAGE, "new vocabulary label"); + vocabulary = update(vocabulary, vocabularyService); + + // verify change event was handled by change tracker + verify(changeTracker).onAssetUpdateEvent(any()); + + // retrieve change record created by change tracker + final UpdateChangeRecord record = getRecord(vocabulary); + + assertEquals(Vocabulary_.labelPropertyIRI.toURI(), record.getChangedAttribute()); + assertEquals(Set.of(originalValue), record.getOriginalValue()); + assertEquals(Set.of(vocabulary.getLabel()), record.getNewValue()); + + sut.rollback(record); + + + final Vocabulary rollbacked = vocabularyService.findRequired(vocabulary.getUri()); + assertEquals(originalValue, rollbacked.getLabel()); + } + + @Test + void rollbackRelatedTermRollsbackToOriginalValue() { + final Set originalValue = Set.copyOf(term.getRelated()); + + term.getRelated().remove(termB.toTermInfo()); + // termC remains + term.getRelated().add(termD.toTermInfo()); + term = update(term, termService); + + assertEquals(Set.of(termC.toTermInfo(), termD.toTermInfo()), term.getRelated()); + + final UpdateChangeRecord record = getRecord(term); + sut.rollback(record); + + term = termService.findRequired(term.getUri()); + + assertEquals(originalValue, term.getRelated()); + } + + @Test + void rollbackRelatedTermThrowsWhenOriginalRelatedTermDoesNotExist() { + final Set originalValue = Set.copyOf(term.getRelated()); + + term.getRelated().remove(termB.toTermInfo()); + // termC remains + term = update(term, termService); + + final Set newValue = Set.of(termC.toTermInfo()); + assertEquals(newValue, term.getRelated()); + termService.remove(termB); + + final UpdateChangeRecord record = getRecord(term); + + assertFalse(termService.exists(termB.getUri())); + assertTrue(record.getOriginalValue().contains(termB.getUri())); + + assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); + + term = termService.findRequired(term.getUri()); + assertEquals(newValue, term.getRelated(), "The related terms must not change when rollback fails"); + assertNotEquals(originalValue, term.getRelated()); + } + + @Test + void rollbackNativePrimitivePropertyPersistsOriginalValue() { + final String newValue = "new value"; + term.getProperties().get(PROPERTY.toString()).add(newValue); + term = update(term, termService); + + assertNotEquals(originalPropertyValue, term.getProperties().get(PROPERTY.toString())); + + final UpdateChangeRecord record = getRecord(term); + + assertEquals(3, record.getNewValue().size()); + assertTrue(record.getNewValue().containsAll(originalPropertyValue)); + assertTrue(record.getNewValue().contains(newValue)); + + sut.rollback(record); + + term = termService.findRequired(term.getUri()); + assertEquals(originalPropertyValue, term.getProperties().get(PROPERTY.toString())); + assertFalse(term.getProperties().containsKey(PROPERTY_B.toString())); + assertEquals(1, term.getProperties().size()); + } + + /** + * TermIt cannot guarantee that the reference should not be valid Term/Vocabulary + */ + @Test + void rollbackThrowsForRollbackOfNativeURIProperty() { + term.getProperties().remove(URI_PROPERTY.toString()); + term = update(term, termService); + + assertFalse(term.getProperties().containsKey(URI_PROPERTY.toString())); + + final UpdateChangeRecord record = getRecord(term); + assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); + } + + private CustomAttribute persistUriCustomAttribute() { + final CustomAttribute customAttribute = new CustomAttribute(); + customAttribute.setUri(URI_PROPERTY); + customAttribute.setLabel(MultilingualString.create("General URI resource", null)); + customAttribute.setDomain(Term_.entityClassIRI.toURI()); + customAttribute.setRange(URI.create(RDFS.RESOURCE)); + dataRepositoryService.persistCustomAttribute(customAttribute); + return customAttribute; + } + + @Test + void rollbackOfNativeURICustomAttributePersistsOriginalValue() { + persistUriCustomAttribute(); + + term.getProperties().remove(URI_PROPERTY.toString()); + term = update(term, termService); + + assertFalse(term.getProperties().containsKey(URI_PROPERTY.toString())); + + final UpdateChangeRecord record = getRecord(term); + sut.rollback(record); + + term = termService.findRequired(term.getUri()); + assertTrue(term.getProperties().containsKey(URI_PROPERTY.toString())); + assertTrue(term.getProperties().get(URI_PROPERTY.toString()).contains(PROPERTY)); + } + + @Test + void rollbackOfCustomAttributeWithUnknownRangeThrows() { + CustomAttribute attribute = persistUriCustomAttribute(); + attribute.setRange(PROPERTY_B); + dataRepositoryService.updateCustomAttribute(attribute); + + term.getProperties().remove(URI_PROPERTY.toString()); + term = update(term, termService); + + assertFalse(term.getProperties().containsKey(URI_PROPERTY.toString())); + + final UpdateChangeRecord record = getRecord(term); + assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); + } +} diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java new file mode 100644 index 000000000..9e0e036cf --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java @@ -0,0 +1,153 @@ +package cz.cvut.kbss.termit.service.changetracking; + +import cz.cvut.kbss.termit.environment.Generator; +import cz.cvut.kbss.termit.exception.UpdateChangeRecordRollbackException; +import cz.cvut.kbss.termit.model.Asset; +import cz.cvut.kbss.termit.model.Term; +import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import cz.cvut.kbss.termit.service.repository.TermRepositoryService; +import cz.cvut.kbss.termit.service.repository.VocabularyRepositoryService; +import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; +import cz.cvut.kbss.termit.service.security.authorization.VocabularyAuthorizationService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.access.AccessDeniedException; + +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ChangeRollbackServiceTest { + + @Mock + private RollbackValidator rollbackValidator; + + @Mock + private ChangeRollbackDao rollbackDao; + + @Mock + private TermRepositoryService termService; + + @Mock + private VocabularyRepositoryService vocabularyService; + + @Mock + private TermAuthorizationService termAuthorizationService; + + @Mock + private VocabularyAuthorizationService vocabularyAuthorizationService; + + @InjectMocks + private ChangeRollbackService sut; + + @Test + void canRollbackValidatesExistingVocabulary() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + final UpdateChangeRecord record = recordFor(vocabulary); + when(vocabularyService.find(vocabulary.getUri())).thenReturn(Optional.of(vocabulary)); + when(vocabularyAuthorizationService.canModify(vocabulary)).thenReturn(true); + when(rollbackValidator.canRollback(record, Vocabulary.class)).thenReturn(true); + + assertTrue(sut.canRollback(record)); + } + + @Test + void canRollbackValidatesExistingTerm() { + final Term term = Generator.generateTermWithId(); + final UpdateChangeRecord record = recordFor(term); + when(termService.find(term.getUri())).thenReturn(Optional.of(term)); + when(termAuthorizationService.canModify(term)).thenReturn(true); + when(rollbackValidator.canRollback(record, Term.class)).thenReturn(true); + + assertTrue(sut.canRollback(record)); + } + + @Test + void canRollbackReturnsFalseWhenChangedEntityDoesNotExist() { + final UpdateChangeRecord record = new UpdateChangeRecord(); + record.setChangedEntity(Generator.generateUri()); + when(vocabularyService.find(record.getChangedEntity())).thenReturn(Optional.empty()); + when(termService.find(record.getChangedEntity())).thenReturn(Optional.empty()); + + assertFalse(sut.canRollback(record)); + } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void canRollbackChecksForUserAuthorizationWhenRollbackingTerm(boolean isAuthorized) { + final Term term = Generator.generateTermWithId(); + final UpdateChangeRecord record = recordFor(term); + when(termService.find(term.getUri())).thenReturn(Optional.of(term)); + when(termAuthorizationService.canModify(term)).thenReturn(isAuthorized); + when(rollbackValidator.canRollback(record, Term.class)).thenReturn(true); + + assertEquals(isAuthorized, sut.canRollback(record)); + } + + @ParameterizedTest + @CsvSource({"true", "false"}) + void canRollbackChecksForUserAuthorizationWhenRollbackingVocabulary(boolean isAuthorized) { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + final UpdateChangeRecord record = recordFor(vocabulary); + when(vocabularyService.find(vocabulary.getUri())).thenReturn(Optional.of(vocabulary)); + when(vocabularyAuthorizationService.canModify(vocabulary)).thenReturn(isAuthorized); + when(rollbackValidator.canRollback(record, Vocabulary.class)).thenReturn(true); + + assertEquals(isAuthorized, sut.canRollback(record)); + } + + @Test + void rollbackThrowsWhenRecordCannotBeRolledBack() { + final Term term = Generator.generateTermWithId(); + final UpdateChangeRecord record = recordFor(term); + when(vocabularyService.find(term.getUri())).thenReturn(Optional.empty()); + when(termService.find(term.getUri())).thenReturn(Optional.of(term)); + when(rollbackValidator.canRollback(record, Term.class)).thenReturn(false); + + assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); + } + + @Test + void rollbackThrowsWhenUserIsNotAuthorizedToModifyTerm() { + final Term term = Generator.generateTermWithId(); + final UpdateChangeRecord record = recordFor(term); + when(vocabularyService.find(term.getUri())).thenReturn(Optional.empty()); + when(termService.find(term.getUri())).thenReturn(Optional.of(term)); + when(rollbackValidator.canRollback(record, Term.class)).thenReturn(true); + when(termAuthorizationService.canModify(term)).thenReturn(false); + + assertThrows(AccessDeniedException.class, () -> sut.rollback(record)); + } + + @Test + void rollbackThrowsWhenUserIsNotAuthorizedToModifyVocabulary() { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + final UpdateChangeRecord record = recordFor(vocabulary); + when(vocabularyService.find(vocabulary.getUri())).thenReturn(Optional.of(vocabulary)); + when(rollbackValidator.canRollback(record, Vocabulary.class)).thenReturn(true); + when(vocabularyAuthorizationService.canModify(vocabulary)).thenReturn(false); + + assertThrows(AccessDeniedException.class, () -> sut.rollback(record)); + } + + private static UpdateChangeRecord recordFor(Asset asset) { + final UpdateChangeRecord record = new UpdateChangeRecord(asset); + record.setChangedAttribute(Generator.generateUri()); + record.setOriginalValue(Set.of("original")); + record.setNewValue(Set.of("updated")); + return record; + } +} From 998044860e558e3b2059abb34101402b0d927f64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 14:21:49 +0200 Subject: [PATCH 08/27] [Enhancement kbss-cvut/termit-ui#790] Introduce termit:reversible-change sub-class of UpdateChangeRecord. Introduce rollback endpoints. --- ontology/termit.ttl | 8 +++ .../changetracking/AbstractChangeRecord.java | 13 +++++ .../changetracking/UpdateChangeRecord.java | 4 ++ .../dao/changetracking/ChangeRecordDao.java | 16 +++++ .../cvut/kbss/termit/rest/TermController.java | 51 +++++++++++++++- .../termit/rest/VocabularyController.java | 43 +++++++++++++- .../changetracking/ChangeRollbackService.java | 58 ++++++++++++++++++- .../repository/ChangeRecordService.java | 39 +++++++++++++ 8 files changed, 225 insertions(+), 7 deletions(-) diff --git a/ontology/termit.ttl b/ontology/termit.ttl index 2c886f56a..ca831458c 100644 --- a/ontology/termit.ttl +++ b/ontology/termit.ttl @@ -4,6 +4,7 @@ @prefix xsd: . @prefix rdfs: . @prefix skos: . +@prefix dd: . a skos:ConceptScheme , owl:Ontology ; @@ -719,3 +720,10 @@ termit:has-related-vocabulary ; "Has related vocabulary"@en , "Má související slovník"@cs . + +termit:reversible-change + a skos:Concept , owl:Class ; + rdfs:subClassOf dd:update-of-entity ; + skos:broader dd:update-of-entity ; + skos:inScheme ; + skos:prefLabel "Reversible Change"@en , "Vratná změna"@cs . diff --git a/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java b/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java index 7ed4e338e..3de928824 100644 --- a/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java +++ b/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java @@ -23,6 +23,7 @@ import cz.cvut.kbss.jopa.model.annotations.OWLDataProperty; import cz.cvut.kbss.jopa.model.annotations.OWLObjectProperty; import cz.cvut.kbss.jopa.model.annotations.ParticipationConstraints; +import cz.cvut.kbss.jopa.model.annotations.Types; import cz.cvut.kbss.jopa.vocabulary.DC; import cz.cvut.kbss.termit.model.AbstractEntity; import cz.cvut.kbss.termit.model.Asset; @@ -33,6 +34,7 @@ import java.net.URI; import java.time.Instant; import java.util.Objects; +import java.util.Set; /** * Represents a change to an asset. @@ -53,6 +55,9 @@ public class AbstractChangeRecord extends AbstractEntity implements Comparable types; + public AbstractChangeRecord() { } @@ -84,6 +89,14 @@ public void setChangedEntity(URI changedEntity) { this.changedEntity = changedEntity; } + public Set getTypes() { + return types; + } + + public void setTypes(Set types) { + this.types = types; + } + @Override public boolean equals(Object o) { if (this == o) { diff --git a/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java b/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java index bdabab7c8..6c34845a7 100644 --- a/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java +++ b/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java @@ -31,6 +31,10 @@ @OWLClass(iri = Vocabulary.s_c_update_of_entity) public class UpdateChangeRecord extends AbstractChangeRecord { + /** + * Class indicating that the change record can be rolled back by the current user. + */ + public static final URI REVERSIBLE_CHANGE_CLASS = URI.create(Vocabulary.s_c_reversible_change); @ParticipationConstraints(nonEmpty = true) @OWLObjectProperty(iri = Vocabulary.s_p_has_changed_attribute) diff --git a/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDao.java index 73d18f625..33e58ba17 100644 --- a/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDao.java +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDao.java @@ -257,4 +257,20 @@ public Set getAuthors(HasIdentifier asset) { throw new PersistenceException(e); } } + + /** + * Finds a change record of the specified type and identifier. + * + * @param recordClass Change record type + * @param recordUri Change record identifier + * @return Matching record, or an empty optional if none is found + */ + public Optional find(Class recordClass, URI recordUri) { + Objects.requireNonNull(recordUri); + try { + return Optional.ofNullable(em.find(recordClass, recordUri)); + } catch (RuntimeException e) { + throw new PersistenceException("Failed to find UpdateChangeRecord: " + Utils.uriToString(recordUri), e); + } + } } 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 9ee1e2c42..7b98b0673 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -22,12 +22,14 @@ import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; import cz.cvut.kbss.termit.dto.listing.TermDto; +import cz.cvut.kbss.termit.exception.InvalidParameterException; 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.model.assignment.TermDefinitionSource; import cz.cvut.kbss.termit.model.assignment.TermOccurrence; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.comment.Comment; import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver; import cz.cvut.kbss.termit.rest.doc.ApiDocConstants; @@ -36,6 +38,7 @@ import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.TermService; import cz.cvut.kbss.termit.service.business.util.TermSelectionParams; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportType; import cz.cvut.kbss.termit.service.repository.removal.SubTermRemovalStrategy; @@ -95,14 +98,17 @@ public class TermController extends BaseController { private final TermService termService; + private final ChangeRollbackService changeRollbackService; + private final VocabularyNamespaceResolver namespaceResolver; @Autowired public TermController(IdentifierResolver idResolver, Configuration config, TermService termService, - VocabularyNamespaceResolver namespaceResolver) { + VocabularyNamespaceResolver namespaceResolver, ChangeRollbackService changeRollbackService) { super(idResolver, config); this.termService = termService; this.namespaceResolver = namespaceResolver; + this.changeRollbackService = changeRollbackService; } private URI getVocabularyUri(Optional namespace, String fragment) { @@ -846,7 +852,9 @@ public List getHistory( @RequestParam(name = "attribute", required = false, defaultValue = "") String changedAttributeName) { final URI termUri = getTermUri(localName, termLocalName, namespace); final ChangeRecordFilterDto filterDto = new ChangeRecordFilterDto(changedAttributeName, authorName, changeType); - return termService.getChanges(termService.findRequired(termUri), filterDto); + final List records = termService.getChanges(termService.findRequired(termUri), filterDto); + changeRollbackService.withReversibleType(records); + return records; } /** @@ -883,7 +891,44 @@ public List getHistory(@Parameter(description = ApiDoc.ID_ defaultValue = "") String changedAttributeName) { final URI termUri = idResolver.resolveIdentifier(namespace, localName); final ChangeRecordFilterDto filter = new ChangeRecordFilterDto(changedAttributeName, authorName, changeType); - return termService.getChanges(termService.findRequired(termUri), filter); + final List records = termService.getChanges(termService.findRequired(termUri), filter); + changeRollbackService.withReversibleType(records); + return records; + } + + /** + * Rolls back the specified update change record of a term. + * + * @param localName Term local name + * @param namespace Term identifier namespace + * @param changeRecord Local name of the update change record + * @throws InvalidParameterException If the change record is not associated with the specified term + */ + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, + description = "Rolls back the specified update change record of the term.") + @ApiResponses({ + @ApiResponse(responseCode = "204", description = "Change successfully rolled back."), + @ApiResponse(responseCode = "404", description = "Term or update change record not found.") + }) + @PostMapping("/terms/{localName}/history/{changeRecord}/rollback") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void rollbackChange( + @Parameter(description = ApiDoc.ID_STANDALONE_LOCAL_NAME_DESCRIPTION, + example = ApiDoc.ID_TERM_LOCAL_NAME_EXAMPLE) + @PathVariable String localName, + @Parameter(description = ApiDoc.ID_STANDALONE_NAMESPACE_DESCRIPTION, + example = ApiDoc.ID_STANDALONE_NAMESPACE_EXAMPLE) + @RequestParam(name = QueryParams.NAMESPACE) String namespace, + @Parameter(description = "Local name of the update change record to roll back.") + @PathVariable String changeRecord) { + final URI termUri = idResolver.resolveIdentifier(namespace, localName); + final UpdateChangeRecord recordToRollback = changeRollbackService.findRecordByLocalName(changeRecord); + if (termUri.equals(recordToRollback.getChangedEntity())) { + changeRollbackService.rollback(recordToRollback); + LOG.debug("Change record {} of term {} rolled back.", changeRecord, Utils.uriToString(termUri)); + } else { + throw new InvalidParameterException("Record not associated with specified Term"); + } } @Operation(security = {@SecurityRequirement(name = "bearer-key")}, diff --git a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java index 0918a4a0b..e470be7c9 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java @@ -24,16 +24,19 @@ import cz.cvut.kbss.termit.dto.acl.AccessControlListDto; import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; import cz.cvut.kbss.termit.dto.listing.VocabularyDto; +import cz.cvut.kbss.termit.exception.InvalidParameterException; import cz.cvut.kbss.termit.model.RdfsResource; import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.acl.AccessControlRecord; import cz.cvut.kbss.termit.model.acl.AccessLevel; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.rest.doc.ApiDocConstants; import cz.cvut.kbss.termit.rest.util.RestUtils; import cz.cvut.kbss.termit.security.SecurityConstants; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.VocabularyService; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; @@ -94,11 +97,14 @@ public class VocabularyController extends BaseController { private final VocabularyService vocabularyService; + private final ChangeRollbackService changeRollbackService; + @Autowired public VocabularyController(VocabularyService vocabularyService, IdentifierResolver idResolver, - Configuration config) { + Configuration config, ChangeRollbackService changeRollbackService) { super(idResolver, config); this.vocabularyService = vocabularyService; + this.changeRollbackService = changeRollbackService; } @Operation(security = {@SecurityRequirement(name = "bearer-key")}, @@ -317,6 +323,41 @@ public List getHistory( return vocabularyService.getChanges(vocabulary, filterDto); } + /** + * Rolls back the specified update change record of a vocabulary. + * + * @param localName Vocabulary local name + * @param namespace Optional vocabulary namespace + * @param changeRecord Local name of the update change record + * @throws InvalidParameterException If the change record is not associated with the specified vocabulary + */ + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, + description = "Rolls back the specified update change record of the vocabulary.") + @ApiResponses({ + @ApiResponse(responseCode = "204", description = "Change successfully rolled back."), + @ApiResponse(responseCode = "404", description = "Vocabulary or update change record not found.") + }) + @PostMapping("/{localName}/history/{changeRecord}/rollback") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void rollbackChange( + @Parameter(description = ApiDoc.ID_LOCAL_NAME_DESCRIPTION, + example = ApiDoc.ID_LOCAL_NAME_EXAMPLE) + @PathVariable String localName, + @Parameter(description = ApiDoc.ID_NAMESPACE_DESCRIPTION, + example = ApiDoc.ID_NAMESPACE_EXAMPLE) + @RequestParam(name = QueryParams.NAMESPACE, required = false) Optional namespace, + @Parameter(description = "Local name of the update change record to roll back.") + @PathVariable String changeRecord) { + final URI vocabularyUri = resolveVocabularyUri(localName, namespace); + final UpdateChangeRecord recordToRollback = changeRollbackService.findRecordByLocalName(changeRecord); + if (vocabularyUri.equals(recordToRollback.getChangedEntity())) { + changeRollbackService.rollback(recordToRollback); + LOG.debug("Change record {} of vocabulary {} rolled back.", changeRecord, Utils.uriToString(vocabularyUri)); + } else { + throw new InvalidParameterException("Record not associated with specified Vocabulary."); + } + } + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, description = "Gets summary info about changes made to the content of the vocabulary (term creation, editing).") @ApiResponses({ diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index b30502329..8303ed73e 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -5,9 +5,13 @@ import cz.cvut.kbss.termit.model.Asset; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.Vocabulary; +import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; import cz.cvut.kbss.termit.model.util.HasProperties; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import cz.cvut.kbss.termit.service.IdentifierResolver; +import cz.cvut.kbss.termit.service.repository.ChangeRecordService; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; import cz.cvut.kbss.termit.service.repository.VocabularyRepositoryService; import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; @@ -17,6 +21,8 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.net.URI; +import java.util.Collection; import java.util.Optional; /** @@ -26,23 +32,29 @@ public class ChangeRollbackService { private final RollbackValidator rollbackValidator; private final ChangeRollbackDao rollbackDao; + private final ChangeRecordService changeRecordService; private final TermRepositoryService termService; private final VocabularyRepositoryService vocabularyService; private final TermAuthorizationService termAuthorizationService; private final VocabularyAuthorizationService vocabularyAuthorizationService; + private final IdentifierResolver identifierResolver; public ChangeRollbackService(RollbackValidator rollbackValidator, ChangeRollbackDao rollbackDao, + ChangeRecordService changeRecordService, TermRepositoryService termService, VocabularyRepositoryService vocabularyService, TermAuthorizationService termAuthorizationService, - VocabularyAuthorizationService vocabularyAuthorizationService) { + VocabularyAuthorizationService vocabularyAuthorizationService, + IdentifierResolver identifierResolver) { this.rollbackValidator = rollbackValidator; this.rollbackDao = rollbackDao; + this.changeRecordService = changeRecordService; this.termService = termService; this.vocabularyService = vocabularyService; this.termAuthorizationService = termAuthorizationService; this.vocabularyAuthorizationService = vocabularyAuthorizationService; + this.identifierResolver = identifierResolver; } /** @@ -52,7 +64,7 @@ public ChangeRollbackService(RollbackValidator rollbackValidator, * @return {@code true} when the change record can be rolled back and the current user is authorized to do so, * {@code false} otherwise. */ - @Transactional + @Transactional(readOnly = true) public boolean canRollback(UpdateChangeRecord record) { final Asset changedObject = resolveChangedAsset(record); if (changedObject == null) { @@ -61,6 +73,32 @@ public boolean canRollback(UpdateChangeRecord record) { return canRollback(record, changedObject) && isModificationAuthorized(changedObject); } + /** + * Sets the {@link UpdateChangeRecord#REVERSIBLE_CHANGE_CLASS reversible class} + * on each {@link UpdateChangeRecord} in the specified collection based on whether it + * can be rolled back by the current user. + * + * @param records Change records to enrich with rollback possibility + */ + @Transactional(readOnly = true) + public void withReversibleType(Collection records) { + Asset changedAsset = null; + boolean authorized = false; + for(AbstractChangeRecord record : records) { + if (changedAsset == null || !changedAsset.getUri().equals(record.getChangedEntity())) { + changedAsset = resolveChangedAsset(record); + authorized = isModificationAuthorized(changedAsset); + } + if (authorized && + record instanceof UpdateChangeRecord updateRecord && + canRollback(updateRecord, changedAsset)) { + record.getTypes().add(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + } else { + record.getTypes().remove(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + } + } + } + /** * Checks whether the {@link UpdateChangeRecord} of the {@code changedObject} can be rolled back. * @@ -93,6 +131,20 @@ public void rollback(UpdateChangeRecord record) { doRollback(record, changedAsset); } + /** + * Finds an update change record with the specified local name. + *

+ * The local name is resolved against the {@link UpdateChangeRecord} identifier namespace. + * + * @param recordLocalName Change record local name + * @return Matching update change record + * @throws cz.cvut.kbss.termit.exception.NotFoundException If no matching record is found + */ + public UpdateChangeRecord findRecordByLocalName(String recordLocalName) { + final URI recordUri = identifierResolver.resolveIdentifier(UpdateChangeRecord_.entityClassIRI.toString(), recordLocalName); + return changeRecordService.findUpdateRequired(recordUri); + } + /** * Resolves the Java field of the entity class and updates its value. * When the attribute is not resolved to a specific Java field, the attribute is updated via @@ -138,7 +190,7 @@ private Asset resolveChangedAssetRequired(UpdateChangeRecord record) { return changedAsset; } - private Asset resolveChangedAsset(UpdateChangeRecord record) { + private Asset resolveChangedAsset(AbstractChangeRecord record) { Optional vocabulary = vocabularyService.find(record.getChangedEntity()); if (vocabulary.isPresent()) { return vocabulary.get(); diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java index ad09428ad..71c275f6e 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java @@ -18,16 +18,20 @@ package cz.cvut.kbss.termit.service.repository; import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; +import cz.cvut.kbss.termit.exception.NotFoundException; import cz.cvut.kbss.termit.model.Asset; import cz.cvut.kbss.termit.model.User; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRecordDao; import cz.cvut.kbss.termit.service.changetracking.ChangeRecordProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.net.URI; import java.util.List; +import java.util.Optional; import java.util.Set; @Service @@ -58,4 +62,39 @@ public List getChanges(Asset asset, ChangeRecordFilterD public Set getAuthors(HasIdentifier asset) { return changeRecordDao.getAuthors(asset); } + + /** + * Finds an update change record with the specified identifier. + * + * @param recordUri Change record identifier + * @return Matching update change record + * @throws NotFoundException If no matching record is found + */ + public UpdateChangeRecord findUpdateRequired(URI recordUri) { + return findRequired(UpdateChangeRecord.class, recordUri); + } + + /** + * Finds a change record of the specified type and identifier. + * + * @param recordClass Change record type + * @param recordUri Change record identifier + * @return Matching change record + * @throws NotFoundException If no matching record is found + */ + private T findRequired(Class recordClass, URI recordUri) { + return find(recordClass, recordUri) + .orElseThrow(()-> new NotFoundException(recordClass.getSimpleName() + " not found")); + } + + /** + * Finds a change record of the specified type and identifier. + * + * @param recordClass Change record type + * @param recordUri Change record identifier + * @return Matching record, or an empty optional if none is found + */ + private Optional find(Class recordClass, URI recordUri) { + return changeRecordDao.find(recordClass, recordUri); + } } From d68abb60b76fb7b862e8acda3c73620dcd9dc808 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 15:02:36 +0200 Subject: [PATCH 09/27] [Test] Fix failing tests because of missing bean in context and database context sharing between test methods --- .../VocabularyControllerSecurityTest.java | 4 ++ .../ChangeRollbackIntegrationTest.java | 46 +++++++++++-------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerSecurityTest.java b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerSecurityTest.java index d2096eb9d..6789ce5a4 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerSecurityTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerSecurityTest.java @@ -24,6 +24,7 @@ import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.SparqlExternalVocabularyService; import cz.cvut.kbss.termit.service.business.VocabularyService; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.util.Configuration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -62,6 +63,9 @@ class VocabularyControllerSecurityTest extends BaseControllerTestRunner { @MockitoBean private SparqlExternalVocabularyService externalVocabularyService; + @MockitoBean + private ChangeRollbackService changeRollbackService; // no-op bean + @Autowired private Configuration configuration; diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java index 3f3362139..e91dc3935 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java @@ -46,9 +46,6 @@ class ChangeRollbackIntegrationTest extends BaseServiceTestRunner { - private static final URI PROPERTY = URI.create("http://example.com/property"); - private static final URI URI_PROPERTY = URI.create("http://example.com/property/uri"); - private static final URI PROPERTY_B = URI.create("http://example.com/property/b"); @Autowired private EntityManager em; @@ -83,6 +80,10 @@ class ChangeRollbackIntegrationTest extends BaseServiceTestRunner { final Set originalPropertyValue = Set.of("first value", "second value"); + private URI property; + private URI uriProperty; + private URI propertyB; + @BeforeEach void setUp() { enableRdfsInference(em); @@ -93,6 +94,10 @@ void setUp() { transactional(() -> em.persist(author)); + property = URI.create(Generator.generateUriString() + "/property"); + uriProperty = URI.create(Generator.generateUriString() + "/property/uri"); + propertyB = URI.create(Generator.generateUriString() + "/property/B"); + vocabulary = Generator.generateVocabularyWithId(); term = Generator.generateTermWithId(vocabulary.getUri()); termB = Generator.generateTermWithId(vocabulary.getUri()); @@ -101,8 +106,8 @@ void setUp() { term.setProperties(new HashMap<>()); - term.getProperties().put(PROPERTY.toString(), new HashSet<>(originalPropertyValue)); - term.getProperties().put(URI_PROPERTY.toString(), new HashSet<>(Set.of(PROPERTY))); + term.getProperties().put(property.toString(), new HashSet<>(originalPropertyValue)); + term.getProperties().put(uriProperty.toString(), new HashSet<>(Set.of(property))); term.setRelated(new HashSet<>()); term.getRelated().add(termB.toTermInfo()); @@ -207,10 +212,11 @@ void rollbackRelatedTermThrowsWhenOriginalRelatedTermDoesNotExist() { @Test void rollbackNativePrimitivePropertyPersistsOriginalValue() { final String newValue = "new value"; - term.getProperties().get(PROPERTY.toString()).add(newValue); + final int originalTermPropertiesSize = term.getProperties().size(); + term.getProperties().get(property.toString()).add(newValue); term = update(term, termService); - assertNotEquals(originalPropertyValue, term.getProperties().get(PROPERTY.toString())); + assertNotEquals(originalPropertyValue, term.getProperties().get(property.toString())); final UpdateChangeRecord record = getRecord(term); @@ -221,9 +227,9 @@ void rollbackNativePrimitivePropertyPersistsOriginalValue() { sut.rollback(record); term = termService.findRequired(term.getUri()); - assertEquals(originalPropertyValue, term.getProperties().get(PROPERTY.toString())); - assertFalse(term.getProperties().containsKey(PROPERTY_B.toString())); - assertEquals(1, term.getProperties().size()); + assertEquals(originalPropertyValue, term.getProperties().get(property.toString())); + assertFalse(term.getProperties().containsKey(propertyB.toString())); + assertEquals(originalTermPropertiesSize, term.getProperties().size()); } /** @@ -231,10 +237,10 @@ void rollbackNativePrimitivePropertyPersistsOriginalValue() { */ @Test void rollbackThrowsForRollbackOfNativeURIProperty() { - term.getProperties().remove(URI_PROPERTY.toString()); + term.getProperties().remove(uriProperty.toString()); term = update(term, termService); - assertFalse(term.getProperties().containsKey(URI_PROPERTY.toString())); + assertFalse(term.getProperties().containsKey(uriProperty.toString())); final UpdateChangeRecord record = getRecord(term); assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); @@ -242,7 +248,7 @@ void rollbackThrowsForRollbackOfNativeURIProperty() { private CustomAttribute persistUriCustomAttribute() { final CustomAttribute customAttribute = new CustomAttribute(); - customAttribute.setUri(URI_PROPERTY); + customAttribute.setUri(uriProperty); customAttribute.setLabel(MultilingualString.create("General URI resource", null)); customAttribute.setDomain(Term_.entityClassIRI.toURI()); customAttribute.setRange(URI.create(RDFS.RESOURCE)); @@ -254,29 +260,29 @@ private CustomAttribute persistUriCustomAttribute() { void rollbackOfNativeURICustomAttributePersistsOriginalValue() { persistUriCustomAttribute(); - term.getProperties().remove(URI_PROPERTY.toString()); + term.getProperties().remove(uriProperty.toString()); term = update(term, termService); - assertFalse(term.getProperties().containsKey(URI_PROPERTY.toString())); + assertFalse(term.getProperties().containsKey(uriProperty.toString())); final UpdateChangeRecord record = getRecord(term); sut.rollback(record); term = termService.findRequired(term.getUri()); - assertTrue(term.getProperties().containsKey(URI_PROPERTY.toString())); - assertTrue(term.getProperties().get(URI_PROPERTY.toString()).contains(PROPERTY)); + assertTrue(term.getProperties().containsKey(uriProperty.toString())); + assertTrue(term.getProperties().get(uriProperty.toString()).contains(property)); } @Test void rollbackOfCustomAttributeWithUnknownRangeThrows() { CustomAttribute attribute = persistUriCustomAttribute(); - attribute.setRange(PROPERTY_B); + attribute.setRange(propertyB); dataRepositoryService.updateCustomAttribute(attribute); - term.getProperties().remove(URI_PROPERTY.toString()); + term.getProperties().remove(uriProperty.toString()); term = update(term, termService); - assertFalse(term.getProperties().containsKey(URI_PROPERTY.toString())); + assertFalse(term.getProperties().containsKey(uriProperty.toString())); final UpdateChangeRecord record = getRecord(term); assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); From 062bebe6ff1de8e9b836eceed79069cbfa1af33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 15:48:41 +0200 Subject: [PATCH 10/27] [Ref] Rename primitives to literals in RollbackValidator --- .../changetracking/RollbackValidator.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java index fa9e69105..88152bb8a 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java @@ -27,7 +27,7 @@ */ @Component public class RollbackValidator { - private static final Class[] PRIMITIVE_CLASSES = { + private static final Class[] LITERAL_CLASSES = { // not including URI - can represent a reference to another entity Number.class, String.class, // TermIt is not using Strings as identifiers @@ -58,7 +58,7 @@ public RollbackValidator(ChangeRollbackDao changeRollbackDao, DataRepositoryServ */ @Transactional(readOnly = true) public boolean canRollback(UpdateChangeRecord record, Class entityClass) { - if (allValuesArePrimitives(record)) { + if (allValuesAreLiteral(record)) { return true; } @@ -75,20 +75,20 @@ public boolean canRollback(UpdateChangeRecord record, Class entityClass) { return canRollbackNativeProperty(record); } - private boolean allValuesArePrimitives(UpdateChangeRecord record) { + private boolean allValuesAreLiteral(UpdateChangeRecord record) { return Stream.of(record.getOriginalValue(), record.getNewValue()) .filter(Objects::nonNull) .flatMap(Collection::stream) .map(Object::getClass) - .allMatch(RollbackValidator::isPrimitive); + .allMatch(RollbackValidator::isLiteral); } - private static boolean isPrimitive(Class clazz) { + private static boolean isLiteral(Class clazz) { if (clazz.isPrimitive()) { return true; } - for (Class primitiveClass : PRIMITIVE_CLASSES) { - if (primitiveClass.isAssignableFrom(clazz)) { + for (Class literalClass : LITERAL_CLASSES) { + if (literalClass.isAssignableFrom(clazz)) { return true; } } @@ -96,7 +96,7 @@ private static boolean isPrimitive(Class clazz) { } private boolean canRollbackAttributeWithType(Class attributeValueClass, UpdateChangeRecord record) { - if (isPrimitive(attributeValueClass)) { + if (isLiteral(attributeValueClass)) { return true; } if (record.getOriginalValue() == null) { @@ -118,9 +118,7 @@ private boolean canRollbackAttributeWithType(Class attributeValueClass, Updat * @return {@code true} when the change record can safely be rolled back, {@code false} otherwise */ private boolean canRollbackToEntityReference(URI referencedEntity) { - if (referencedEntity == null) { - return true; - } + Objects.requireNonNull(referencedEntity); return changeRollbackDao.entityExists(referencedEntity); } From 42f5aced15985b82538b8de042668e2f64ce70ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 22 Sep 2026 16:18:05 +0200 Subject: [PATCH 11/27] [Test kbss-cvut/termit-ui#790] Add integration tests for rollbacking custom attributes with Term range --- .../ChangeRollbackIntegrationTest.java | 84 +++++++++++++++++++ .../changetracking/RollbackValidatorTest.java | 4 + 2 files changed, 88 insertions(+) diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java index e91dc3935..917be36d0 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java @@ -3,6 +3,7 @@ import cz.cvut.kbss.jopa.model.EntityManager; import cz.cvut.kbss.jopa.model.MultilingualString; import cz.cvut.kbss.jopa.vocabulary.RDFS; +import cz.cvut.kbss.jopa.vocabulary.SKOS; import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; import cz.cvut.kbss.termit.environment.Environment; @@ -17,6 +18,7 @@ import cz.cvut.kbss.termit.model.Vocabulary_; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; +import cz.cvut.kbss.termit.persistence.context.DescriptorFactory; import cz.cvut.kbss.termit.security.model.UserRole; import cz.cvut.kbss.termit.service.BaseServiceTestRunner; import cz.cvut.kbss.termit.service.business.RudService; @@ -50,6 +52,9 @@ class ChangeRollbackIntegrationTest extends BaseServiceTestRunner { @Autowired private EntityManager em; + @Autowired + private DescriptorFactory descriptorFactory; + @Autowired private TermService termService; @@ -146,6 +151,7 @@ private > T update(T entity, RudService service) { void rollbackVocabularyLabelPersistsOriginalValue() { final MultilingualString originalValue = makeCopy(vocabulary.getLabel()); + // apply change and create change record vocabulary.setLabel(Environment.LANGUAGE, "new vocabulary label"); vocabulary = update(vocabulary, vocabularyService); @@ -170,6 +176,7 @@ void rollbackVocabularyLabelPersistsOriginalValue() { void rollbackRelatedTermRollsbackToOriginalValue() { final Set originalValue = Set.copyOf(term.getRelated()); + // apply change and create change record term.getRelated().remove(termB.toTermInfo()); // termC remains term.getRelated().add(termD.toTermInfo()); @@ -189,6 +196,7 @@ void rollbackRelatedTermRollsbackToOriginalValue() { void rollbackRelatedTermThrowsWhenOriginalRelatedTermDoesNotExist() { final Set originalValue = Set.copyOf(term.getRelated()); + // apply change and create change record term.getRelated().remove(termB.toTermInfo()); // termC remains term = update(term, termService); @@ -213,6 +221,8 @@ void rollbackRelatedTermThrowsWhenOriginalRelatedTermDoesNotExist() { void rollbackNativePrimitivePropertyPersistsOriginalValue() { final String newValue = "new value"; final int originalTermPropertiesSize = term.getProperties().size(); + + // apply change and create change record term.getProperties().get(property.toString()).add(newValue); term = update(term, termService); @@ -237,6 +247,7 @@ void rollbackNativePrimitivePropertyPersistsOriginalValue() { */ @Test void rollbackThrowsForRollbackOfNativeURIProperty() { + // apply change and create change record term.getProperties().remove(uriProperty.toString()); term = update(term, termService); @@ -260,6 +271,7 @@ private CustomAttribute persistUriCustomAttribute() { void rollbackOfNativeURICustomAttributePersistsOriginalValue() { persistUriCustomAttribute(); + // apply change and create change record term.getProperties().remove(uriProperty.toString()); term = update(term, termService); @@ -279,6 +291,7 @@ void rollbackOfCustomAttributeWithUnknownRangeThrows() { attribute.setRange(propertyB); dataRepositoryService.updateCustomAttribute(attribute); + // apply change and create change record term.getProperties().remove(uriProperty.toString()); term = update(term, termService); @@ -287,4 +300,75 @@ void rollbackOfCustomAttributeWithUnknownRangeThrows() { final UpdateChangeRecord record = getRecord(term); assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); } + + @Test + void rollbackOfCustomAttributeWithExistingTermReferencePersistsOriginalValue() { + final CustomAttribute customAttribute = persistTermReferenceCustomAttribute(); + setNativePropertyWithoutChangeRecord(customAttribute.getUri(), termB.getUri()); + final Set originalValue = Set.of(termB.getUri()); + + // apply change and create change record + term.getProperties().put(customAttribute.getUri().toString(), Set.of(termC.getUri())); + term = update(term, termService); + + final UpdateChangeRecord record = getRecord(term); + sut.rollback(record); + + term = termService.findRequired(term.getUri()); + assertEquals(originalValue, term.getProperties().get(customAttribute.getUri().toString())); + } + + @Test + void rollbackOfCustomAttributeWithNonExistingTermReferenceThrows() { + final CustomAttribute customAttribute = persistTermReferenceCustomAttribute(); + final URI nonExistingTerm = Generator.generateUri(); + setNativePropertyWithoutChangeRecord(customAttribute.getUri(), nonExistingTerm); + + final Set newValue = Set.of(termC.getUri()); + + // apply change and create change record + term.getProperties().put(customAttribute.getUri().toString(), newValue); + term = update(term, termService); + + final UpdateChangeRecord record = getRecord(term); + assertEquals(Set.of(nonExistingTerm), record.getOriginalValue()); + + assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); + + term = termService.findRequired(term.getUri()); + assertEquals(newValue, term.getProperties().get(customAttribute.getUri().toString()), + "The term reference must not change when rollback fails"); + } + + @Test + void rollbackOfCustomAttributeWithUnknownRangeAndUriOriginalValueThrows() { + final CustomAttribute customAttribute = persistUriCustomAttribute(); + customAttribute.setRange(Generator.generateUri()); + dataRepositoryService.updateCustomAttribute(customAttribute); + + // apply change and create change record + term.getProperties().remove(customAttribute.getUri().toString()); + term = update(term, termService); + + final UpdateChangeRecord record = getRecord(term); + assertEquals(Set.of(property), record.getOriginalValue()); + + assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); + } + + private CustomAttribute persistTermReferenceCustomAttribute() { + final CustomAttribute customAttribute = new CustomAttribute(); + customAttribute.setUri(Generator.generateUri()); + customAttribute.setLabel(MultilingualString.create("Term reference", null)); + customAttribute.setDomain(Term_.entityClassIRI.toURI()); + customAttribute.setRange(URI.create(SKOS.CONCEPT)); + dataRepositoryService.persistCustomAttribute(customAttribute); + return customAttribute; + } + + private void setNativePropertyWithoutChangeRecord(URI property, URI value) { + term.getProperties().put(property.toString(), new HashSet<>(Set.of(value))); + transactional(() -> em.merge(term, descriptorFactory.termDescriptor(term))); + term = termService.findRequired(term.getUri()); + } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java index e5db13687..0f039291e 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java @@ -7,6 +7,7 @@ import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import cz.cvut.kbss.termit.service.repository.DataRepositoryService; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -38,6 +39,9 @@ class RollbackValidatorTest { @Mock private ChangeRollbackDao changeRollbackDao; + @Mock + private DataRepositoryService dataRepositoryService; // injected into sut + @Mock private Attribute attribute; From 05c4f6a1ed6148fc26f6fb3f2d078166b9763ab5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 07:27:28 +0200 Subject: [PATCH 12/27] [Test kbss-cvut/termit-ui#790] Add tests for TermController ensuring history is returned with reversible types and rollback endpoint resolves update change record and calls rollback --- .../kbss/termit/rest/TermControllerTest.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) 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 80ddd4d63..d6ee880f0 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java @@ -35,6 +35,7 @@ import cz.cvut.kbss.termit.model.assignment.TermDefinitionSource; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; import cz.cvut.kbss.termit.model.comment.Comment; import cz.cvut.kbss.termit.model.resource.File; import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver; @@ -42,6 +43,7 @@ import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.TermService; import cz.cvut.kbss.termit.service.business.util.TermSelectionParams; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportFormat; import cz.cvut.kbss.termit.service.export.ExportType; @@ -59,6 +61,8 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; @@ -108,6 +112,7 @@ import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -142,6 +147,9 @@ public class TermControllerTest extends BaseControllerTestRunner { @Mock private TermService termServiceMock; + @Mock + private ChangeRollbackService changeRollbackService; + @InjectMocks private TermController sut; @@ -1422,6 +1430,71 @@ void getByIdDoesNotResolvesAllAncestorsByDefault() throws Exception { verify(termServiceMock, never()).resolveAllAncestors(term); } + @ParameterizedTest + @CsvSource({ + "/terms/" + TERM_NAME + "/history", + PATH + VOCABULARY_NAME + "/terms/" + TERM_NAME + "/history" + }) + void getHistoryReturnsRecordsWithReversibleTypes(String endpoint) throws Exception { + final Term term = Generator.generateTerm(); + term.setUri(URI.create(NAMESPACE + TERM_NAME)); + final List changeRecords = generateChangeRecords(term); + + lenient().when(namespaceResolver.resolveNamespace(URI.create(VOCABULARY_URI))).thenReturn(NAMESPACE); + lenient().when(idResolverMock.resolveIdentifier(NAMESPACE, VOCABULARY_NAME)).thenReturn(URI.create(VOCABULARY_URI)); + when(idResolverMock.resolveIdentifier(NAMESPACE, TERM_NAME)).thenReturn(term.getUri()); + when(termServiceMock.findRequired(term.getUri())).thenReturn(term); + when(termServiceMock.getChanges(eq(term), any())).thenReturn(changeRecords); + + mockMvc.perform(get(endpoint) + .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) + .andExpect(status().isOk()); + + verify(changeRollbackService).withReversibleType(changeRecords); + } + + @Test + void rollbackChangeResolvesUpdateChangeRecordAndRollsbackTheChange() throws Exception { + final Term term = Generator.generateTerm(); + term.setUri(URI.create(NAMESPACE + TERM_NAME)); + + final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); + final String recordLocalName = "update" + Generator.randomInt(); + changeRecord.setUri(URI.create(UpdateChangeRecord_.entityClassIRI + "/" + recordLocalName)); + changeRecord.setChangedEntity(term.getUri()); + + when(idResolverMock.resolveIdentifier(NAMESPACE, TERM_NAME)).thenReturn(term.getUri()); + when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); + + mockMvc.perform(post("/terms/{localName}/history/{changeRecord}/rollback", TERM_NAME, recordLocalName) + .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) + .andExpect(status().isNoContent()); + + verify(changeRollbackService).findRecordByLocalName(recordLocalName); + verify(changeRollbackService).rollback(changeRecord); + } + + @Test + void rollbackChangeReturnsUnprocessableContentWhenResolvedChangeRecordDoesNotMatchChangedAsset() throws Exception { + final Term term = Generator.generateTerm(); + term.setUri(URI.create(NAMESPACE + TERM_NAME)); + + final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); + final String recordLocalName = "update" + Generator.randomInt(); + changeRecord.setUri(URI.create(UpdateChangeRecord_.entityClassIRI + "/" + recordLocalName)); + changeRecord.setChangedEntity(Generator.generateUri()); + + when(idResolverMock.resolveIdentifier(NAMESPACE, TERM_NAME)).thenReturn(term.getUri()); + when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); + + mockMvc.perform(post("/terms/{localName}/history/{changeRecord}/rollback", TERM_NAME, recordLocalName) + .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) + .andExpect(status().isUnprocessableContent()); + + verify(changeRollbackService).findRecordByLocalName(recordLocalName); + verify(changeRollbackService, never()).rollback(any()); + } + public static class TermSelectionParamsBuilder { private boolean flat = false; private boolean includeImported = false; From d936d990eb62cdb6d42a797e951a0d50a0764d30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 07:31:32 +0200 Subject: [PATCH 13/27] [Enhancement kbss-cvut/termit-ui#790] Include reversible types for change records from VocabularyController --- .../java/cz/cvut/kbss/termit/rest/VocabularyController.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java index e470be7c9..a23601a8a 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java @@ -320,7 +320,9 @@ public List getHistory( final Vocabulary vocabulary = vocabularyService.getReference( resolveVocabularyUri(localName, namespace)); final ChangeRecordFilterDto filterDto = new ChangeRecordFilterDto(changedAttributeName, authorName, changeType); - return vocabularyService.getChanges(vocabulary, filterDto); + List records = vocabularyService.getChanges(vocabulary, filterDto); + changeRollbackService.withReversibleType(records); + return records; } /** From b89839f53cc892e247f5e8b301be6085d5572d5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 07:53:18 +0200 Subject: [PATCH 14/27] [Docs] Add missing api response documentation for rollback change endpoints in TermController and VocabularyController --- src/main/java/cz/cvut/kbss/termit/rest/TermController.java | 3 ++- .../java/cz/cvut/kbss/termit/rest/VocabularyController.java | 3 ++- 2 files changed, 4 insertions(+), 2 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 7b98b0673..c296b9366 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -908,7 +908,8 @@ public List getHistory(@Parameter(description = ApiDoc.ID_ description = "Rolls back the specified update change record of the term.") @ApiResponses({ @ApiResponse(responseCode = "204", description = "Change successfully rolled back."), - @ApiResponse(responseCode = "404", description = "Term or update change record not found.") + @ApiResponse(responseCode = "404", description = "Term or update change record not found."), + @ApiResponse(responseCode = "422", description = "When the change record is associated with a different asset") }) @PostMapping("/terms/{localName}/history/{changeRecord}/rollback") @ResponseStatus(HttpStatus.NO_CONTENT) diff --git a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java index a23601a8a..b7b7f73ed 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java @@ -299,7 +299,8 @@ private URI resolveVocabularyUri(String fragment, Optional namespace) { description = "Gets a list of changes made to metadata of vocabulary with the specified identifier.") @ApiResponses({ @ApiResponse(responseCode = "200", description = "List of change records."), - @ApiResponse(responseCode = "404", description = ApiDoc.ID_NOT_FOUND_DESCRIPTION) + @ApiResponse(responseCode = "404", description = ApiDoc.ID_NOT_FOUND_DESCRIPTION), + @ApiResponse(responseCode = "422", description = "When the change record is associated with a different asset") }) @GetMapping(value = "/{localName}/history", produces = {MediaType.APPLICATION_JSON_VALUE, JsonLd.MEDIA_TYPE}) From 1d69e179c9ff10e69936059b51def91f67155169 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 07:56:37 +0200 Subject: [PATCH 15/27] [Test kbss-cvut/termit-ui#790] Add tests for VocabularyController ensuring history is returned with reversible types and rollback endpoint resolves update change record and calls rollback --- .../termit/rest/VocabularyControllerTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java index 641547948..a1b90a039 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java @@ -27,6 +27,7 @@ import cz.cvut.kbss.termit.environment.Generator; import cz.cvut.kbss.termit.exception.AssetRemovalException; import cz.cvut.kbss.termit.exception.importing.VocabularyImportException; +import cz.cvut.kbss.termit.model.Asset; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.User; import cz.cvut.kbss.termit.model.Vocabulary; @@ -35,9 +36,11 @@ import cz.cvut.kbss.termit.model.acl.AccessLevel; import cz.cvut.kbss.termit.model.acl.UserAccessControlRecord; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.rest.handler.ErrorInfo; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.VocabularyService; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; @@ -105,6 +108,9 @@ class VocabularyControllerTest extends BaseControllerTestRunner { @Mock private VocabularyService serviceMock; + @Mock + private ChangeRollbackService changeRollbackService; + @Mock private IdentifierResolver idResolverMock; @@ -717,4 +723,70 @@ void reImportVocabularyRunsTermTranslationsImportForUploadedFileWhenTranslations containsString(QueryParams.NAMESPACE + "=" + NAMESPACE)); verify(serviceMock).importTermTranslations(vocabulary.getUri(), upload); } + + private UpdateChangeRecord generateChangeRecord(Asset changedAsset) { + final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); + changeRecord.setUri(Generator.generateUri()); + changeRecord.setChangedEntity(changedAsset.getUri()); + return changeRecord; + } + + @Test + void getHistoryReturnsRecordsWithReversibleTypes() throws Exception { + final Vocabulary vocabulary = Generator.generateVocabulary(); + vocabulary.setUri(URI.create(NAMESPACE + FRAGMENT)); + + final List changeRecords = List.of(generateChangeRecord(vocabulary), generateChangeRecord(vocabulary)); + + when(idResolverMock.resolveIdentifier(NAMESPACE, FRAGMENT)).thenReturn(vocabulary.getUri()); + when(serviceMock.getReference(vocabulary.getUri())).thenReturn(vocabulary); + when(serviceMock.getChanges(eq(vocabulary), any())).thenReturn(changeRecords); + + mockMvc.perform(get(PATH + "/{localName}/history", FRAGMENT) + .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) + .andExpect(status().isOk()); + + verify(serviceMock).getChanges(eq(vocabulary), any()); + verify(changeRollbackService).withReversibleType(changeRecords); + } + + @Test + void rollbackChangeResolvesUpdateChangeRecordAndRollsbackTheChange() throws Exception { + final Vocabulary vocabulary = Generator.generateVocabulary(); + vocabulary.setUri(URI.create(NAMESPACE + FRAGMENT)); + + final UpdateChangeRecord changeRecord = generateChangeRecord(vocabulary); + final String recordLocalName = IdentifierResolver.extractIdentifierFragment(changeRecord.getUri()); + + when(idResolverMock.resolveIdentifier(NAMESPACE, FRAGMENT)).thenReturn(vocabulary.getUri()); + when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); + + mockMvc.perform(post(PATH + "/{localName}/history/{changeRecord}/rollback", FRAGMENT, recordLocalName) + .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) + .andExpect(status().isNoContent()); + + verify(changeRollbackService).findRecordByLocalName(recordLocalName); + verify(changeRollbackService).rollback(changeRecord); + } + + @Test + void rollbackChangeReturnsUnprocessableContentWhenResolvedChangeRecordDoesNotMatchChangedAsset() throws Exception { + final Vocabulary vocabulary = Generator.generateVocabulary(); + vocabulary.setUri(URI.create(NAMESPACE + FRAGMENT)); + + final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); + changeRecord.setUri(Generator.generateUri()); + changeRecord.setChangedEntity(Generator.generateUri()); + final String recordLocalName = IdentifierResolver.extractIdentifierFragment(changeRecord.getUri()); + + when(idResolverMock.resolveIdentifier(NAMESPACE, FRAGMENT)).thenReturn(vocabulary.getUri()); + when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); + + mockMvc.perform(post(PATH + "/{localName}/history/{changeRecord}/rollback", FRAGMENT, recordLocalName) + .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) + .andExpect(status().isUnprocessableContent()); + + verify(changeRollbackService).findRecordByLocalName(recordLocalName); + verify(changeRollbackService, never()).rollback(any()); + } } From 2b32015de61c548ea9ced146245a9168952c0551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 08:36:25 +0200 Subject: [PATCH 16/27] [Test kbss-cvut/termit-ui#790] Add tests for ChangeRollbackService#withReversibleType method --- .../changetracking/ChangeRollbackService.java | 33 ++++++++++ .../ChangeRollbackServiceTest.java | 63 +++++++++++++++++++ 2 files changed, 96 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index 8303ed73e..c4397b231 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -181,6 +181,13 @@ private Class> resolveEntityClass(Asset asset) { throw unsupportedAssetType(asset); } + /** + * Resolves the changed asset entity. + * + * @param record the change record + * @return the changed asset + * @throws UpdateChangeRecordRollbackException when the asset was not found or is unsupported type + */ private Asset resolveChangedAssetRequired(UpdateChangeRecord record) { final Asset changedAsset = resolveChangedAsset(record); if (changedAsset == null) { @@ -190,6 +197,12 @@ private Asset resolveChangedAssetRequired(UpdateChangeRecord record) { return changedAsset; } + /** + * Tries to find {@link Vocabulary} or {@link Term} by the changed asset identifier. + * + * @param record the change record + * @return the resolved changed asset or {@code null} + */ private Asset resolveChangedAsset(AbstractChangeRecord record) { Optional vocabulary = vocabularyService.find(record.getChangedEntity()); if (vocabulary.isPresent()) { @@ -202,12 +215,26 @@ private Asset resolveChangedAsset(AbstractChangeRecord record) { return null; } + /** + * Ensures the current user is authorized to modify the specified asset. + * + * @param asset the asset to be modified + * @throws AccessDeniedException when the modification of the given asset is not authorized. + * @see #isModificationAuthorized(Asset) + */ private void ensureModificationAuthorized(Asset asset) { if (!isModificationAuthorized(asset)) { throw new AccessDeniedException("Not authorized to roll back changes to the asset."); } } + /** + * Checks whether the current user is authorized to modify the specified {@link Vocabulary} or {@link Term}. + * + * @param asset the asset to be modified + * @return {@code true} when the specified asset is {@link Vocabulary} or {@link Term} + * and the current user is authorized for its modification, {@code false} otherwise. + */ private boolean isModificationAuthorized(Asset asset) { if (asset instanceof Term term) { return termAuthorizationService.canModify(term); @@ -218,6 +245,12 @@ private boolean isModificationAuthorized(Asset asset) { return false; } + /** + * Updates the given asset using respective repository service. + * + * @param asset the asset to update + * @throws UpdateChangeRecordRollbackException when the asset is not {@link Term} or {@link Vocabulary} + */ private void updateChangedAsset(Asset asset) { if (asset instanceof Term term) { termService.update(term); diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java index 9e0e036cf..8364610d9 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java @@ -20,6 +20,8 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.access.AccessDeniedException; +import java.util.HashSet; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -27,6 +29,9 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @@ -143,11 +148,69 @@ void rollbackThrowsWhenUserIsNotAuthorizedToModifyVocabulary() { assertThrows(AccessDeniedException.class, () -> sut.rollback(record)); } + private static final String WITH_REVERSIBLE_CSV_SOURCE = """ + # can be rolled back and user is authorized -> is reversible + true, true, true + # can not be rolled back, user is authorized -> is not reversible + false, true, false + # can be rolled back, user is not authorized -> is not reversible + true, false, false + # can not be rolled back, user is not authorized -> is not reversible + false, false, false + """; + + @ParameterizedTest + @CsvSource(textBlock = WITH_REVERSIBLE_CSV_SOURCE) + void withReversibleTypeAddsReversibleTypeToReversibleVocabularyChange(boolean canRollback, boolean canModify, boolean expectedIsReversible) { + final Vocabulary vocabulary = Generator.generateVocabularyWithId(); + final UpdateChangeRecord record = recordFor(vocabulary); + + when (vocabularyService.find(vocabulary.getUri())).thenReturn(Optional.of(vocabulary)); + lenient().when(rollbackValidator.canRollback(record, Vocabulary.class)).thenReturn(canRollback); + when(vocabularyAuthorizationService.canModify(vocabulary)).thenReturn(canModify); + + assertFalse(record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); + sut.withReversibleType(List.of(record)); + final boolean isReversibleResult = record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + assertEquals(expectedIsReversible, isReversibleResult); + + if (canModify) { + verify(rollbackValidator).canRollback(record, Vocabulary.class); + } + verify(vocabularyAuthorizationService).canModify(vocabulary); + verifyNoMoreInteractions(rollbackValidator); + verifyNoMoreInteractions(vocabularyAuthorizationService); + } + + @ParameterizedTest + @CsvSource(textBlock = WITH_REVERSIBLE_CSV_SOURCE) + void withReversibleTypeAddsReversibleTypeToReversibleTermChange(boolean canRollback, boolean canModify, boolean expectedIsReversible) { + final Term term = Generator.generateTermWithId(); + final UpdateChangeRecord record = recordFor(term); + + when (termService.find(term.getUri())).thenReturn(Optional.of(term)); + lenient().when(rollbackValidator.canRollback(record, Term.class)).thenReturn(canRollback); + when(termAuthorizationService.canModify(term)).thenReturn(canModify); + + assertFalse(record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); + sut.withReversibleType(List.of(record)); + final boolean isReversibleResult = record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + assertEquals(expectedIsReversible, isReversibleResult); + + if (canModify) { + verify(rollbackValidator).canRollback(record, Term.class); + } + verify(termAuthorizationService).canModify(term); + verifyNoMoreInteractions(rollbackValidator); + verifyNoMoreInteractions(termAuthorizationService); + } + private static UpdateChangeRecord recordFor(Asset asset) { final UpdateChangeRecord record = new UpdateChangeRecord(asset); record.setChangedAttribute(Generator.generateUri()); record.setOriginalValue(Set.of("original")); record.setNewValue(Set.of("updated")); + record.setTypes(new HashSet<>()); return record; } } From 33ea5c898c1d67505b8e376f42247a46b2bf885f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 08:49:45 +0200 Subject: [PATCH 17/27] [Test kbss-cvut/termit-ui#790] Add test for ChangeRollbackService#findRecordByLocalName method --- .../ChangeRollbackServiceTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java index 8364610d9..35eb68e19 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java @@ -6,7 +6,10 @@ import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import cz.cvut.kbss.termit.service.IdentifierResolver; +import cz.cvut.kbss.termit.service.repository.ChangeRecordService; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; import cz.cvut.kbss.termit.service.repository.VocabularyRepositoryService; import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; @@ -15,11 +18,13 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.access.AccessDeniedException; +import java.net.URI; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -55,6 +60,12 @@ class ChangeRollbackServiceTest { @Mock private VocabularyAuthorizationService vocabularyAuthorizationService; + @Mock(answer = Answers.CALLS_REAL_METHODS) + private IdentifierResolver identifierResolver; + + @Mock + private ChangeRecordService changeRecordService; + @InjectMocks private ChangeRollbackService sut; @@ -205,6 +216,16 @@ void withReversibleTypeAddsReversibleTypeToReversibleTermChange(boolean canRollb verifyNoMoreInteractions(termAuthorizationService); } + @Test + void findRecordByLocalNameResolvesIdentifierUsingUpdateChangeRecordNamespace() { + final String recordLocalName = "updateRecord" + Generator.randomInt(); + final URI expectedRecordUri = URI.create(UpdateChangeRecord_.entityClassIRI + "/" + recordLocalName); + + sut.findRecordByLocalName(recordLocalName); + + verify(changeRecordService).findUpdateRequired(expectedRecordUri); + } + private static UpdateChangeRecord recordFor(Asset asset) { final UpdateChangeRecord record = new UpdateChangeRecord(asset); record.setChangedAttribute(Generator.generateUri()); From 4e05d4a87a353820fbf28a2ee388caa68f239107 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 09:06:16 +0200 Subject: [PATCH 18/27] [Test kbss-cvut/termit-ui#790] Add tests for DataRepositoryService#findCustomAttribute and ChangeRecordDao#find --- .../changetracking/ChangeRecordDaoTest.java | 23 +++++++++++++++++++ .../repository/DataRepositoryServiceTest.java | 10 ++++++++ 2 files changed, 33 insertions(+) diff --git a/src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDaoTest.java b/src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDaoTest.java index 0ba71c1d8..e3835a09d 100644 --- a/src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDaoTest.java +++ b/src/test/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRecordDaoTest.java @@ -67,6 +67,7 @@ import static org.hamcrest.Matchers.empty; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) @@ -548,4 +549,26 @@ void findAllRelatedToTypeReturnsRecordsOfExistingTermFilteredByChangeType(Class< assertTrue(contentChanges.stream().allMatch(typeClass::isInstance)); } + @Test + void findRetrievesChangeRecordOfSpecifiedTypeAndIdentifier() { + final UpdateChangeRecord record = generateUpdateRecord(Utils.timestamp(), vocabulary.getUri()); + transactional(() -> sut.persist(record, vocabulary)); + + final Optional result = sut.find(UpdateChangeRecord.class, record.getUri()); + assertTrue(result.isPresent()); + assertEquals(record.getUri(), result.get().getUri()); + assertEquals(record.getChangedAttribute(), result.get().getChangedAttribute()); + } + + @Test + void findReturnsEmptyOptionalForUnknownIdentifier() { + final Optional result = sut.find(UpdateChangeRecord.class, Generator.generateUri()); + + assertTrue(result.isEmpty()); + } + + @Test + void findRejectsNullIdentifier() { + assertThrows(NullPointerException.class, () -> sut.find(UpdateChangeRecord.class, null)); + } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java index 91214af25..f4242cee0 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/DataRepositoryServiceTest.java @@ -121,6 +121,16 @@ void persistCustomAttributeThrowsValidationExceptionWhenLabelIsEmpty() { assertThrows(ValidationException.class, () -> sut.persistCustomAttribute(customAttribute)); } + @Test + void findCustomAttributeReturnsMatchingAttribute() { + final URI uri = Generator.generateUri(); + final CustomAttribute attribute = new CustomAttribute(); + attribute.setUri(uri); + when(dataDao.findCustomAttribute(uri)).thenReturn(Optional.of(attribute)); + + assertEquals(Optional.of(attribute), sut.findCustomAttribute(uri)); + } + @Test void updateCustomAttributeUpdatesLabelAndDescriptionOfExistingCustomAttribute() { final CustomAttribute existing = new CustomAttribute(Generator.generateUri(), From 408e9098b84da66d015f064bfaf8c68fb1bd55f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 09:39:20 +0200 Subject: [PATCH 19/27] [Test kbss-cvut/termit-ui#790] Add security tests to change rollback service integration tests --- .../ChangeRollbackIntegrationTest.java | 68 +++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java index 917be36d0..e32be608b 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java @@ -16,6 +16,8 @@ import cz.cvut.kbss.termit.model.User; import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.Vocabulary_; +import cz.cvut.kbss.termit.model.acl.AccessLevel; +import cz.cvut.kbss.termit.model.acl.UserAccessControlRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; import cz.cvut.kbss.termit.persistence.context.DescriptorFactory; @@ -30,6 +32,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.AccessDeniedException; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; @@ -37,6 +40,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Set; +import java.util.function.Supplier; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -147,6 +151,70 @@ private > T update(T entity, RudService service) { return service.findRequired(entity.getUri()); } + private User createUser(UserRole role) { + final User user = Generator.generateUserWithId(); + user.setTypes(new HashSet<>(Set.of(role.getType()))); + transactional(() -> em.persist(user)); + return user; + } + + private void grantAccess(User user, AccessLevel accessLevel) { + vocabularyService.addAccessControlRecords(vocabulary, new UserAccessControlRecord(accessLevel, user)); + } + + /** + * Asserts that user with read access cannot execute rollback, while user with write access can. + * + * @param record the change record + * @param originalValue the original attribute value + * @param updatedValue the new attribute value after change + * @param readValue supplier of the current attribute value + * @param The type of the attribute value + */ + private void assertRollbackRequiresWriteAccess(UpdateChangeRecord record, T originalValue, T updatedValue, + Supplier readValue) { + final User reader = createUser(UserRole.RESTRICTED_USER); + final User writer = createUser(UserRole.FULL_USER); + grantAccess(reader, AccessLevel.READ); + grantAccess(writer, AccessLevel.WRITE); + + // assert reader cannot rollback + Environment.setCurrentUser(reader); + assertThrows(AccessDeniedException.class, () -> sut.rollback(record)); + // assert nothing changed + assertEquals(updatedValue, readValue.get()); + + // assert writer can do rollback + Environment.setCurrentUser(writer); + sut.rollback(record); + // value rolled back to original + assertEquals(originalValue, readValue.get()); + } + + @Test + void vocabularyRollbackRequiresWriteAccess() { + final MultilingualString originalLabel = makeCopy(vocabulary.getLabel()); + vocabulary.setLabel(Environment.LANGUAGE, "updated vocabulary label"); + vocabulary = update(vocabulary, vocabularyService); + final MultilingualString updatedLabel = makeCopy(vocabulary.getLabel()); + final UpdateChangeRecord record = getRecord(vocabulary); + + assertRollbackRequiresWriteAccess(record, originalLabel, updatedLabel, + () -> vocabularyService.findRequired(vocabulary.getUri()).getLabel()); + } + + @Test + void termRollbackUsesContainingVocabularyWriteAccess() { + term.getProperties().get(property.toString()).add("updated value"); + term = update(term, termService); + final Set updatedValues = Set.copyOf(term.getProperties().get(property.toString())); + final UpdateChangeRecord record = getRecord(term); + + assertRollbackRequiresWriteAccess(record, originalPropertyValue, updatedValues, + () -> termService.findRequired(term.getUri()).getProperties() + .get(property.toString())); + } + @Test void rollbackVocabularyLabelPersistsOriginalValue() { final MultilingualString originalValue = makeCopy(vocabulary.getLabel()); From 8a041356ed444a1af19d52a54814894d2bb43145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Wed, 23 Sep 2026 12:08:40 +0200 Subject: [PATCH 20/27] [Test kbss-cvut/termit-ui#790] Add test ensuring that rollback of multilingual string does not discard other transaltions --- .../changetracking/ChangeRollbackService.java | 5 +++ .../ChangeRollbackIntegrationTest.java | 31 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index c4397b231..81b3960ec 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -17,6 +17,8 @@ import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; import cz.cvut.kbss.termit.service.security.authorization.VocabularyAuthorizationService; import cz.cvut.kbss.termit.util.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -30,6 +32,7 @@ */ @Service public class ChangeRollbackService { + private static final Logger LOG = LoggerFactory.getLogger(ChangeRollbackService.class); private final RollbackValidator rollbackValidator; private final ChangeRollbackDao rollbackDao; private final ChangeRecordService changeRecordService; @@ -156,12 +159,14 @@ public UpdateChangeRecord findRecordByLocalName(String recordLocalName) { private void doRollback(UpdateChangeRecord record, Asset changedAsset) { final Class> entityClass = resolveEntityClass(changedAsset); final Attribute classAttribute = rollbackDao.resolveClassAttribute(entityClass, record).orElse(null); + LOG.info("Rolling back change record {} of entity {}", record, entityClass); if (classAttribute != null) { rollbackDao.rollbackClassAttribute(record.getOriginalValue(), changedAsset, classAttribute); } else { rollbackDao.rollbackNativeProperty(record.getOriginalValue(), changedAsset, record.getChangedAttribute()); } updateChangedAsset(changedAsset); + LOG.info("Rolled back change record {} of entity {}", record, entityClass); } /** diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java index e32be608b..579e9f6df 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java @@ -424,6 +424,37 @@ void rollbackOfCustomAttributeWithUnknownRangeAndUriOriginalValueThrows() { assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); } + @Test + void rollbackOfMultilingualStringPreservesOtherTranslations() { + final String originalEn = "Original English description"; + final String originalCs = "PĹŻvodnĂ­ ÄŤeskĂ˝ popis"; + final String updatedEn = "Updated English description"; + term.getDescription().set("en", originalEn); + term.getDescription().set("cs", originalCs); + + transactional(() -> em.merge(term, descriptorFactory.termDescriptor(term))); + term = termService.findRequired(term.getUri()); + final MultilingualString originalDescription = makeCopy(term.getDescription()); + + // apply change and create change record + term.getDescription().set("en", updatedEn); + term = update(term, termService); + assertEquals(updatedEn, term.getDescription().get("en")); + assertEquals(originalCs, term.getDescription().get("cs")); + + final UpdateChangeRecord record = getRecord(term); + assertEquals(Term_.descriptionPropertyIRI.toURI(), record.getChangedAttribute()); + assertEquals(originalDescription, record.getOriginalValue()); + assertEquals(term.getDescription(), record.getNewValue()); + + sut.rollback(record); + + final Term rolledBackTerm = termService.findRequired(term.getUri()); + assertEquals(originalDescription, rolledBackTerm.getDescription()); + assertEquals(originalEn, rolledBackTerm.getDescription().get("en")); + assertEquals(originalCs, rolledBackTerm.getDescription().get("cs")); + } + private CustomAttribute persistTermReferenceCustomAttribute() { final CustomAttribute customAttribute = new CustomAttribute(); customAttribute.setUri(Generator.generateUri()); From def14fb614b72f7fc6c0a69b8e2c563915af189c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Tue, 29 Sep 2026 12:53:33 +0200 Subject: [PATCH 21/27] [Test] Verify new jopa version is merging multilingual strings as expected and fix rollbackOfMultilingualStringPreservesOtherTranslations test asserting equality of different object types --- .../service/changetracking/ChangeRollbackIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java index 579e9f6df..2ce465395 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java @@ -444,8 +444,8 @@ void rollbackOfMultilingualStringPreservesOtherTranslations() { final UpdateChangeRecord record = getRecord(term); assertEquals(Term_.descriptionPropertyIRI.toURI(), record.getChangedAttribute()); - assertEquals(originalDescription, record.getOriginalValue()); - assertEquals(term.getDescription(), record.getNewValue()); + assertEquals(Set.of(originalDescription), record.getOriginalValue()); + assertEquals(Set.of(term.getDescription()), record.getNewValue()); sut.rollback(record); From f8286e69be02eaf15a94b80e3645ab31d4ede65d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 1 Oct 2026 08:44:45 +0200 Subject: [PATCH 22/27] [Ref] Inline optional null resolution in ChangeRollbackService --- .../termit/service/changetracking/ChangeRollbackService.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index 81b3960ec..bf247e887 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -214,10 +214,7 @@ private Asset resolveChangedAsset(AbstractChangeRecord record) { return vocabulary.get(); } Optional term = termService.find(record.getChangedEntity()); - if (term.isPresent()) { - return term.get(); - } - return null; + return term.orElse(null); } /** From 92bae3a3b5fbc932a17196183301821389cc6d2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 1 Oct 2026 09:48:41 +0200 Subject: [PATCH 23/27] [Ref] Remove find and findRequired methods from ChangeRecordService and call ChangeRecordDao directly from ChangeRollbackService --- .../changetracking/ChangeRollbackService.java | 14 ++++--- .../repository/ChangeRecordService.java | 39 ------------------- 2 files changed, 8 insertions(+), 45 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index bf247e887..0e6d97227 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -1,6 +1,7 @@ package cz.cvut.kbss.termit.service.changetracking; import cz.cvut.kbss.jopa.model.metamodel.Attribute; +import cz.cvut.kbss.termit.exception.NotFoundException; import cz.cvut.kbss.termit.exception.UpdateChangeRecordRollbackException; import cz.cvut.kbss.termit.model.Asset; import cz.cvut.kbss.termit.model.Term; @@ -9,9 +10,9 @@ import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; import cz.cvut.kbss.termit.model.util.HasProperties; +import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRecordDao; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; import cz.cvut.kbss.termit.service.IdentifierResolver; -import cz.cvut.kbss.termit.service.repository.ChangeRecordService; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; import cz.cvut.kbss.termit.service.repository.VocabularyRepositoryService; import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; @@ -35,29 +36,29 @@ public class ChangeRollbackService { private static final Logger LOG = LoggerFactory.getLogger(ChangeRollbackService.class); private final RollbackValidator rollbackValidator; private final ChangeRollbackDao rollbackDao; - private final ChangeRecordService changeRecordService; private final TermRepositoryService termService; private final VocabularyRepositoryService vocabularyService; private final TermAuthorizationService termAuthorizationService; private final VocabularyAuthorizationService vocabularyAuthorizationService; private final IdentifierResolver identifierResolver; + private final ChangeRecordDao changeRecordDao; public ChangeRollbackService(RollbackValidator rollbackValidator, ChangeRollbackDao rollbackDao, - ChangeRecordService changeRecordService, TermRepositoryService termService, VocabularyRepositoryService vocabularyService, TermAuthorizationService termAuthorizationService, VocabularyAuthorizationService vocabularyAuthorizationService, - IdentifierResolver identifierResolver) { + IdentifierResolver identifierResolver, + ChangeRecordDao changeRecordDao) { this.rollbackValidator = rollbackValidator; this.rollbackDao = rollbackDao; - this.changeRecordService = changeRecordService; this.termService = termService; this.vocabularyService = vocabularyService; this.termAuthorizationService = termAuthorizationService; this.vocabularyAuthorizationService = vocabularyAuthorizationService; this.identifierResolver = identifierResolver; + this.changeRecordDao = changeRecordDao; } /** @@ -145,7 +146,8 @@ public void rollback(UpdateChangeRecord record) { */ public UpdateChangeRecord findRecordByLocalName(String recordLocalName) { final URI recordUri = identifierResolver.resolveIdentifier(UpdateChangeRecord_.entityClassIRI.toString(), recordLocalName); - return changeRecordService.findUpdateRequired(recordUri); + return changeRecordDao.find(UpdateChangeRecord.class, recordUri) + .orElseThrow(()-> new NotFoundException("UpdateChangeRecord not found")); } /** diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java index 71c275f6e..ad09428ad 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java @@ -18,20 +18,16 @@ package cz.cvut.kbss.termit.service.repository; import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; -import cz.cvut.kbss.termit.exception.NotFoundException; import cz.cvut.kbss.termit.model.Asset; import cz.cvut.kbss.termit.model.User; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; -import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRecordDao; import cz.cvut.kbss.termit.service.changetracking.ChangeRecordProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.net.URI; import java.util.List; -import java.util.Optional; import java.util.Set; @Service @@ -62,39 +58,4 @@ public List getChanges(Asset asset, ChangeRecordFilterD public Set getAuthors(HasIdentifier asset) { return changeRecordDao.getAuthors(asset); } - - /** - * Finds an update change record with the specified identifier. - * - * @param recordUri Change record identifier - * @return Matching update change record - * @throws NotFoundException If no matching record is found - */ - public UpdateChangeRecord findUpdateRequired(URI recordUri) { - return findRequired(UpdateChangeRecord.class, recordUri); - } - - /** - * Finds a change record of the specified type and identifier. - * - * @param recordClass Change record type - * @param recordUri Change record identifier - * @return Matching change record - * @throws NotFoundException If no matching record is found - */ - private T findRequired(Class recordClass, URI recordUri) { - return find(recordClass, recordUri) - .orElseThrow(()-> new NotFoundException(recordClass.getSimpleName() + " not found")); - } - - /** - * Finds a change record of the specified type and identifier. - * - * @param recordClass Change record type - * @param recordUri Change record identifier - * @return Matching record, or an empty optional if none is found - */ - private Optional find(Class recordClass, URI recordUri) { - return changeRecordDao.find(recordClass, recordUri); - } } From 7a959748c0a241d661797eeb3fb9c590eeec1b58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 1 Oct 2026 11:33:41 +0200 Subject: [PATCH 24/27] [Ref] Extract update change record rollback endpoints to RollbackController --- .../kbss/termit/rest/RollbackController.java | 94 ++++++++++++++++ .../cvut/kbss/termit/rest/TermController.java | 38 ------- .../termit/rest/VocabularyController.java | 37 ------- .../termit/rest/RollbackControllerTest.java | 103 ++++++++++++++++++ .../kbss/termit/rest/TermControllerTest.java | 43 -------- .../termit/rest/VocabularyControllerTest.java | 40 ------- .../ChangeRollbackServiceTest.java | 8 +- 7 files changed, 202 insertions(+), 161 deletions(-) create mode 100644 src/main/java/cz/cvut/kbss/termit/rest/RollbackController.java create mode 100644 src/test/java/cz/cvut/kbss/termit/rest/RollbackControllerTest.java diff --git a/src/main/java/cz/cvut/kbss/termit/rest/RollbackController.java b/src/main/java/cz/cvut/kbss/termit/rest/RollbackController.java new file mode 100644 index 000000000..67de19336 --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/rest/RollbackController.java @@ -0,0 +1,94 @@ +package cz.cvut.kbss.termit.rest; + +import cz.cvut.kbss.termit.exception.InvalidParameterException; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.security.SecurityConstants; +import cz.cvut.kbss.termit.service.IdentifierResolver; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; +import cz.cvut.kbss.termit.util.Configuration; +import cz.cvut.kbss.termit.util.Constants.QueryParams; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import java.net.URI; + +@Tag(name = "Rollback", description = "Change rollback API") +@RestController +@RequestMapping("/") +@PreAuthorize("hasRole('" + SecurityConstants.ROLE_RESTRICTED_USER + "')") +public class RollbackController extends BaseController { + private static final Logger LOG = LoggerFactory.getLogger(RollbackController.class); + + private final ChangeRollbackService changeRollbackService; + + @Autowired + public RollbackController(IdentifierResolver idResolver, Configuration config, + ChangeRollbackService changeRollbackService) { + super(idResolver, config); + this.changeRollbackService = changeRollbackService; + } + + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, + description = "Rolls back the specified update change record of the vocabulary.") + @ApiResponses({ + @ApiResponse(responseCode = "204", description = "Change successfully rolled back."), + @ApiResponse(responseCode = "404", description = "Vocabulary or update change record not found."), + @ApiResponse(responseCode = "422", description = "When the change record is associated with a different asset") + }) + @PostMapping("/vocabularies/{localName}/history/{changeRecord}/rollback") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void rollbackVocabulary(@Parameter(description = VocabularyController.ApiDoc.ID_LOCAL_NAME_DESCRIPTION, + example = VocabularyController.ApiDoc.ID_LOCAL_NAME_EXAMPLE) + @PathVariable String localName, + @Parameter(description = VocabularyController.ApiDoc.ID_NAMESPACE_DESCRIPTION, + example = VocabularyController.ApiDoc.ID_NAMESPACE_EXAMPLE) + @RequestParam(name = QueryParams.NAMESPACE) String namespace, + @Parameter(description = "Local name of the update change record to roll back.") + @PathVariable String changeRecord) { + final URI vocabularyUri = resolveIdentifier(namespace, localName); + rollback(vocabularyUri, changeRecord, "Vocabulary"); + } + + @Operation(security = {@SecurityRequirement(name = "bearer-key")}, + description = "Rolls back the specified update change record of the term.") + @ApiResponses({ + @ApiResponse(responseCode = "204", description = "Change successfully rolled back."), + @ApiResponse(responseCode = "404", description = "Term or update change record not found."), + @ApiResponse(responseCode = "422", description = "When the change record is associated with a different asset") + }) + @PostMapping("/terms/{localName}/history/{changeRecord}/rollback") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void rollbackTerm( + @Parameter(description = TermController.ApiDoc.ID_LOCAL_NAME_DESCRIPTION, example = TermController.ApiDoc.ID_LOCAL_NAME_EXAMPLE) + @PathVariable String localName, + @PathVariable String changeRecord, + @Parameter(description = TermController.ApiDoc.ID_NAMESPACE_DESCRIPTION, example = TermController.ApiDoc.ID_NAMESPACE_EXAMPLE) + @RequestParam(name = QueryParams.NAMESPACE) String namespace) { + final URI termUri = resolveIdentifier(namespace, localName); + rollback(termUri, changeRecord, "Term"); + } + + private void rollback(URI entityUri, String changeRecord, String entityType) { + final UpdateChangeRecord record = changeRollbackService.findRecordByLocalName(changeRecord); + if (!entityUri.equals(record.getChangedEntity())) { + throw new InvalidParameterException("Record not associated with specified " + entityType); + } + changeRollbackService.rollback(record); + LOG.debug("Change record {} of {} <{}> rolled back.", changeRecord, entityType.toLowerCase(), entityUri); + } +} 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 c296b9366..301f153ce 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -22,14 +22,12 @@ import cz.cvut.kbss.termit.dto.TermInfo; import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; import cz.cvut.kbss.termit.dto.listing.TermDto; -import cz.cvut.kbss.termit.exception.InvalidParameterException; 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.model.assignment.TermDefinitionSource; import cz.cvut.kbss.termit.model.assignment.TermOccurrence; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; -import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.comment.Comment; import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver; import cz.cvut.kbss.termit.rest.doc.ApiDocConstants; @@ -896,42 +894,6 @@ public List getHistory(@Parameter(description = ApiDoc.ID_ return records; } - /** - * Rolls back the specified update change record of a term. - * - * @param localName Term local name - * @param namespace Term identifier namespace - * @param changeRecord Local name of the update change record - * @throws InvalidParameterException If the change record is not associated with the specified term - */ - @Operation(security = {@SecurityRequirement(name = "bearer-key")}, - description = "Rolls back the specified update change record of the term.") - @ApiResponses({ - @ApiResponse(responseCode = "204", description = "Change successfully rolled back."), - @ApiResponse(responseCode = "404", description = "Term or update change record not found."), - @ApiResponse(responseCode = "422", description = "When the change record is associated with a different asset") - }) - @PostMapping("/terms/{localName}/history/{changeRecord}/rollback") - @ResponseStatus(HttpStatus.NO_CONTENT) - public void rollbackChange( - @Parameter(description = ApiDoc.ID_STANDALONE_LOCAL_NAME_DESCRIPTION, - example = ApiDoc.ID_TERM_LOCAL_NAME_EXAMPLE) - @PathVariable String localName, - @Parameter(description = ApiDoc.ID_STANDALONE_NAMESPACE_DESCRIPTION, - example = ApiDoc.ID_STANDALONE_NAMESPACE_EXAMPLE) - @RequestParam(name = QueryParams.NAMESPACE) String namespace, - @Parameter(description = "Local name of the update change record to roll back.") - @PathVariable String changeRecord) { - final URI termUri = idResolver.resolveIdentifier(namespace, localName); - final UpdateChangeRecord recordToRollback = changeRollbackService.findRecordByLocalName(changeRecord); - if (termUri.equals(recordToRollback.getChangedEntity())) { - changeRollbackService.rollback(recordToRollback); - LOG.debug("Change record {} of term {} rolled back.", changeRecord, Utils.uriToString(termUri)); - } else { - throw new InvalidParameterException("Record not associated with specified Term"); - } - } - @Operation(security = {@SecurityRequirement(name = "bearer-key")}, description = "Gets a list of comments on 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/rest/VocabularyController.java b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java index b7b7f73ed..81adbfddf 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java @@ -24,13 +24,11 @@ import cz.cvut.kbss.termit.dto.acl.AccessControlListDto; import cz.cvut.kbss.termit.dto.filter.ChangeRecordFilterDto; import cz.cvut.kbss.termit.dto.listing.VocabularyDto; -import cz.cvut.kbss.termit.exception.InvalidParameterException; import cz.cvut.kbss.termit.model.RdfsResource; import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.acl.AccessControlRecord; import cz.cvut.kbss.termit.model.acl.AccessLevel; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; -import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.rest.doc.ApiDocConstants; import cz.cvut.kbss.termit.rest.util.RestUtils; import cz.cvut.kbss.termit.security.SecurityConstants; @@ -326,41 +324,6 @@ public List getHistory( return records; } - /** - * Rolls back the specified update change record of a vocabulary. - * - * @param localName Vocabulary local name - * @param namespace Optional vocabulary namespace - * @param changeRecord Local name of the update change record - * @throws InvalidParameterException If the change record is not associated with the specified vocabulary - */ - @Operation(security = {@SecurityRequirement(name = "bearer-key")}, - description = "Rolls back the specified update change record of the vocabulary.") - @ApiResponses({ - @ApiResponse(responseCode = "204", description = "Change successfully rolled back."), - @ApiResponse(responseCode = "404", description = "Vocabulary or update change record not found.") - }) - @PostMapping("/{localName}/history/{changeRecord}/rollback") - @ResponseStatus(HttpStatus.NO_CONTENT) - public void rollbackChange( - @Parameter(description = ApiDoc.ID_LOCAL_NAME_DESCRIPTION, - example = ApiDoc.ID_LOCAL_NAME_EXAMPLE) - @PathVariable String localName, - @Parameter(description = ApiDoc.ID_NAMESPACE_DESCRIPTION, - example = ApiDoc.ID_NAMESPACE_EXAMPLE) - @RequestParam(name = QueryParams.NAMESPACE, required = false) Optional namespace, - @Parameter(description = "Local name of the update change record to roll back.") - @PathVariable String changeRecord) { - final URI vocabularyUri = resolveVocabularyUri(localName, namespace); - final UpdateChangeRecord recordToRollback = changeRollbackService.findRecordByLocalName(changeRecord); - if (vocabularyUri.equals(recordToRollback.getChangedEntity())) { - changeRollbackService.rollback(recordToRollback); - LOG.debug("Change record {} of vocabulary {} rolled back.", changeRecord, Utils.uriToString(vocabularyUri)); - } else { - throw new InvalidParameterException("Record not associated with specified Vocabulary."); - } - } - @Operation(security = {@SecurityRequirement(name = "bearer-key")}, description = "Gets summary info about changes made to the content of the vocabulary (term creation, editing).") @ApiResponses({ diff --git a/src/test/java/cz/cvut/kbss/termit/rest/RollbackControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/RollbackControllerTest.java new file mode 100644 index 000000000..1e782d72e --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/rest/RollbackControllerTest.java @@ -0,0 +1,103 @@ +package cz.cvut.kbss.termit.rest; + +import cz.cvut.kbss.termit.environment.Generator; +import cz.cvut.kbss.termit.model.Asset; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; +import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; +import cz.cvut.kbss.termit.service.IdentifierResolver; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; +import cz.cvut.kbss.termit.util.Configuration; +import cz.cvut.kbss.termit.util.Constants; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Answers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.net.URI; +import java.util.stream.Stream; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +public class RollbackControllerTest extends BaseControllerTestRunner { + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private Configuration config; + + @Mock + private IdentifierResolver idResolverMock; + + @Mock + private ChangeRollbackService changeRollbackService; + + @InjectMocks + private RollbackController sut; + + @BeforeEach + void setUp() { + this.setUp(sut); + } + + private static UpdateChangeRecord createUpdateRecord(Asset asset) { + final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); + final String recordLocalName = "update" + Generator.randomInt(); + changeRecord.setUri(URI.create(UpdateChangeRecord_.entityClassIRI + "/" + recordLocalName)); + changeRecord.setChangedEntity(asset.getUri()); + return changeRecord; + } + + private static Stream argumentsStream() { + final String suffix = "/{localName}/history/{changeRecord}/rollback"; + + return Stream.of( + Arguments.of("/vocabularies" + suffix, Generator.generateVocabularyWithId()), + Arguments.of("/terms" + suffix, Generator.generateTermWithId()) + ); + } + + @ParameterizedTest + @MethodSource("argumentsStream") + void rollbackChangeResolvesUpdateChangeRecordAndRollsbackTheChange(String endpointPath, Asset asset) throws Exception { + final String localName = IdentifierResolver.extractIdentifierFragment(asset.getUri()); + final String namespace = IdentifierResolver.extractIdentifierNamespace(asset.getUri()); + final UpdateChangeRecord record = createUpdateRecord(asset); + final String recordLocalName = IdentifierResolver.extractIdentifierFragment(record.getUri()); + + when(idResolverMock.resolveIdentifier(namespace, localName)).thenReturn(asset.getUri()); + when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(record); + + mockMvc.perform(post(endpointPath, localName, recordLocalName).param(Constants.QueryParams.NAMESPACE, namespace)) + .andExpect(status().isNoContent()); + + verify(changeRollbackService).findRecordByLocalName(recordLocalName); + verify(changeRollbackService).rollback(record); + } + + @ParameterizedTest + @MethodSource("argumentsStream") + void rollbackChangeReturnsUnprocessableContentWhenResolvedChangeRecordDoesNotMatchChangedAsset(String endpointPath, Asset asset) throws Exception { + final String localName = IdentifierResolver.extractIdentifierFragment(asset.getUri()); + final String namespace = IdentifierResolver.extractIdentifierNamespace(asset.getUri()); + final UpdateChangeRecord record = createUpdateRecord(asset); + record.setChangedEntity(Generator.generateUri()); + final String recordLocalName = IdentifierResolver.extractIdentifierFragment(record.getUri()); + + when(idResolverMock.resolveIdentifier(namespace, localName)).thenReturn(asset.getUri()); + when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(record); + + mockMvc.perform(post(endpointPath, localName, recordLocalName).param(Constants.QueryParams.NAMESPACE, namespace)) + .andExpect(status().isUnprocessableContent()); + + verify(changeRollbackService).findRecordByLocalName(recordLocalName); + verify(changeRollbackService, never()).rollback(record); + } +} 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 d6ee880f0..27a702b9a 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java @@ -35,7 +35,6 @@ import cz.cvut.kbss.termit.model.assignment.TermDefinitionSource; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; -import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; import cz.cvut.kbss.termit.model.comment.Comment; import cz.cvut.kbss.termit.model.resource.File; import cz.cvut.kbss.termit.persistence.namespace.VocabularyNamespaceResolver; @@ -1453,48 +1452,6 @@ void getHistoryReturnsRecordsWithReversibleTypes(String endpoint) throws Excepti verify(changeRollbackService).withReversibleType(changeRecords); } - @Test - void rollbackChangeResolvesUpdateChangeRecordAndRollsbackTheChange() throws Exception { - final Term term = Generator.generateTerm(); - term.setUri(URI.create(NAMESPACE + TERM_NAME)); - - final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); - final String recordLocalName = "update" + Generator.randomInt(); - changeRecord.setUri(URI.create(UpdateChangeRecord_.entityClassIRI + "/" + recordLocalName)); - changeRecord.setChangedEntity(term.getUri()); - - when(idResolverMock.resolveIdentifier(NAMESPACE, TERM_NAME)).thenReturn(term.getUri()); - when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); - - mockMvc.perform(post("/terms/{localName}/history/{changeRecord}/rollback", TERM_NAME, recordLocalName) - .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) - .andExpect(status().isNoContent()); - - verify(changeRollbackService).findRecordByLocalName(recordLocalName); - verify(changeRollbackService).rollback(changeRecord); - } - - @Test - void rollbackChangeReturnsUnprocessableContentWhenResolvedChangeRecordDoesNotMatchChangedAsset() throws Exception { - final Term term = Generator.generateTerm(); - term.setUri(URI.create(NAMESPACE + TERM_NAME)); - - final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); - final String recordLocalName = "update" + Generator.randomInt(); - changeRecord.setUri(URI.create(UpdateChangeRecord_.entityClassIRI + "/" + recordLocalName)); - changeRecord.setChangedEntity(Generator.generateUri()); - - when(idResolverMock.resolveIdentifier(NAMESPACE, TERM_NAME)).thenReturn(term.getUri()); - when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); - - mockMvc.perform(post("/terms/{localName}/history/{changeRecord}/rollback", TERM_NAME, recordLocalName) - .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) - .andExpect(status().isUnprocessableContent()); - - verify(changeRollbackService).findRecordByLocalName(recordLocalName); - verify(changeRollbackService, never()).rollback(any()); - } - public static class TermSelectionParamsBuilder { private boolean flat = false; private boolean includeImported = false; diff --git a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java index a1b90a039..9bd361de9 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java @@ -749,44 +749,4 @@ void getHistoryReturnsRecordsWithReversibleTypes() throws Exception { verify(serviceMock).getChanges(eq(vocabulary), any()); verify(changeRollbackService).withReversibleType(changeRecords); } - - @Test - void rollbackChangeResolvesUpdateChangeRecordAndRollsbackTheChange() throws Exception { - final Vocabulary vocabulary = Generator.generateVocabulary(); - vocabulary.setUri(URI.create(NAMESPACE + FRAGMENT)); - - final UpdateChangeRecord changeRecord = generateChangeRecord(vocabulary); - final String recordLocalName = IdentifierResolver.extractIdentifierFragment(changeRecord.getUri()); - - when(idResolverMock.resolveIdentifier(NAMESPACE, FRAGMENT)).thenReturn(vocabulary.getUri()); - when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); - - mockMvc.perform(post(PATH + "/{localName}/history/{changeRecord}/rollback", FRAGMENT, recordLocalName) - .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) - .andExpect(status().isNoContent()); - - verify(changeRollbackService).findRecordByLocalName(recordLocalName); - verify(changeRollbackService).rollback(changeRecord); - } - - @Test - void rollbackChangeReturnsUnprocessableContentWhenResolvedChangeRecordDoesNotMatchChangedAsset() throws Exception { - final Vocabulary vocabulary = Generator.generateVocabulary(); - vocabulary.setUri(URI.create(NAMESPACE + FRAGMENT)); - - final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); - changeRecord.setUri(Generator.generateUri()); - changeRecord.setChangedEntity(Generator.generateUri()); - final String recordLocalName = IdentifierResolver.extractIdentifierFragment(changeRecord.getUri()); - - when(idResolverMock.resolveIdentifier(NAMESPACE, FRAGMENT)).thenReturn(vocabulary.getUri()); - when(changeRollbackService.findRecordByLocalName(recordLocalName)).thenReturn(changeRecord); - - mockMvc.perform(post(PATH + "/{localName}/history/{changeRecord}/rollback", FRAGMENT, recordLocalName) - .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) - .andExpect(status().isUnprocessableContent()); - - verify(changeRollbackService).findRecordByLocalName(recordLocalName); - verify(changeRollbackService, never()).rollback(any()); - } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java index 35eb68e19..fcb03baae 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java @@ -7,9 +7,9 @@ import cz.cvut.kbss.termit.model.Vocabulary; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord_; +import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRecordDao; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; import cz.cvut.kbss.termit.service.IdentifierResolver; -import cz.cvut.kbss.termit.service.repository.ChangeRecordService; import cz.cvut.kbss.termit.service.repository.TermRepositoryService; import cz.cvut.kbss.termit.service.repository.VocabularyRepositoryService; import cz.cvut.kbss.termit.service.security.authorization.TermAuthorizationService; @@ -64,7 +64,7 @@ class ChangeRollbackServiceTest { private IdentifierResolver identifierResolver; @Mock - private ChangeRecordService changeRecordService; + private ChangeRecordDao changeRecordDao; @InjectMocks private ChangeRollbackService sut; @@ -221,9 +221,11 @@ void findRecordByLocalNameResolvesIdentifierUsingUpdateChangeRecordNamespace() { final String recordLocalName = "updateRecord" + Generator.randomInt(); final URI expectedRecordUri = URI.create(UpdateChangeRecord_.entityClassIRI + "/" + recordLocalName); + when(changeRecordDao.find(UpdateChangeRecord.class, expectedRecordUri)).thenReturn(Optional.of(new UpdateChangeRecord())); + sut.findRecordByLocalName(recordLocalName); - verify(changeRecordService).findUpdateRequired(expectedRecordUri); + verify(changeRecordDao).find(UpdateChangeRecord.class, expectedRecordUri); } private static UpdateChangeRecord recordFor(Asset asset) { From 2d9914ae701572df93f5d4ef13bcd7cc9722bc23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 1 Oct 2026 11:46:24 +0200 Subject: [PATCH 25/27] [Ref] Change Types value in AbstractChangeRecord from URI to String --- .../model/changetracking/AbstractChangeRecord.java | 11 +++++++---- .../model/changetracking/UpdateChangeRecord.java | 2 +- .../service/changetracking/ChangeRollbackService.java | 4 ++-- .../changetracking/ChangeRollbackServiceTest.java | 8 ++++---- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java b/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java index 3de928824..e5b71ae22 100644 --- a/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java +++ b/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java @@ -28,6 +28,7 @@ import cz.cvut.kbss.termit.model.AbstractEntity; import cz.cvut.kbss.termit.model.Asset; import cz.cvut.kbss.termit.model.User; +import cz.cvut.kbss.termit.model.util.HasTypes; import cz.cvut.kbss.termit.util.Vocabulary; import jakarta.annotation.Nonnull; @@ -41,7 +42,7 @@ */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "className") @OWLClass(iri = Vocabulary.s_c_change) -public class AbstractChangeRecord extends AbstractEntity implements Comparable { +public class AbstractChangeRecord extends AbstractEntity implements Comparable, HasTypes { @ParticipationConstraints(nonEmpty = true) @OWLDataProperty(iri = DC.Terms.MODIFIED) @@ -56,7 +57,7 @@ public class AbstractChangeRecord extends AbstractEntity implements Comparable types; + private Set types; public AbstractChangeRecord() { } @@ -89,11 +90,13 @@ public void setChangedEntity(URI changedEntity) { this.changedEntity = changedEntity; } - public Set getTypes() { + @Override + public Set getTypes() { return types; } - public void setTypes(Set types) { + @Override + public void setTypes(Set types) { this.types = types; } diff --git a/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java b/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java index 6c34845a7..e694cf1bb 100644 --- a/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java +++ b/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java @@ -34,7 +34,7 @@ public class UpdateChangeRecord extends AbstractChangeRecord { /** * Class indicating that the change record can be rolled back by the current user. */ - public static final URI REVERSIBLE_CHANGE_CLASS = URI.create(Vocabulary.s_c_reversible_change); + public static final String REVERSIBLE_CHANGE_CLASS = Vocabulary.s_c_reversible_change; @ParticipationConstraints(nonEmpty = true) @OWLObjectProperty(iri = Vocabulary.s_p_has_changed_attribute) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index 0e6d97227..8a5f6fc1c 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -96,9 +96,9 @@ public void withReversibleType(Collection records) { if (authorized && record instanceof UpdateChangeRecord updateRecord && canRollback(updateRecord, changedAsset)) { - record.getTypes().add(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + record.addType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); } else { - record.getTypes().remove(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + record.removeType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); } } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java index fcb03baae..913ceab88 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java @@ -180,9 +180,9 @@ void withReversibleTypeAddsReversibleTypeToReversibleVocabularyChange(boolean ca lenient().when(rollbackValidator.canRollback(record, Vocabulary.class)).thenReturn(canRollback); when(vocabularyAuthorizationService.canModify(vocabulary)).thenReturn(canModify); - assertFalse(record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); + assertFalse(record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); sut.withReversibleType(List.of(record)); - final boolean isReversibleResult = record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + final boolean isReversibleResult = record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); assertEquals(expectedIsReversible, isReversibleResult); if (canModify) { @@ -203,9 +203,9 @@ void withReversibleTypeAddsReversibleTypeToReversibleTermChange(boolean canRollb lenient().when(rollbackValidator.canRollback(record, Term.class)).thenReturn(canRollback); when(termAuthorizationService.canModify(term)).thenReturn(canModify); - assertFalse(record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); + assertFalse(record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); sut.withReversibleType(List.of(record)); - final boolean isReversibleResult = record.getTypes().contains(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + final boolean isReversibleResult = record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); assertEquals(expectedIsReversible, isReversibleResult); if (canModify) { From 5bed19b70a0397dababb923e94f0967c77061821 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Thu, 1 Oct 2026 12:00:20 +0200 Subject: [PATCH 26/27] [Ref] Remove ChangeRollbackService from Term and Vocabulary controllers and enrich change records with rollback possibility information in ChangeRecordService --- .../cvut/kbss/termit/rest/TermController.java | 14 ++------ .../termit/rest/VocabularyController.java | 10 ++---- .../repository/ChangeRecordService.java | 10 ++++-- .../kbss/termit/rest/TermControllerTest.java | 30 ----------------- .../termit/rest/VocabularyControllerTest.java | 32 ------------------- .../repository/ChangeRecordServiceTest.java | 12 +++++++ 6 files changed, 25 insertions(+), 83 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 301f153ce..9ee1e2c42 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/TermController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/TermController.java @@ -36,7 +36,6 @@ import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.TermService; import cz.cvut.kbss.termit.service.business.util.TermSelectionParams; -import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportType; import cz.cvut.kbss.termit.service.repository.removal.SubTermRemovalStrategy; @@ -96,17 +95,14 @@ public class TermController extends BaseController { private final TermService termService; - private final ChangeRollbackService changeRollbackService; - private final VocabularyNamespaceResolver namespaceResolver; @Autowired public TermController(IdentifierResolver idResolver, Configuration config, TermService termService, - VocabularyNamespaceResolver namespaceResolver, ChangeRollbackService changeRollbackService) { + VocabularyNamespaceResolver namespaceResolver) { super(idResolver, config); this.termService = termService; this.namespaceResolver = namespaceResolver; - this.changeRollbackService = changeRollbackService; } private URI getVocabularyUri(Optional namespace, String fragment) { @@ -850,9 +846,7 @@ public List getHistory( @RequestParam(name = "attribute", required = false, defaultValue = "") String changedAttributeName) { final URI termUri = getTermUri(localName, termLocalName, namespace); final ChangeRecordFilterDto filterDto = new ChangeRecordFilterDto(changedAttributeName, authorName, changeType); - final List records = termService.getChanges(termService.findRequired(termUri), filterDto); - changeRollbackService.withReversibleType(records); - return records; + return termService.getChanges(termService.findRequired(termUri), filterDto); } /** @@ -889,9 +883,7 @@ public List getHistory(@Parameter(description = ApiDoc.ID_ defaultValue = "") String changedAttributeName) { final URI termUri = idResolver.resolveIdentifier(namespace, localName); final ChangeRecordFilterDto filter = new ChangeRecordFilterDto(changedAttributeName, authorName, changeType); - final List records = termService.getChanges(termService.findRequired(termUri), filter); - changeRollbackService.withReversibleType(records); - return records; + return termService.getChanges(termService.findRequired(termUri), filter); } @Operation(security = {@SecurityRequirement(name = "bearer-key")}, diff --git a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java index 81adbfddf..f62f76405 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java @@ -34,7 +34,6 @@ import cz.cvut.kbss.termit.security.SecurityConstants; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.VocabularyService; -import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; @@ -95,14 +94,11 @@ public class VocabularyController extends BaseController { private final VocabularyService vocabularyService; - private final ChangeRollbackService changeRollbackService; - @Autowired public VocabularyController(VocabularyService vocabularyService, IdentifierResolver idResolver, - Configuration config, ChangeRollbackService changeRollbackService) { + Configuration config) { super(idResolver, config); this.vocabularyService = vocabularyService; - this.changeRollbackService = changeRollbackService; } @Operation(security = {@SecurityRequirement(name = "bearer-key")}, @@ -319,9 +315,7 @@ public List getHistory( final Vocabulary vocabulary = vocabularyService.getReference( resolveVocabularyUri(localName, namespace)); final ChangeRecordFilterDto filterDto = new ChangeRecordFilterDto(changedAttributeName, authorName, changeType); - List records = vocabularyService.getChanges(vocabulary, filterDto); - changeRollbackService.withReversibleType(records); - return records; + return vocabularyService.getChanges(vocabulary, filterDto); } @Operation(security = {@SecurityRequirement(name = "bearer-key")}, diff --git a/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java b/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java index ad09428ad..20dea6113 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/repository/ChangeRecordService.java @@ -24,7 +24,9 @@ import cz.cvut.kbss.termit.model.util.HasIdentifier; import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRecordDao; import cz.cvut.kbss.termit.service.changetracking.ChangeRecordProvider; +import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import java.util.List; @@ -34,15 +36,19 @@ public class ChangeRecordService implements ChangeRecordProvider> { private final ChangeRecordDao changeRecordDao; + private final ChangeRollbackService changeRollbackService; @Autowired - public ChangeRecordService(ChangeRecordDao changeRecordDao) { + public ChangeRecordService(ChangeRecordDao changeRecordDao, @Lazy ChangeRollbackService changeRollbackService) { this.changeRecordDao = changeRecordDao; + this.changeRollbackService = changeRollbackService; } @Override public List getChanges(Asset asset, ChangeRecordFilterDto filterDto) { - return changeRecordDao.findAll(asset, filterDto); + final List records = changeRecordDao.findAll(asset, filterDto); + changeRollbackService.withReversibleType(records); + return records; } /** 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 27a702b9a..80ddd4d63 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/TermControllerTest.java @@ -42,7 +42,6 @@ import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.TermService; import cz.cvut.kbss.termit.service.business.util.TermSelectionParams; -import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.service.export.ExportConfig; import cz.cvut.kbss.termit.service.export.ExportFormat; import cz.cvut.kbss.termit.service.export.ExportType; @@ -60,8 +59,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; @@ -111,7 +108,6 @@ import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -146,9 +142,6 @@ public class TermControllerTest extends BaseControllerTestRunner { @Mock private TermService termServiceMock; - @Mock - private ChangeRollbackService changeRollbackService; - @InjectMocks private TermController sut; @@ -1429,29 +1422,6 @@ void getByIdDoesNotResolvesAllAncestorsByDefault() throws Exception { verify(termServiceMock, never()).resolveAllAncestors(term); } - @ParameterizedTest - @CsvSource({ - "/terms/" + TERM_NAME + "/history", - PATH + VOCABULARY_NAME + "/terms/" + TERM_NAME + "/history" - }) - void getHistoryReturnsRecordsWithReversibleTypes(String endpoint) throws Exception { - final Term term = Generator.generateTerm(); - term.setUri(URI.create(NAMESPACE + TERM_NAME)); - final List changeRecords = generateChangeRecords(term); - - lenient().when(namespaceResolver.resolveNamespace(URI.create(VOCABULARY_URI))).thenReturn(NAMESPACE); - lenient().when(idResolverMock.resolveIdentifier(NAMESPACE, VOCABULARY_NAME)).thenReturn(URI.create(VOCABULARY_URI)); - when(idResolverMock.resolveIdentifier(NAMESPACE, TERM_NAME)).thenReturn(term.getUri()); - when(termServiceMock.findRequired(term.getUri())).thenReturn(term); - when(termServiceMock.getChanges(eq(term), any())).thenReturn(changeRecords); - - mockMvc.perform(get(endpoint) - .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) - .andExpect(status().isOk()); - - verify(changeRollbackService).withReversibleType(changeRecords); - } - public static class TermSelectionParamsBuilder { private boolean flat = false; private boolean includeImported = false; diff --git a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java index 9bd361de9..641547948 100644 --- a/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java +++ b/src/test/java/cz/cvut/kbss/termit/rest/VocabularyControllerTest.java @@ -27,7 +27,6 @@ import cz.cvut.kbss.termit.environment.Generator; import cz.cvut.kbss.termit.exception.AssetRemovalException; import cz.cvut.kbss.termit.exception.importing.VocabularyImportException; -import cz.cvut.kbss.termit.model.Asset; import cz.cvut.kbss.termit.model.Term; import cz.cvut.kbss.termit.model.User; import cz.cvut.kbss.termit.model.Vocabulary; @@ -36,11 +35,9 @@ import cz.cvut.kbss.termit.model.acl.AccessLevel; import cz.cvut.kbss.termit.model.acl.UserAccessControlRecord; import cz.cvut.kbss.termit.model.changetracking.AbstractChangeRecord; -import cz.cvut.kbss.termit.model.changetracking.UpdateChangeRecord; import cz.cvut.kbss.termit.rest.handler.ErrorInfo; import cz.cvut.kbss.termit.service.IdentifierResolver; import cz.cvut.kbss.termit.service.business.VocabularyService; -import cz.cvut.kbss.termit.service.changetracking.ChangeRollbackService; import cz.cvut.kbss.termit.util.Configuration; import cz.cvut.kbss.termit.util.Constants; import cz.cvut.kbss.termit.util.Constants.QueryParams; @@ -108,9 +105,6 @@ class VocabularyControllerTest extends BaseControllerTestRunner { @Mock private VocabularyService serviceMock; - @Mock - private ChangeRollbackService changeRollbackService; - @Mock private IdentifierResolver idResolverMock; @@ -723,30 +717,4 @@ void reImportVocabularyRunsTermTranslationsImportForUploadedFileWhenTranslations containsString(QueryParams.NAMESPACE + "=" + NAMESPACE)); verify(serviceMock).importTermTranslations(vocabulary.getUri(), upload); } - - private UpdateChangeRecord generateChangeRecord(Asset changedAsset) { - final UpdateChangeRecord changeRecord = new UpdateChangeRecord(); - changeRecord.setUri(Generator.generateUri()); - changeRecord.setChangedEntity(changedAsset.getUri()); - return changeRecord; - } - - @Test - void getHistoryReturnsRecordsWithReversibleTypes() throws Exception { - final Vocabulary vocabulary = Generator.generateVocabulary(); - vocabulary.setUri(URI.create(NAMESPACE + FRAGMENT)); - - final List changeRecords = List.of(generateChangeRecord(vocabulary), generateChangeRecord(vocabulary)); - - when(idResolverMock.resolveIdentifier(NAMESPACE, FRAGMENT)).thenReturn(vocabulary.getUri()); - when(serviceMock.getReference(vocabulary.getUri())).thenReturn(vocabulary); - when(serviceMock.getChanges(eq(vocabulary), any())).thenReturn(changeRecords); - - mockMvc.perform(get(PATH + "/{localName}/history", FRAGMENT) - .param(Constants.QueryParams.NAMESPACE, NAMESPACE)) - .andExpect(status().isOk()); - - verify(serviceMock).getChanges(eq(vocabulary), any()); - verify(changeRollbackService).withReversibleType(changeRecords); - } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java index e067a67c9..53ac0ba31 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java @@ -40,6 +40,7 @@ import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; class ChangeRecordServiceTest extends BaseServiceTestRunner { @@ -80,6 +81,17 @@ void getChangesReturnsChangesForSpecifiedAsset() { assertEquals(records, result); } + @Test + void getChangesAddsReversibleTypesForReturnedReversibleChanges() { + enableRdfsInference(em); + + final List result = sut.getChanges(asset); + + // all change records generated are updates of title, which are reversible + assertTrue(result.stream().map(UpdateChangeRecord.class::cast) + .allMatch(r -> r.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS))); + } + private List generateChanges() { final List records = IntStream.range(0, 5).mapToObj(i -> { final UpdateChangeRecord r = new UpdateChangeRecord(asset); From 3145488fd9248546ebfe4cb568baaf3ab029fafd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Ka=C5=88ka?= Date: Fri, 2 Oct 2026 09:49:33 +0200 Subject: [PATCH 27/27] [Ref] Remove UpdateChangeRecord#REVERSIBLE_CHANGE_CLASS constant and replace it with direct references to the Vocabulary#s_c_reversible_change --- .../termit/model/changetracking/UpdateChangeRecord.java | 4 ---- .../service/changetracking/ChangeRollbackService.java | 6 +++--- .../service/changetracking/ChangeRollbackServiceTest.java | 8 ++++---- .../service/repository/ChangeRecordServiceTest.java | 2 +- 4 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java b/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java index e694cf1bb..bdabab7c8 100644 --- a/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java +++ b/src/main/java/cz/cvut/kbss/termit/model/changetracking/UpdateChangeRecord.java @@ -31,10 +31,6 @@ @OWLClass(iri = Vocabulary.s_c_update_of_entity) public class UpdateChangeRecord extends AbstractChangeRecord { - /** - * Class indicating that the change record can be rolled back by the current user. - */ - public static final String REVERSIBLE_CHANGE_CLASS = Vocabulary.s_c_reversible_change; @ParticipationConstraints(nonEmpty = true) @OWLObjectProperty(iri = Vocabulary.s_p_has_changed_attribute) diff --git a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java index 8a5f6fc1c..55d9969f1 100644 --- a/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -78,7 +78,7 @@ public boolean canRollback(UpdateChangeRecord record) { } /** - * Sets the {@link UpdateChangeRecord#REVERSIBLE_CHANGE_CLASS reversible class} + * Sets the {@link cz.cvut.kbss.termit.util.Vocabulary#s_c_reversible_change reversible class} * on each {@link UpdateChangeRecord} in the specified collection based on whether it * can be rolled back by the current user. * @@ -96,9 +96,9 @@ public void withReversibleType(Collection records) { if (authorized && record instanceof UpdateChangeRecord updateRecord && canRollback(updateRecord, changedAsset)) { - record.addType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + updateRecord.addType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); } else { - record.removeType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + record.removeType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); } } } diff --git a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java index 913ceab88..21ccda159 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java @@ -180,9 +180,9 @@ void withReversibleTypeAddsReversibleTypeToReversibleVocabularyChange(boolean ca lenient().when(rollbackValidator.canRollback(record, Vocabulary.class)).thenReturn(canRollback); when(vocabularyAuthorizationService.canModify(vocabulary)).thenReturn(canModify); - assertFalse(record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); + assertFalse(record.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change)); sut.withReversibleType(List.of(record)); - final boolean isReversibleResult = record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + final boolean isReversibleResult = record.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); assertEquals(expectedIsReversible, isReversibleResult); if (canModify) { @@ -203,9 +203,9 @@ void withReversibleTypeAddsReversibleTypeToReversibleTermChange(boolean canRollb lenient().when(rollbackValidator.canRollback(record, Term.class)).thenReturn(canRollback); when(termAuthorizationService.canModify(term)).thenReturn(canModify); - assertFalse(record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS)); + assertFalse(record.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change)); sut.withReversibleType(List.of(record)); - final boolean isReversibleResult = record.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS); + final boolean isReversibleResult = record.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); assertEquals(expectedIsReversible, isReversibleResult); if (canModify) { diff --git a/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java index 53ac0ba31..34273ce80 100644 --- a/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java +++ b/src/test/java/cz/cvut/kbss/termit/service/repository/ChangeRecordServiceTest.java @@ -89,7 +89,7 @@ void getChangesAddsReversibleTypesForReturnedReversibleChanges() { // all change records generated are updates of title, which are reversible assertTrue(result.stream().map(UpdateChangeRecord.class::cast) - .allMatch(r -> r.hasType(UpdateChangeRecord.REVERSIBLE_CHANGE_CLASS))); + .allMatch(r -> r.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change))); } private List generateChanges() {