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/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/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/changetracking/AbstractChangeRecord.java b/src/main/java/cz/cvut/kbss/termit/model/changetracking/AbstractChangeRecord.java index 7ed4e338e..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 @@ -23,23 +23,26 @@ 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; 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; import java.net.URI; import java.time.Instant; import java.util.Objects; +import java.util.Set; /** * Represents a change to an asset. */ @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) @@ -53,6 +56,9 @@ public class AbstractChangeRecord extends AbstractEntity implements Comparable types; + public AbstractChangeRecord() { } @@ -84,6 +90,16 @@ public void setChangedEntity(URI changedEntity) { this.changedEntity = changedEntity; } + @Override + public Set getTypes() { + return types; + } + + @Override + 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/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); +} 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/persistence/dao/changetracking/ChangeRollbackDao.java b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java new file mode 100644 index 000000000..1c4fb5408 --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/persistence/dao/changetracking/ChangeRollbackDao.java @@ -0,0 +1,163 @@ +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.query.QueryHints; +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) + .setHint(QueryHints.DISABLE_INFERENCE, "true") + .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/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/VocabularyController.java b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java index 0918a4a0b..f62f76405 100644 --- a/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java +++ b/src/main/java/cz/cvut/kbss/termit/rest/VocabularyController.java @@ -293,7 +293,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}) 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..55d9969f1 --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackService.java @@ -0,0 +1,272 @@ +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; +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.ChangeRecordDao; +import cz.cvut.kbss.termit.persistence.dao.changetracking.ChangeRollbackDao; +import cz.cvut.kbss.termit.service.IdentifierResolver; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.net.URI; +import java.util.Collection; +import java.util.Optional; + +/** + * Service capable of performing rollback of {@link UpdateChangeRecord} + */ +@Service +public class ChangeRollbackService { + private static final Logger LOG = LoggerFactory.getLogger(ChangeRollbackService.class); + private final RollbackValidator rollbackValidator; + private final ChangeRollbackDao rollbackDao; + 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, + TermRepositoryService termService, + VocabularyRepositoryService vocabularyService, + TermAuthorizationService termAuthorizationService, + VocabularyAuthorizationService vocabularyAuthorizationService, + IdentifierResolver identifierResolver, + ChangeRecordDao changeRecordDao) { + this.rollbackValidator = rollbackValidator; + this.rollbackDao = rollbackDao; + this.termService = termService; + this.vocabularyService = vocabularyService; + this.termAuthorizationService = termAuthorizationService; + this.vocabularyAuthorizationService = vocabularyAuthorizationService; + this.identifierResolver = identifierResolver; + this.changeRecordDao = changeRecordDao; + } + + /** + * 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(readOnly = true) + public boolean canRollback(UpdateChangeRecord record) { + final Asset changedObject = resolveChangedAsset(record); + if (changedObject == null) { + return false; // unknown entity class + } + return canRollback(record, changedObject) && isModificationAuthorized(changedObject); + } + + /** + * 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. + * + * @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)) { + updateRecord.addType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); + } else { + record.removeType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); + } + } + } + + /** + * 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); + } + + /** + * 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 changeRecordDao.find(UpdateChangeRecord.class, recordUri) + .orElseThrow(()-> new NotFoundException("UpdateChangeRecord not found")); + } + + /** + * 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); + 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); + } + + /** + * 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); + } + + /** + * 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) { + throw new UpdateChangeRecordRollbackException("Rollback not supported for asset " + + Utils.uriToString(record.getChangedEntity())); + } + 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()) { + return vocabulary.get(); + } + Optional term = termService.find(record.getChangedEntity()); + return term.orElse(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); + } + if (asset instanceof Vocabulary vocabulary) { + return vocabularyAuthorizationService.canModify(vocabulary); + } + 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); + } 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/RollbackValidator.java b/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.java new file mode 100644 index 000000000..88152bb8a --- /dev/null +++ b/src/main/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidator.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.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; + +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 RollbackValidator { + 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 + Boolean.class, + Temporal.class, + Date.class, + TemporalAmount.class, + UUID.class, + MultilingualString.class, + Void.TYPE, + Void.class + }; + + private final ChangeRollbackDao changeRollbackDao; + private final DataRepositoryService dataRepositoryService; + + public RollbackValidator(ChangeRollbackDao changeRollbackDao, DataRepositoryService dataRepositoryService) { + this.changeRollbackDao = changeRollbackDao; + this.dataRepositoryService = dataRepositoryService; + } + + /** + * 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 (allValuesAreLiteral(record)) { + return true; + } + + 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 allValuesAreLiteral(UpdateChangeRecord record) { + return Stream.of(record.getOriginalValue(), record.getNewValue()) + .filter(Objects::nonNull) + .flatMap(Collection::stream) + .map(Object::getClass) + .allMatch(RollbackValidator::isLiteral); + } + + private static boolean isLiteral(Class clazz) { + if (clazz.isPrimitive()) { + return true; + } + for (Class literalClass : LITERAL_CLASSES) { + if (literalClass.isAssignableFrom(clazz)) { + return true; + } + } + return false; + } + + private boolean canRollbackAttributeWithType(Class attributeValueClass, UpdateChangeRecord record) { + if (isLiteral(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; + } + + /** + * 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 + */ + private boolean canRollbackToEntityReference(URI referencedEntity) { + Objects.requireNonNull(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/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/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/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/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; + } +} 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/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 new file mode 100644 index 000000000..2ce465395 --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackIntegrationTest.java @@ -0,0 +1,473 @@ +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.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; +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.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; +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.security.access.AccessDeniedException; +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 java.util.function.Supplier; + +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 { + + @Autowired + private EntityManager em; + + @Autowired + private DescriptorFactory descriptorFactory; + + @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"); + + private URI property; + private URI uriProperty; + private URI propertyB; + + @BeforeEach + void setUp() { + enableRdfsInference(em); + + final User author = Generator.generateUserWithId(); + author.addType(UserRole.ADMIN.getType()); + Environment.setCurrentUser(author); + + 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()); + 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(uriProperty.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()); + } + + 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()); + + // apply change and create change record + 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()); + + // apply change and create change record + 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()); + + // apply change and create change record + 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"; + final int originalTermPropertiesSize = term.getProperties().size(); + + // apply change and create change record + 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(propertyB.toString())); + assertEquals(originalTermPropertiesSize, term.getProperties().size()); + } + + /** + * TermIt cannot guarantee that the reference should not be valid Term/Vocabulary + */ + @Test + void rollbackThrowsForRollbackOfNativeURIProperty() { + // apply change and create change record + term.getProperties().remove(uriProperty.toString()); + term = update(term, termService); + + assertFalse(term.getProperties().containsKey(uriProperty.toString())); + + final UpdateChangeRecord record = getRecord(term); + assertThrows(UpdateChangeRecordRollbackException.class, () -> sut.rollback(record)); + } + + private CustomAttribute persistUriCustomAttribute() { + final CustomAttribute customAttribute = new CustomAttribute(); + customAttribute.setUri(uriProperty); + 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(); + + // apply change and create change record + term.getProperties().remove(uriProperty.toString()); + term = update(term, termService); + + assertFalse(term.getProperties().containsKey(uriProperty.toString())); + + final UpdateChangeRecord record = getRecord(term); + sut.rollback(record); + + term = termService.findRequired(term.getUri()); + assertTrue(term.getProperties().containsKey(uriProperty.toString())); + assertTrue(term.getProperties().get(uriProperty.toString()).contains(property)); + } + + @Test + void rollbackOfCustomAttributeWithUnknownRangeThrows() { + CustomAttribute attribute = persistUriCustomAttribute(); + attribute.setRange(propertyB); + dataRepositoryService.updateCustomAttribute(attribute); + + // apply change and create change record + term.getProperties().remove(uriProperty.toString()); + term = update(term, termService); + + assertFalse(term.getProperties().containsKey(uriProperty.toString())); + + 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)); + } + + @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(Set.of(originalDescription), record.getOriginalValue()); + assertEquals(Set.of(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()); + 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/ChangeRollbackServiceTest.java b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java new file mode 100644 index 000000000..21ccda159 --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/ChangeRollbackServiceTest.java @@ -0,0 +1,239 @@ +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.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.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.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; +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.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +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; + + @Mock(answer = Answers.CALLS_REAL_METHODS) + private IdentifierResolver identifierResolver; + + @Mock + private ChangeRecordDao changeRecordDao; + + @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 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.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change)); + sut.withReversibleType(List.of(record)); + final boolean isReversibleResult = record.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); + 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.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change)); + sut.withReversibleType(List.of(record)); + final boolean isReversibleResult = record.hasType(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change); + assertEquals(expectedIsReversible, isReversibleResult); + + if (canModify) { + verify(rollbackValidator).canRollback(record, Term.class); + } + verify(termAuthorizationService).canModify(term); + verifyNoMoreInteractions(rollbackValidator); + verifyNoMoreInteractions(termAuthorizationService); + } + + @Test + 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(changeRecordDao).find(UpdateChangeRecord.class, expectedRecordUri); + } + + 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; + } +} 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 new file mode 100644 index 000000000..0f039291e --- /dev/null +++ b/src/test/java/cz/cvut/kbss/termit/service/changetracking/RollbackValidatorTest.java @@ -0,0 +1,157 @@ +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 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; +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 RollbackValidatorTest { + + @Mock + private ChangeRollbackDao changeRollbackDao; + + @Mock + private DataRepositoryService dataRepositoryService; // injected into sut + + @Mock + private Attribute attribute; + + @InjectMocks + private RollbackValidator 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; + } +} 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..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 @@ -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(cz.cvut.kbss.termit.util.Vocabulary.s_c_reversible_change))); + } + private List generateChanges() { final List records = IntStream.range(0, 5).mapToObj(i -> { final UpdateChangeRecord r = new UpdateChangeRecord(asset); 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(),