Search in sources :

Example 1 with ConstraintViolation

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

the class RestControllerV2Test method testUpdateEntitiesMolgenisValidationException.

@SuppressWarnings("unchecked")
@Test
public void testUpdateEntitiesMolgenisValidationException() throws Exception {
    Exception e = new MolgenisValidationException(Collections.singleton(new ConstraintViolation("Message", 5L)));
    doThrow(e).when(dataService).update(eq(ENTITY_NAME), (Stream<Entity>) any(Stream.class));
    mockMvc.perform(put(HREF_ENTITY_COLLECTION).content("{entities:[{id:'p1', name:'Example data'}]}").contentType(APPLICATION_JSON)).andExpect(status().isBadRequest()).andExpect(content().contentType(APPLICATION_JSON_UTF8)).andExpect(header().doesNotExist("Location")).andExpect(jsonPath(FIRST_ERROR_MESSAGE, is("Message (entity 5)")));
}
Also used : DynamicEntity(org.molgenis.data.support.DynamicEntity) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) ParseException(java.text.ParseException) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException)

Example 2 with ConstraintViolation

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

the class EntityTypeValidator method validateOwnAttributes.

/**
 * Validates the attributes owned by this entity:
 * 1) validates that the parent entity doesn't have attributes with the same name
 * 2) validates that this entity doesn't have attributes with the same name
 * 3) validates that this entity has attributes defined at all
 *
 * @param entityType entity meta data
 * @throws MolgenisValidationException if an attribute is owned by another entity or a parent attribute has the same name
 */
private static void validateOwnAttributes(EntityType entityType) {
    // Validate that entity has attributes
    if (asStream(entityType.getAllAttributes()).collect(toList()).isEmpty()) {
        throw new MolgenisValidationException(new ConstraintViolation(format("Entity [%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 = asStream(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("Entity [%s] contains multiple attributes with name [%s]", entityType.getId(), attrName)));
        }
    });
    // Validate that entity attributes with same name do no exist in parent entity
    EntityType extendsEntityType = entityType.getExtends();
    if (extendsEntityType != null) {
        Map<String, Attribute> extendsAllAttrMap = stream(extendsEntityType.getAllAttributes().spliterator(), false).collect(toMap(Attribute::getName, Function.identity(), (u, v) -> {
            throw new IllegalStateException(String.format("Duplicate key %s", u));
        }, LinkedHashMap::new));
        entityType.getOwnAllAttributes().forEach(attr -> {
            if (extendsAllAttrMap.containsKey(attr.getName())) {
                throw new MolgenisValidationException(new ConstraintViolation(format("An attribute with name [%s] already exists in entity [%s] or one of its parents", attr.getName(), extendsEntityType.getId())));
            }
        });
    }
}
Also used : EntityType(org.molgenis.data.meta.model.EntityType) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) Multimap(com.google.common.collect.Multimap) Attribute(org.molgenis.data.meta.model.Attribute) Function(java.util.function.Function) EntityUtils.asStream(org.molgenis.data.util.EntityUtils.asStream) LinkedHashMap(java.util.LinkedHashMap) MetaUtils(org.molgenis.data.meta.MetaUtils) ENTITY_TYPE_META_DATA(org.molgenis.data.meta.model.EntityTypeMetadata.ENTITY_TYPE_META_DATA) Collectors.toMap(java.util.stream.Collectors.toMap) AttributeUtils(org.molgenis.data.support.AttributeUtils) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) SystemEntityTypeRegistry(org.molgenis.data.meta.system.SystemEntityTypeRegistry) ATTRIBUTE_META_DATA(org.molgenis.data.meta.model.AttributeMetadata.ATTRIBUTE_META_DATA) RepositoryCollection(org.molgenis.data.RepositoryCollection) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) MultimapCollectors(org.molgenis.util.stream.MultimapCollectors) EntityType(org.molgenis.data.meta.model.EntityType) String.format(java.lang.String.format) Component(org.springframework.stereotype.Component) Collectors.toList(java.util.stream.Collectors.toList) PACKAGE(org.molgenis.data.meta.model.PackageMetadata.PACKAGE) StreamSupport.stream(java.util.stream.StreamSupport.stream) 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.data.validation.ConstraintViolation) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException)

Example 3 with ConstraintViolation

use of org.molgenis.data.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.data.validation.ConstraintViolation) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException)

Example 4 with ConstraintViolation

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

the class AppRepositoryDecorator method validateResourceZip.

private void validateResourceZip(App app) {
    FileMeta appZipMeta = app.getSourceFiles();
    if (appZipMeta != null) {
        File fileStoreFile = fileStore.getFile(appZipMeta.getId());
        if (fileStoreFile == null) {
            LOG.error("Resource zip '{}' for app '{}' missing in file store", appZipMeta.getId(), app.getName());
            throw new RuntimeException("An error occurred trying to create or update app");
        }
        ZipFile zipFile;
        try {
            zipFile = new ZipFile(fileStoreFile);
        } catch (ZipException e) {
            LOG.error("Error creating zip file object", e);
            throw new RuntimeException("An error occurred trying to create or update app");
        }
        if (!zipFile.isValidZipFile()) {
            throw new MolgenisValidationException(new ConstraintViolation(String.format("'%s' is not a valid zip file.", appZipMeta.getFilename())));
        }
    }
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) ZipException(net.lingala.zip4j.exception.ZipException) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) FileMeta(org.molgenis.data.file.model.FileMeta)

Example 5 with ConstraintViolation

use of org.molgenis.data.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.getBoolean(ScheduledJobMetadata.ACTIVE)) {
            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 : TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException)

Aggregations

ConstraintViolation (org.molgenis.data.validation.ConstraintViolation)20 MolgenisValidationException (org.molgenis.data.validation.MolgenisValidationException)19 ServerErrorMessage (org.postgresql.util.ServerErrorMessage)7 Matcher (java.util.regex.Matcher)6 Attribute (org.molgenis.data.meta.model.Attribute)4 String.format (java.lang.String.format)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 Objects.requireNonNull (java.util.Objects.requireNonNull)2 MolgenisDataException (org.molgenis.data.MolgenisDataException)2 RepositoryCollection (org.molgenis.data.RepositoryCollection)2 AttributeType (org.molgenis.data.meta.AttributeType)2 EntityType (org.molgenis.data.meta.model.EntityType)2 EntityTypeDescription (org.molgenis.data.postgresql.identifier.EntityTypeDescription)2 Component (org.springframework.stereotype.Component)2 Lists.newArrayList (com.google.common.collect.Lists.newArrayList)1 Multimap (com.google.common.collect.Multimap)1 File (java.io.File)1 BatchUpdateException (java.sql.BatchUpdateException)1 SQLException (java.sql.SQLException)1