Search in sources :

Example 21 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class ValueDatasourceDelegate method afterLoadValues.

protected void afterLoadValues(Map<String, Object> params, ValueLoadContext context, List<KeyValueEntity> entities) {
    ds.detachListener(ds.data.values());
    ds.data.clear();
    boolean hasEnumerations = ds.metaClass.getOwnProperties().stream().anyMatch(p -> p.getRange().isEnum());
    if (!hasEnumerations) {
        for (KeyValueEntity entity : entities) {
            ds.data.put(entity.getId(), entity);
            ds.attachListener(entity);
            entity.setMetaClass(ds.metaClass);
        }
    } else {
        List<MetaProperty> enumProperties = getEnumProperties(ds.metaClass);
        for (KeyValueEntity entity : entities) {
            convertEnumValues(entity, enumProperties);
            ds.data.put(entity.getId(), entity);
            ds.attachListener(entity);
            entity.setMetaClass(ds.metaClass);
        }
    }
}
Also used : MetaProperty(com.haulmont.chile.core.model.MetaProperty) KeyValueMetaProperty(com.haulmont.cuba.core.app.keyvalue.KeyValueMetaProperty) KeyValueEntity(com.haulmont.cuba.core.entity.KeyValueEntity)

Example 22 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class PersistenceTools method getReferenceId.

/**
 * Returns an ID of directly referenced entity without loading it from DB.
 *
 * If the view does not contain the reference and {@link View#loadPartialEntities()} is true,
 * the returned {@link RefId} will have {@link RefId#isLoaded()} = false.
 *
 * <p>Usage example:
 * <pre>
 *   PersistenceTools.RefId refId = persistenceTools.getReferenceId(doc, "currency");
 *   if (refId.isLoaded()) {
 *       String currencyCode = (String) refId.getValue();
 *   }
 * </pre>
 *
 * @param entity   entity instance in managed state
 * @param property name of reference property
 * @return {@link RefId} instance which contains the referenced entity ID
 * @throws IllegalArgumentException if the specified property is not a reference
 * @throws IllegalStateException if the entity is not in Managed state
 * @throws RuntimeException if anything goes wrong when retrieving the ID
 */
public RefId getReferenceId(BaseGenericIdEntity entity, String property) {
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    MetaProperty metaProperty = metaClass.getPropertyNN(property);
    if (!metaProperty.getRange().isClass() || metaProperty.getRange().getCardinality().isMany())
        throw new IllegalArgumentException("Property is not a reference");
    if (!PersistenceHelper.isManaged(entity))
        throw new IllegalStateException("Entity must be in managed state");
    String[] inaccessibleAttributes = BaseEntityInternalAccess.getInaccessibleAttributes(entity);
    if (inaccessibleAttributes != null) {
        for (String inaccessibleAttr : inaccessibleAttributes) {
            if (inaccessibleAttr.equals(property))
                return RefId.createNotLoaded(property);
        }
    }
    if (entity instanceof FetchGroupTracker) {
        FetchGroup fetchGroup = ((FetchGroupTracker) entity)._persistence_getFetchGroup();
        if (fetchGroup != null) {
            if (!fetchGroup.getAttributeNames().contains(property))
                return RefId.createNotLoaded(property);
            else {
                Entity refEntity = (Entity) entity.getValue(property);
                return RefId.create(property, refEntity == null ? null : refEntity.getId());
            }
        }
    }
    try {
        Class<?> declaringClass = metaProperty.getDeclaringClass();
        if (declaringClass == null) {
            throw new RuntimeException("Property does not belong to persistent class");
        }
        Method vhMethod = declaringClass.getDeclaredMethod(String.format("_persistence_get_%s_vh", property));
        vhMethod.setAccessible(true);
        ValueHolderInterface vh = (ValueHolderInterface) vhMethod.invoke(entity);
        if (vh instanceof DatabaseValueHolder) {
            AbstractRecord row = ((DatabaseValueHolder) vh).getRow();
            if (row != null) {
                Session session = persistence.getEntityManager().getDelegate().unwrap(Session.class);
                ClassDescriptor descriptor = session.getDescriptor(entity);
                DatabaseMapping mapping = descriptor.getMappingForAttributeName(property);
                Vector<DatabaseField> fields = mapping.getFields();
                if (fields.size() != 1) {
                    throw new IllegalStateException("Invalid number of columns in mapping: " + fields);
                }
                Object value = row.get(fields.get(0));
                if (value != null) {
                    ClassDescriptor refDescriptor = mapping.getReferenceDescriptor();
                    DatabaseMapping refMapping = refDescriptor.getMappingForAttributeName(metadata.getTools().getPrimaryKeyName(metaClass));
                    if (refMapping instanceof AbstractColumnMapping) {
                        Converter converter = ((AbstractColumnMapping) refMapping).getConverter();
                        if (converter != null) {
                            return RefId.create(property, converter.convertDataValueToObjectValue(value, session));
                        }
                    }
                }
                return RefId.create(property, value);
            } else {
                return RefId.create(property, null);
            }
        }
        return RefId.createNotLoaded(property);
    } catch (Exception e) {
        throw new RuntimeException(String.format("Error retrieving reference ID from %s.%s", entity.getClass().getSimpleName(), property), e);
    }
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) AbstractRecord(org.eclipse.persistence.internal.sessions.AbstractRecord) DatabaseMapping(org.eclipse.persistence.mappings.DatabaseMapping) Method(java.lang.reflect.Method) AbstractColumnMapping(org.eclipse.persistence.mappings.foundation.AbstractColumnMapping) FetchGroupTracker(org.eclipse.persistence.queries.FetchGroupTracker) DatabaseValueHolder(org.eclipse.persistence.internal.indirection.DatabaseValueHolder) MetaClass(com.haulmont.chile.core.model.MetaClass) ValueHolderInterface(org.eclipse.persistence.indirection.ValueHolderInterface) DatabaseField(org.eclipse.persistence.internal.helper.DatabaseField) FetchGroup(org.eclipse.persistence.queries.FetchGroup) Converter(org.eclipse.persistence.mappings.converters.Converter) MetaProperty(com.haulmont.chile.core.model.MetaProperty) Session(org.eclipse.persistence.sessions.Session)

