Java Code Examples for org.alfresco.service.cmr.dictionary.PropertyDefinition#getConstraints()

The following examples show how to use org.alfresco.service.cmr.dictionary.PropertyDefinition#getConstraints() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomModelServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Validates the properties' non-null default values against the defined property constraints.
 *
 * @param compiledModel the compiled model
 * @throws CustomModelException.CustomModelConstraintException if there is constraint evaluation
 *                                                             exception
 */
private void validatePropsDefaultValues(CompiledModel compiledModel)
{
    for (PropertyDefinition propertyDef : compiledModel.getProperties())
    {
        if (propertyDef.getDefaultValue() != null && propertyDef.getConstraints().size() > 0)
        {
            for (ConstraintDefinition constraintDef : propertyDef.getConstraints())
            {
                Constraint constraint = constraintDef.getConstraint();
                try
                {
                    constraint.evaluate(propertyDef.getDefaultValue());
                }
                catch (AlfrescoRuntimeException ex)
                {
                    String message = getRootCauseMsg(ex, false, "cmm.service.constraint.default_prop_value_err");
                    throw new CustomModelException.CustomModelConstraintException(message);
                }
            }
        }
    }
}
 
Example 2
Source File: RepoDictionaryDAOTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testConstraintsOverrideInheritance()
{
    QName baseQName = QName.createQName(TEST_URL, "base");
    QName fileQName = QName.createQName(TEST_URL, "file");
    QName folderQName = QName.createQName(TEST_URL, "folder");
    QName prop1QName = QName.createQName(TEST_URL, "prop1");

    // get the base property
    PropertyDefinition prop1Def = service.getProperty(baseQName, prop1QName);
    assertNotNull(prop1Def);
    List<ConstraintDefinition> prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);

    // check the inherited property on folder (must be same as above)
    prop1Def = service.getProperty(folderQName, prop1QName);
    assertNotNull(prop1Def);
    prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);

    // check the overridden property on file (must be reverse of above)
    prop1Def = service.getProperty(fileQName, prop1QName);
    assertNotNull(prop1Def);
    prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);
}
 
Example 3
Source File: DictionaryDAOImpl.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Collection<ConstraintDefinition> getReferenceableConstraintDefs(
        CompiledModel model)
{
    Collection<ConstraintDefinition> conDefs = model.getConstraints();
    Collection<PropertyDefinition> propDefs = model.getProperties();
    for (PropertyDefinition propDef : propDefs)
    {
        for (ConstraintDefinition conDef : propDef.getConstraints())
        {
            conDefs.remove(conDef);
        }
    }

    return conDefs;
}
 
Example 4
Source File: CustomModelDefinitionImpl.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Removes the inline constraints (i.e. defined within the property) from
 * all constraints. The result will be constraints that have been defined
 * within the model (Top level) itself.
 *
 * @param compiledModel the compiled model
 * @return list of model defined constraints
 */
public static List<ConstraintDefinition> removeInlineConstraints(CompiledModel compiledModel)
{
    List<ConstraintDefinition> modelConstraints = new ArrayList<>();

    Set<QName> propertyConstraints = new HashSet<>();
    for(PropertyDefinition propDef : compiledModel.getProperties())
    {
        if (propDef.getConstraints().size() > 0)
        {
            for (ConstraintDefinition propConst : propDef.getConstraints())
            {
                propertyConstraints.add(propConst.getName());
            }
        }
    }

    for (ConstraintDefinition constraint : compiledModel.getConstraints())
    {
        if (!propertyConstraints.contains(constraint.getName()))
        {
            modelConstraints.add(constraint);
        }
    }

    return modelConstraints;
}
 
