Search in sources :

Example 11 with ConstraintViolation

use of org.molgenis.validation.ConstraintViolation in project molgenis by molgenis.

the class RepositoryValidationDecorator method validateEntityValueReferences.

private void validateEntityValueReferences(Entity entity, ValidationResource validationResource) {
    validationResource.getRefAttrs().forEach(refAttr -> {
        HugeSet<Object> refEntityIds = validationResource.getRefEntitiesIds().get(refAttr.getRefEntity().getId());
        Iterable<Entity> refEntities;
        if (isSingleReferenceType(refAttr)) {
            Entity refEntity = entity.getEntity(refAttr.getName());
            if (refEntity != null) {
                refEntities = singleton(refEntity);
            } else {
                refEntities = emptyList();
            }
        } else {
            refEntities = entity.getEntities(refAttr.getName());
        }
        for (Entity refEntity : refEntities) {
            if (!refEntityIds.contains(refEntity.getIdValue())) {
                boolean selfReference = entity.getEntityType().getId().equals(refAttr.getRefEntity().getId());
                if (!(selfReference && entity.getIdValue().equals(refEntity.getIdValue()))) {
                    String message = String.format("Unknown xref value '%s' for attribute '%s' of entity '%s'.", DataConverter.toString(refEntity.getIdValue()), refAttr.getName(), getName());
                    ConstraintViolation constraintViolation = new ConstraintViolation(message, (long) validationResource.getRow());
                    validationResource.addViolation(constraintViolation);
                }
            }
        }
        // only do if self reference
        if (validationResource.isSelfReferencing()) {
            validationResource.addRefEntityId(getName(), entity.getIdValue());
        }
    });
}
Also used : Entity(org.molgenis.data.Entity) ConstraintViolation(org.molgenis.validation.ConstraintViolation)

Example 12 with ConstraintViolation

use of org.molgenis.validation.ConstraintViolation in project molgenis by molgenis.

the class EntityAttributesValidator method createConstraintViolation.

private static ConstraintViolation createConstraintViolation(Entity entity, Attribute attribute, EntityType entityType) {
    String message = format("Invalid %s value '%s' for attribute '%s' of entity '%s'.", attribute.getDataType().toString().toLowerCase(), entity.get(attribute.getName()), attribute.getLabel(), entityType.getId());
    Range range = attribute.getRange();
    if (range != null) {
        message += format("Value must be between %d and %d", range.getMin(), range.getMax());
    }
    Integer maxLength = attribute.getMaxLength();
    if (maxLength != null) {
        message += format("Value must be less than or equal to %d characters", maxLength);
    }
    return new ConstraintViolation(message);
}
Also used : ConstraintViolation(org.molgenis.validation.ConstraintViolation) Range(org.molgenis.data.Range)

Example 13 with ConstraintViolation

use of org.molgenis.validation.ConstraintViolation in project molgenis by molgenis.

the class EntityTypeValidator method validateOwnAttributes.

/**
 * Validates that this entity: <br>
 * 1) has attributes defined at all <br>
 * 2) doesn't have attributes with the same name (also in the parent entities)<br>
 * 3) doesn't have attributes with a non-existing parent <br>
 *
 * @param entityType entity meta data
 * @throws MolgenisValidationException if one of the above rules is violated
 */
static void validateOwnAttributes(EntityType entityType) {
    // Validate that entity has attributes
    if (stream(entityType.getAllAttributes()).collect(toList()).isEmpty()) {
        throw new MolgenisValidationException(new ConstraintViolation(format("EntityType [%s] does not contain any attributes. Did you use the correct package+entity name combination in both the entities as well as the attributes sheet?", entityType.getId())));
    }
    // Validate that entity does not contain multiple attributes with the same name
    Multimap<String, Attribute> attrMultiMap = stream(entityType.getAllAttributes()).collect(MultimapCollectors.toArrayListMultimap(Attribute::getName, Function.identity()));
    attrMultiMap.keySet().forEach(attrName -> {
        if (attrMultiMap.get(attrName).size() > 1) {
            throw new MolgenisValidationException(new ConstraintViolation(format("EntityType [%s] contains multiple attributes with name [%s]", entityType.getId(), attrName)));
        }
    });
    // Validate that all parent attributes actually exist
    Set<String> attributeIds = stream(entityType.getAllAttributes()).map(Attribute::getIdentifier).collect(toSet());
    stream(entityType.getAllAttributes()).filter(attr -> attr.getParent() != null).forEach(attr -> {
        if (!attributeIds.contains(attr.getParent().getIdentifier())) {
            throw new MolgenisValidationException(new ConstraintViolation(format("Attribute [%s] of EntityType [%s] has a non-existing parent attribute [%s]", attr.getName(), entityType.getId(), attr.getParent().getName())));
        }
    });
}
Also used : MapCollectors.toLinkedMap(org.molgenis.util.stream.MapCollectors.toLinkedMap) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) Attribute(org.molgenis.data.meta.model.Attribute) ENTITY_TYPE_META_DATA(org.molgenis.data.meta.model.EntityTypeMetadata.ENTITY_TYPE_META_DATA) AttributeUtils(org.molgenis.data.util.AttributeUtils) Objects.requireNonNull(java.util.Objects.requireNonNull) Map(java.util.Map) PackageUtils.isSystemPackage(org.molgenis.data.util.PackageUtils.isSystemPackage) SystemEntityTypeRegistry(org.molgenis.data.meta.system.SystemEntityTypeRegistry) ATTRIBUTE_META_DATA(org.molgenis.data.meta.model.AttributeMetadata.ATTRIBUTE_META_DATA) Collectors.toSet(java.util.stream.Collectors.toSet) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) MultimapCollectors(org.molgenis.util.stream.MultimapCollectors) Set(java.util.Set) EntityType(org.molgenis.data.meta.model.EntityType) String.format(java.lang.String.format) Streams.stream(com.google.common.collect.Streams.stream) Collectors.toList(java.util.stream.Collectors.toList) PACKAGE(org.molgenis.data.meta.model.PackageMetadata.PACKAGE) ConstraintViolation(org.molgenis.validation.ConstraintViolation) Component(org.springframework.stereotype.Component) DataService(org.molgenis.data.DataService) Package(org.molgenis.data.meta.model.Package) MolgenisDataException(org.molgenis.data.MolgenisDataException) Attribute(org.molgenis.data.meta.model.Attribute) ConstraintViolation(org.molgenis.validation.ConstraintViolation) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException)