Example 23 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class PersistenceTools method getOldEnumValue.

/**
 * Returns an old value of an enum attribute changed in the current transaction. The entity must be in the Managed state.
 * <p>
 * Unlike {@link #getOldValue(Entity, String)}, returns enum value and not its id.
 *
 * @param entity    entity instance
 * @param attribute attribute name
 * @return  an old value stored in the database. For a new entity returns null.
 * @throws IllegalArgumentException if the entity is not persistent or not in the Managed state
 */
@Nullable
public EnumClass getOldEnumValue(Entity entity, String attribute) {
    Object value = getOldValue(entity, attribute);
    if (value == null)
        return null;
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    MetaProperty metaProperty = metaClass.getPropertyNN(attribute);
    if (metaProperty.getRange().isEnum()) {
        for (Object o : metaProperty.getRange().asEnumeration().getValues()) {
            EnumClass enumValue = (EnumClass) o;
            if (value.equals(enumValue.getId()))
                return enumValue;
        }
    }
    return null;
}
Also used : MetaClass(com.haulmont.chile.core.model.MetaClass) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) MetaProperty(com.haulmont.chile.core.model.MetaProperty) Nullable(javax.annotation.Nullable)

Example 24 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class AttributeSecuritySupport method applySecurityToFetchGroup.