Example 5
Source File: DictionaryDAOTest.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testConstraintsOverrideInheritance()
{
    QName baseQName = QName.createQName(TEST_URL, "base");
    QName fileQName = QName.createQName(TEST_URL, "file");
    QName folderQName = QName.createQName(TEST_URL, "folder");
    QName prop1QName = QName.createQName(TEST_URL, "prop1");

    // get the base property
    PropertyDefinition prop1Def = service.getProperty(baseQName, prop1QName);
    assertNotNull(prop1Def);
    List<ConstraintDefinition> prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);

    // check the inherited property on folder (must be same as above)
    prop1Def = service.getProperty(folderQName, prop1QName);
    assertNotNull(prop1Def);
    prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);

    // check the overridden property on file (must be reverse of above)
    prop1Def = service.getProperty(fileQName, prop1QName);
    assertNotNull(prop1Def);
    prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);
}
 
Example 6
Source File: CustomModelProperty.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CustomModelProperty(PropertyDefinition propertyDefinition, MessageLookup messageLookup)
{
    this.name = propertyDefinition.getName().getLocalName();
    this.prefixedName = propertyDefinition.getName().toPrefixString();
    this.title = propertyDefinition.getTitle(messageLookup);
    this.dataType = propertyDefinition.getDataType().getName().toPrefixString();
    this.description = propertyDefinition.getDescription(messageLookup);
    this.isMandatory = propertyDefinition.isMandatory();
    this.isMandatoryEnforced = propertyDefinition.isMandatoryEnforced();
    this.isMultiValued = propertyDefinition.isMultiValued();
    this.defaultValue = propertyDefinition.getDefaultValue();
    this.isIndexed = propertyDefinition.isIndexed();
    this.facetable = propertyDefinition.getFacetable();
    this.indexTokenisationMode = propertyDefinition.getIndexTokenisationMode();
    List<ConstraintDefinition> constraintDefs = propertyDefinition.getConstraints();
    if (constraintDefs.size() > 0)
    {
        this.constraintRefs = new ArrayList<>();
        this.constraints = new ArrayList<>();
        for (ConstraintDefinition cd : constraintDefs)
        {
            if (cd.getRef() != null)
            {
                constraintRefs.add(cd.getRef().toPrefixString());
            }
            else
            {
                constraints.add(new CustomModelConstraint(cd, messageLookup));
            }
        }
    }
}
 
Example 7
Source File: DirectoryAnalyserImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean isMetadataValid(ImportableItem importableItem)
{
    if (!importableItem.getHeadRevision().metadataFileExists())
    {
        return true;
    }
    
    if (metadataLoader != null)
    {
        MetadataLoader.Metadata result = new MetadataLoader.Metadata();
        metadataLoader.loadMetadata(importableItem.getHeadRevision(), result);
        
        Map<QName, Serializable> metadataProperties = result.getProperties();
        for (QName propertyName : metadataProperties.keySet())
        {
            PropertyDefinition propDef = dictionaryService.getProperty(propertyName);
            if (propDef != null)
            {
                for (ConstraintDefinition constraintDef : propDef.getConstraints())
                {
                    Constraint constraint = constraintDef.getConstraint();
                    if (constraint != null)
                    {
                        try
                        {
                            constraint.evaluate(metadataProperties.get(propertyName));
                        }
                        catch (ConstraintException e)
                        {
                            if (log.isWarnEnabled())
                            {
                                log.warn("Skipping file '" + FileUtils.getFileName(importableItem.getHeadRevision().getContentFile())
                                   +"' with invalid metadata: '" + FileUtils.getFileName(importableItem.getHeadRevision().getMetadataFile()) + "'.", e);
                            }
                            return false;
                        }
                    }
                }
            }
        }
    }
    
    return true;
}
 