Example 14 with ConstraintViolation

use of org.molgenis.validation.ConstraintViolation in project molgenis by molgenis.

the class TagValidator method validate.

/**
 * Validates tag
 *
 * @param tag tag
 * @throws MolgenisValidationException if tag is not valid
 */
@SuppressWarnings("MethodMayBeStatic")
public void validate(Tag tag) {
    String relationIri = tag.getRelationIri();
    Relation relation = Relation.forIRI(relationIri);
    if (relation == null) {
        throw new MolgenisValidationException(new ConstraintViolation(format("Unknown relation IRI [%s]", relationIri)));
    }
}
Also used : Relation(org.molgenis.data.semantic.Relation) ConstraintViolation(org.molgenis.validation.ConstraintViolation) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException)

Example 15 with ConstraintViolation

use of org.molgenis.validation.ConstraintViolation in project molgenis by molgenis.

the class JobScheduler method schedule.

/**
 * Schedule a {@link ScheduledJob} with a cron expression defined in the entity.
 *
 * <p>Reschedules job if the job already exists.
 *
 * <p>If active is false, it unschedules the job
 *
 * @param scheduledJob the {@link ScheduledJob} to schedule
 */
public synchronized void schedule(ScheduledJob scheduledJob) {
    String id = scheduledJob.getId();
    String cronExpression = scheduledJob.getCronExpression();
    String name = scheduledJob.getName();
    // Validate cron expression
    if (!CronExpression.isValidExpression(cronExpression)) {
        throw new MolgenisValidationException(singleton(new ConstraintViolation("Invalid cronexpression '" + cronExpression + "'", null)));
    }
    try {
        // If already scheduled, remove it from the quartzScheduler
        if (quartzScheduler.checkExists(new JobKey(id, SCHEDULED_JOB_GROUP))) {
            unschedule(id);
        }
        // If not active, do not schedule it
        if (!scheduledJob.isActive()) {
            return;
        }
        // Schedule with 'cron' trigger
        Trigger trigger = newTrigger().withIdentity(id, SCHEDULED_JOB_GROUP).withSchedule(cronSchedule(cronExpression)).build();
        schedule(scheduledJob, trigger);
        LOG.info("Scheduled Job '{}' with trigger '{}'", name, trigger);
    } catch (SchedulerException e) {
        LOG.error("Error schedule job", e);
        throw new ScheduledJobException("Error schedule job", e);
    }
}
Also used : JobKey(org.quartz.JobKey) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) Trigger(org.quartz.Trigger) SchedulerException(org.quartz.SchedulerException) ConstraintViolation(org.molgenis.validation.ConstraintViolation) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException)

Aggregations

ConstraintViolation (org.molgenis.validation.ConstraintViolation)36 Entity (org.molgenis.data.Entity)22 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)14 Attribute (org.molgenis.data.meta.model.Attribute)14 DynamicEntity (org.molgenis.data.support.DynamicEntity)13 Test (org.junit.jupiter.api.Test)12 EntityType (org.molgenis.data.meta.model.EntityType)11 MolgenisValidationException (org.molgenis.data.validation.MolgenisValidationException)10 MethodSource (org.junit.jupiter.params.provider.MethodSource)6 AbstractMockitoTest (org.molgenis.test.AbstractMockitoTest)6 AttributeType (org.molgenis.data.meta.AttributeType)4 UnexpectedEnumException (org.molgenis.util.UnexpectedEnumException)4 Collectors.toList (java.util.stream.Collectors.toList)3 MolgenisDataException (org.molgenis.data.MolgenisDataException)3 Lists.newArrayList (com.google.common.collect.Lists.newArrayList)2 Streams.stream (com.google.common.collect.Streams.stream)2 String.format (java.lang.String.format)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2