protected void applySecurityToFetchGroup(Entity entity) {
    if (entity == null) {
        return;
    }
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    FetchGroupTracker fetchGroupTracker = (FetchGroupTracker) entity;
    FetchGroup fetchGroup = fetchGroupTracker._persistence_getFetchGroup();
    SecurityState securityState = getSecurityState(entity);
    if (fetchGroup != null) {
        List<String> attributesToRemove = new ArrayList<>();
        for (String attrName : fetchGroup.getAttributeNames()) {
            String[] parts = attrName.split("\\.");
            if (parts.length > 0 && BaseEntityInternalAccess.isHiddenOrReadOnly(securityState, parts[0])) {
                attributesToRemove.add(attrName);
            } else {
                MetaClass currentMetaClass = metaClass;
                for (String part : parts) {
                    if (!security.isEntityAttrUpdatePermitted(currentMetaClass, part)) {
                        attributesToRemove.add(attrName);
                        break;
                    }
                    MetaProperty metaProperty = currentMetaClass.getPropertyNN(part);
                    if (metaProperty.getRange().isClass()) {
                        currentMetaClass = metaProperty.getRange().asClass();
                    }
                }
            }
        }
        if (!attributesToRemove.isEmpty()) {
            List<String> attributeNames = new ArrayList<>(fetchGroup.getAttributeNames());
            attributeNames.removeAll(attributesToRemove);
            fetchGroupTracker._persistence_setFetchGroup(new CubaEntityFetchGroup(attributeNames));
        }
    } else {
        List<String> attributeNames = new ArrayList<>();
        for (MetaProperty metaProperty : metaClass.getProperties()) {
            String propertyName = metaProperty.getName();
            if (metadataTools.isSystem(metaProperty)) {
                attributeNames.add(propertyName);
            }
            if (security.isEntityAttrUpdatePermitted(metaClass, propertyName) && !BaseEntityInternalAccess.isHiddenOrReadOnly(securityState, propertyName)) {
                attributeNames.add(metaProperty.getName());
            }
        }
        fetchGroupTracker._persistence_setFetchGroup(new CubaEntityFetchGroup(attributeNames));
    }
}
Also used : FetchGroupTracker(org.eclipse.persistence.queries.FetchGroupTracker) CubaEntityFetchGroup(com.haulmont.cuba.core.sys.persistence.CubaEntityFetchGroup) MetaClass(com.haulmont.chile.core.model.MetaClass) FetchGroup(org.eclipse.persistence.queries.FetchGroup) CubaEntityFetchGroup(com.haulmont.cuba.core.sys.persistence.CubaEntityFetchGroup) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 25 with MetaProperty

use of com.haulmont.chile.core.model.MetaProperty in project cuba by cuba-platform.

the class CrossDataStoreReferenceLoader method traverseView.

private void traverseView(View view, Map<Class<? extends Entity>, List<CrossDataStoreProperty>> crossPropertiesMap, Set<View> visited) {
    if (visited.contains(view))
        return;
    visited.add(view);
    String storeName = metadataTools.getStoreName(metaClass);
    Class<? extends Entity> entityClass = view.getEntityClass();
    for (ViewProperty viewProperty : view.getProperties()) {
        MetaProperty metaProperty = metadata.getClassNN(entityClass).getPropertyNN(viewProperty.getName());
        if (metaProperty.getRange().isClass()) {
            MetaClass propertyMetaClass = metaProperty.getRange().asClass();
            if (!Objects.equals(metadataTools.getStoreName(propertyMetaClass), storeName)) {
                List<String> relatedProperties = metadataTools.getRelatedProperties(metaProperty);
                if (relatedProperties.size() == 0) {
                    continue;
                }
                if (relatedProperties.size() > 1) {
                    log.warn("More than 1 related property is defined for attribute {}, skip handling cross-datastore reference", metaProperty);
                    continue;
                }
                List<CrossDataStoreProperty> crossProperties = crossPropertiesMap.computeIfAbsent(entityClass, k -> new ArrayList<>());
                if (crossProperties.stream().noneMatch(aProp -> aProp.property == metaProperty))
                    crossProperties.add(new CrossDataStoreProperty(metaProperty, viewProperty));
            }
            View propertyView = viewProperty.getView();
            if (propertyView != null) {
                traverseView(propertyView, crossPropertiesMap, visited);
            }
        }
    }
}
Also used : MetaClass(com.haulmont.chile.core.model.MetaClass) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Aggregations

MetaProperty (com.haulmont.chile.core.model.MetaProperty)157 MetaClass (com.haulmont.chile.core.model.MetaClass)102 Entity (com.haulmont.cuba.core.entity.Entity)44 MetaPropertyPath (com.haulmont.chile.core.model.MetaPropertyPath)26 BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)21 Range (com.haulmont.chile.core.model.Range)13 Nullable (javax.annotation.Nullable)11 CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)10 CategoryAttribute (com.haulmont.cuba.core.entity.CategoryAttribute)9 java.util (java.util)9 Element (org.dom4j.Element)9 com.haulmont.cuba.core.global (com.haulmont.cuba.core.global)8 Collectors (java.util.stream.Collectors)6 Inject (javax.inject.Inject)6 Query (com.haulmont.cuba.core.Query)5 SoftDelete (com.haulmont.cuba.core.entity.SoftDelete)5 Collection (java.util.Collection)5 MessageTools (com.haulmont.cuba.core.global.MessageTools)4 PropertyDatasource (com.haulmont.cuba.gui.data.PropertyDatasource)4 Logger (org.slf4j.Logger)4