Example 8
Source File: ModelValidatorImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void validateDeleteConstraint(CompiledModel compiledModel, QName constraintName, boolean sharedModel)
{
    String tenantDomain = TenantService.DEFAULT_DOMAIN;
    if (sharedModel)
    {
        tenantDomain = " for tenant [" + tenantService.getCurrentUserDomain() + "]";
    }
    
    Set<QName> referencedBy = new HashSet<QName>(0);
    
    // check for references to constraint definition
    // note: could be anon prop constraint (if no referenceable constraint)
    Collection<QName> allModels = dictionaryDAO.getModels();
    for (QName model : allModels)
    {
        Collection<PropertyDefinition> propDefs = null;
        if (compiledModel.getModelDefinition().getName().equals(model))
        {
            // TODO deal with multiple pending model updates
            propDefs = compiledModel.getProperties();
        }
        else
        {
            propDefs = dictionaryDAO.getProperties(model);
        }
        
        for (PropertyDefinition propDef : propDefs)
        {
            for (ConstraintDefinition conDef : propDef.getConstraints())
            {
                if (constraintName.equals(conDef.getRef()))
                {
                    referencedBy.add(conDef.getName());
                }
            }
        }
    }
    
    if (referencedBy.size() == 1)
    {
        throw new AlfrescoRuntimeException("Failed to validate constraint delete" + tenantDomain + " - constraint definition '" + constraintName + "' is being referenced by '" + referencedBy.toArray()[0] + "' property constraint");
    }
    else if (referencedBy.size() > 1)
    {
        throw new AlfrescoRuntimeException("Failed to validate constraint delete" + tenantDomain + " - constraint definition '" + constraintName + "' is being referenced by " + referencedBy.size() + " property constraints");
    }
}
 
Example 9
Source File: PropertyFieldProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private List<FieldConstraint> makeFieldConstraints(PropertyDefinition propDef)
{
    List<FieldConstraint> fieldConstraints = null;
    List<ConstraintDefinition> constraints = propDef.getConstraints();
    if (constraints != null && constraints.size() > 0)
    {
        fieldConstraints = new ArrayList<FieldConstraint>(constraints.size());
        for (ConstraintDefinition constraintDef : constraints)
        {
            Constraint constraint = constraintDef.getConstraint();
            String type = constraint.getType();
            Map<String, Object> params = constraint.getParameters();
            
            
            //ListOfValuesConstraints have special handling for localising their allowedValues.
            //If the constraint that we are currently handling is a registered constraint then
            //we need to examine the underlying constraint to see if it is a LIST constraint
            if (RegisteredConstraint.class.isAssignableFrom(constraint.getClass()))
            {
                constraint = ((RegisteredConstraint)constraint).getRegisteredConstraint();
            }
            
            if (ListOfValuesConstraint.class.isAssignableFrom(constraint.getClass()))
            {
                ListOfValuesConstraint lovConstraint = (ListOfValuesConstraint) constraint;
                List<String> allowedValues = lovConstraint.getAllowedValues();
                List<String> localisedValues = new ArrayList<String>(allowedValues.size());
                
                // Look up each localised display-label in turn.
                for (String value : allowedValues)
                {
                    String displayLabel = lovConstraint.getDisplayLabel(value, dictionaryService);
                    // Change the allowedValue entry to the format the FormsService expects for localised strings: "value|label"
                    // If there is no localisation defined for any value, then this will give us "value|value".
                    localisedValues.add(value + "|" + displayLabel);
                }
                
                // Now replace the allowedValues param with our localised version.
                params.put(ListOfValuesConstraint.ALLOWED_VALUES_PARAM, localisedValues);
            }
            FieldConstraint fieldConstraint = new FieldConstraint(type, params);
            fieldConstraints.add(fieldConstraint);
        }
    }
    return fieldConstraints;
}
 
Example 10
Source File: ActivitiPropertyConverter.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sets Default Properties of Task
 * 
 * @param task
 *            task instance
 */
public void setDefaultTaskProperties(DelegateTask task)
{
    TypeDefinition typeDefinition = typeManager.getFullTaskDefinition(task);
    // Only local task properties should be set to default value
    Map<QName, Serializable> existingValues = getTaskProperties(task, typeDefinition, true);
    Map<QName, Serializable> defaultValues = new HashMap<QName, Serializable>();

    Map<QName, PropertyDefinition> propertyDefs = typeDefinition.getProperties();

    // for each property, determine if it has a default value
    for (Map.Entry<QName, PropertyDefinition> entry : propertyDefs.entrySet())
    {
        QName key = entry.getKey();
        String defaultValue = entry.getValue().getDefaultValue();
        if (defaultValue != null && existingValues.get(key) == null)
        {
            defaultValues.put(key, defaultValue);
        }
    }

    // Special case for property priorities
    PropertyDefinition priorDef = propertyDefs.get(WorkflowModel.PROP_PRIORITY);
    Serializable existingValue = existingValues.get(WorkflowModel.PROP_PRIORITY);
    try
    {
    	if(priorDef != null) {
         for (ConstraintDefinition constraintDef : priorDef.getConstraints())
         {
             constraintDef.getConstraint().evaluate(existingValue);
         }
    	}
    }
    catch (ConstraintException ce)
    {
        if(priorDef != null) {
            Integer defaultVal = Integer.valueOf(priorDef.getDefaultValue());
            if (logger.isDebugEnabled())
            {
                logger.debug("Task priority value ("+existingValue+") was invalid so it was set to the default value of "+defaultVal+". Task:"+task.getName());
            }
            defaultValues.put(WorkflowModel.PROP_PRIORITY, defaultVal);
        }
    }    
    
    // Special case for task description default value
    String description = (String) existingValues.get(WorkflowModel.PROP_DESCRIPTION);
    if (description == null || description.length() == 0)
    {
        //Try the localised task description first
        String processDefinitionKey = ((ProcessDefinition) ((TaskEntity)task).getExecution().getProcessDefinition()).getKey();
        description = factory.getTaskDescription(typeDefinition, factory.buildGlobalId(processDefinitionKey), null, task.getTaskDefinitionKey());
        if (description != null && description.length() > 0) {
            defaultValues.put(WorkflowModel.PROP_DESCRIPTION,  description);
        } else {
            String descriptionKey = factory.mapQNameToName(WorkflowModel.PROP_WORKFLOW_DESCRIPTION);
            description = (String) task.getExecution().getVariable(descriptionKey); 
            if (description != null && description.length() > 0) {
                defaultValues.put(WorkflowModel.PROP_DESCRIPTION,  description); 
            } else {
                defaultValues.put(WorkflowModel.PROP_DESCRIPTION,  task.getName());
            }
        }
         
    }

    // Assign the default values to the task
    if (defaultValues.size() > 0)
    {
        setTaskProperties(task, defaultValues);
    }
}
 
Example 11
Source File: M2PropertyDefinition.java    From alfresco-data-model with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Create a property definition whose values are overridden
 * 
 * @param propertyDef  the property definition to override
 * @param override  the overridden values
 * @return  the property definition
 */
private M2Property createOverriddenProperty(
        PropertyDefinition propertyDef,
        M2PropertyOverride override,
        NamespacePrefixResolver prefixResolver,
        Map<QName, ConstraintDefinition> modelConstraints)
{
    M2Property property = new M2Property();
    property.setOverride(true);
    
    // Process Default Value
    String defaultValue = override.getDefaultValue();
    property.setDefaultValue(defaultValue == null ? propertyDef.getDefaultValue() : defaultValue);

    // Process Mandatory Value
    Boolean isOverrideMandatory = override.isMandatory();
    Boolean isOverrideMandatoryEnforced = override.isMandatoryEnforced();
    if (isOverrideMandatory != null && propertyDef.isMandatory())
    {
        // the override specified whether the property should be mandatory or not
        // check that the mandatory enforcement is not relaxed
        if (!isOverrideMandatory)
        {
            throw new DictionaryException(
                    "d_dictionary.property.err.cannot_relax_mandatory",
                    propertyDef.getName().toPrefixString());
        }
        else if ((isOverrideMandatoryEnforced != null) && !isOverrideMandatoryEnforced && propertyDef.isMandatoryEnforced())
        {
            throw new DictionaryException(
                    "d_dictionary.property.err.cannot_relax_mandatory_enforcement",
                    propertyDef.getName().toPrefixString());
        }
    }
    property.setMandatory(isOverrideMandatory == null ? propertyDef.isMandatory() : isOverrideMandatory);
    property.setMandatoryEnforced(isOverrideMandatoryEnforced == null ? propertyDef.isMandatoryEnforced() : isOverrideMandatoryEnforced);

    // inherit or override constraints
    List<M2Constraint> overrideConstraints = override.getConstraints();
    if (overrideConstraints != null)
    {
        constraintDefs = buildConstraints(
                overrideConstraints,
                this,
                prefixResolver,
                modelConstraints);
    }
    else
    {
        this.constraintDefs = propertyDef.getConstraints();
    }

    // Copy all other properties as they are
    property.setDescription(propertyDef.getDescription(null));
    property.setIndexed(propertyDef.isIndexed());
    property.setIndexedAtomically(propertyDef.isIndexedAtomically());
    property.setMultiValued(propertyDef.isMultiValued());
    property.setProtected(propertyDef.isProtected());
    property.setStoredInIndex(propertyDef.isStoredInIndex());
    property.setTitle(propertyDef.getTitle(null));
    property.setIndexTokenisationMode(propertyDef.getIndexTokenisationMode());
    
    return property;
}
 
Example 12
Source File: DataDictionaryBuilderImpl.java    From alfresco-bulk-import with Apache License 2.0 4 votes vote down vote up
private String classDefinitionToString(final ClassDefinition definition)
{
    StringBuilder result = null;
    
    if (definition != null)
    {
        result = new StringBuilder(1024);
        result.append("\n\t\t\t");
        result.append(definition.getName().toPrefixString());
        
        result.append("\n\t\t\t\tParent: ");
        result.append(definition.getParentName() == null ? "<none>" : definition.getParentName().getPrefixString());
        
        result.append("\n\t\t\t\tProperties:");
        Map<QName,PropertyDefinition> properties = definition.getProperties();
        if (properties != null && properties.size() > 0)
        {
            for (QName propertyName : properties.keySet())
            {
                PropertyDefinition propertyDefinition = properties.get(propertyName);
                
                result.append("\n\t\t\t\t\t");
                result.append(propertyName.toPrefixString());
                result.append(" (");
                result.append(propertyDefinition.getDataType().getName().getPrefixString());
                result.append(")");
                
                if (propertyDefinition.isMultiValued())
                {
                    result.append(" (multi-valued)");
                }
                
                if (propertyDefinition.isMandatoryEnforced())
                {
                    result.append(" (mandatory)");
                }
                
                List<ConstraintDefinition> propertyConstraints = propertyDefinition.getConstraints();
                if (propertyConstraints != null && propertyConstraints.size() > 0)
                {
                    result.append(" (constraints: ");
                    for (ConstraintDefinition propertyConstraint : propertyConstraints)
                    {
                        result.append(propertyConstraint.getName().toPrefixString());
                        result.append(", ");
                    }
                    
                    result.delete(result.length() - ", ".length(), result.length());
                    result.append(")");
                }
            }
        }
        else
        {
            result.append("\n\t\t\t\t\t<none>");
        }
        
        result.append("\n\t\t\t\tAssociations:");
        Map<QName, AssociationDefinition> associations = definition.getAssociations();
        if (associations != null && associations.size() > 0)
        {
            for (QName associationName : associations.keySet())
            {
                AssociationDefinition associationDefinition = associations.get(associationName);
                
                result.append("\n\t\t\t\t\t");
                result.append(associationName.toPrefixString());
                
                result.append(associationDefinition.isChild() ? " (parent/child)" : " (peer)");
                
                result.append(" (source: ");
                result.append(associationDefinition.getSourceClass().getName().toPrefixString());
                result.append(")");
                
                result.append(" (target: ");
                result.append(associationDefinition.getTargetClass().getName().toPrefixString());
                result.append(")");
            }
        }
        else
        {
            result.append("\n\t\t\t\t\t<none>");
        }
    }
    
    return(result == null ? null : result.toString());
}