Search in sources :

Example 6 with BaseGenericIdEntity

use of com.haulmont.cuba.core.entity.BaseGenericIdEntity in project cuba by cuba-platform.

the class EntityCopyUtils method copyCompositions.

public static void copyCompositions(Entity source, Entity dest) {
    Preconditions.checkNotNullArgument(source, "source is null");
    Preconditions.checkNotNullArgument(dest, "dest is null");
    if (source instanceof BaseDbGeneratedIdEntity && dest instanceof BaseDbGeneratedIdEntity) {
        ((BaseDbGeneratedIdEntity) dest).setId(((BaseDbGeneratedIdEntity) source).getId());
    }
    for (MetaProperty srcProperty : source.getMetaClass().getProperties()) {
        String name = srcProperty.getName();
        MetaProperty dstProperty = dest.getMetaClass().getProperty(name);
        if (dstProperty != null && !dstProperty.isReadOnly()) {
            try {
                Object value = source.getValue(name);
                if (value != null && srcProperty.getRange().getCardinality().isMany() && srcProperty.getType() == MetaProperty.Type.COMPOSITION) {
                    // noinspection unchecked
                    Collection<Entity> srcCollection = (Collection) value;
                    // Copy first to a Set to remove duplicates that could be created on repeated editing newly
                    // added items
                    Collection<Entity> tmpCollection = new LinkedHashSet<>();
                    for (Entity item : srcCollection) {
                        Entity copy = copyCompositions(item);
                        tmpCollection.add(copy);
                    }
                    Collection<Entity> dstCollection;
                    if (value instanceof List)
                        dstCollection = new ArrayList<>(tmpCollection);
                    else
                        dstCollection = tmpCollection;
                    dest.setValue(name, dstCollection);
                } else {
                    dest.setValue(name, source.getValue(name));
                }
            } catch (RuntimeException e) {
                Throwable cause = ExceptionUtils.getRootCause(e);
                if (cause == null)
                    cause = e;
                // ignore exception on copy for not loaded fields
                if (!isNotLoadedAttributeException(cause))
                    throw e;
            }
        }
    }
    if (source instanceof BaseGenericIdEntity && dest instanceof BaseGenericIdEntity) {
        BaseGenericIdEntity destGenericEntity = (BaseGenericIdEntity) dest;
        BaseGenericIdEntity<?> sourceGenericEntity = (BaseGenericIdEntity<?>) source;
        BaseEntityInternalAccess.setDetached(destGenericEntity, BaseEntityInternalAccess.isDetached(sourceGenericEntity));
        BaseEntityInternalAccess.setNew(destGenericEntity, BaseEntityInternalAccess.isNew(sourceGenericEntity));
        destGenericEntity.setDynamicAttributes(sourceGenericEntity.getDynamicAttributes());
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BaseDbGeneratedIdEntity(com.haulmont.cuba.core.entity.BaseDbGeneratedIdEntity) BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) ArrayList(java.util.ArrayList) BaseDbGeneratedIdEntity(com.haulmont.cuba.core.entity.BaseDbGeneratedIdEntity) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 7 with BaseGenericIdEntity

use of com.haulmont.cuba.core.entity.BaseGenericIdEntity 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 8 with BaseGenericIdEntity

use of com.haulmont.cuba.core.entity.BaseGenericIdEntity in project cuba by cuba-platform.

the class ObjectsCache method copy.

// Items passed to update method can be managed we send only their copies
protected Entity copy(BaseGenericIdEntity entity) {
    BaseGenericIdEntity result = (BaseGenericIdEntity) AppBeans.get(Metadata.class).create(entity.getMetaClass());
    result.setId(entity.getId());
    return result;
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity)

Example 9 with BaseGenericIdEntity

use of com.haulmont.cuba.core.entity.BaseGenericIdEntity in project cuba by cuba-platform.

the class BulkEditorWindow method init.

@Override
public void init(Map<String, Object> params) {
    super.init(params);
    String width = themeConstants.get("cuba.gui.BulkEditorWindow.width");
    String height = themeConstants.get("cuba.gui.BulkEditorWindow.height");
    getDialogOptions().setWidth(width).setHeight(height);
    checkNotNullArgument(metaClass);
    checkNotNullArgument(selected);
    if (StringUtils.isNotBlank(exclude)) {
        excludeRegex = Pattern.compile(exclude);
    }
    for (ManagedField managedField : getManagedFields(metaClass)) {
        managedFields.put(managedField.getFqn(), managedField);
    }
    View view = createView(metaClass);
    items = loadItems(view);
    dsContext = new DsContextImpl(dataSupplier);
    dsContext.setFrameContext(getDsContext().getFrameContext());
    setDsContext(dsContext);
    datasource = new DatasourceImpl<>();
    datasource.setup(dsContext, dataSupplier, metaClass.getName() + "Ds", metaClass, view);
    ((DatasourceImpl) datasource).valid();
    dsContext.register(datasource);
    createNestedEmbeddedDatasources(datasource, metaClass, "");
    Entity instance = metadata.create(metaClass);
    if (loadDynamicAttributes && (instance instanceof BaseGenericIdEntity)) {
        ((BaseGenericIdEntity) instance).setDynamicAttributes(new HashMap<>());
    }
    createEmbeddedFields(metaClass, instance, "");
    datasource.setItem(instance);
    datasource.setAllowCommit(false);
    createDataComponents();
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) DatasourceImpl(com.haulmont.cuba.gui.data.impl.DatasourceImpl) EmbeddedDatasourceImpl(com.haulmont.cuba.gui.data.impl.EmbeddedDatasourceImpl) BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) DsContextImpl(com.haulmont.cuba.gui.data.impl.DsContextImpl)

Example 10 with BaseGenericIdEntity

use of com.haulmont.cuba.core.entity.BaseGenericIdEntity in project cuba by cuba-platform.

the class GlobalPersistentAttributesLoadChecker method isLoaded.

@Override
public boolean isLoaded(Object entity, String property) {
    MetaClass metaClass = metadata.getClassNN(entity.getClass());
    if (isDynamicAttribute(property)) {
        @SuppressWarnings("unchecked") Map<String, CategoryAttributeValue> dynamicAttributes = ((BaseGenericIdEntity) entity).getDynamicAttributes();
        if (dynamicAttributes == null) {
            return false;
        }
        String attributeCode = decodeAttributeCode(property);
        return dynamicAttributes.containsKey(attributeCode);
    }
    MetaProperty metaProperty = metaClass.getPropertyNN(property);
    if (!metadataTools.isPersistent(metaProperty)) {
        List<String> relatedProperties = metadataTools.getRelatedProperties(metaProperty);
        if (relatedProperties.isEmpty()) {
            return true;
        } else {
            for (String relatedProperty : relatedProperties) {
                if (!isLoaded(entity, relatedProperty))
                    return false;
            }
            return true;
        }
    }
    PropertyLoadedState isLoaded = isLoadedCommonCheck(entity, property);
    if (isLoaded != PropertyLoadedState.UNKNOWN) {
        return isLoaded == PropertyLoadedState.YES;
    }
    return isLoadedSpecificCheck(entity, property, metaClass, metaProperty);
}
Also used : MetaClass(com.haulmont.chile.core.model.MetaClass) BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) MetaProperty(com.haulmont.chile.core.model.MetaProperty) CategoryAttributeValue(com.haulmont.cuba.core.entity.CategoryAttributeValue)

Aggregations

BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)21 Entity (com.haulmont.cuba.core.entity.Entity)13 MetaProperty (com.haulmont.chile.core.model.MetaProperty)12 MetaClass (com.haulmont.chile.core.model.MetaClass)11 DynamicAttributesGuiTools (com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools)3 MetaPropertyPath (com.haulmont.chile.core.model.MetaPropertyPath)2 Categorized (com.haulmont.cuba.core.entity.Categorized)2 CategoryAttribute (com.haulmont.cuba.core.entity.CategoryAttribute)2 SecurityState (com.haulmont.cuba.core.entity.SecurityState)2 Element (org.dom4j.Element)2 FetchGroup (org.eclipse.persistence.queries.FetchGroup)2 FetchGroupTracker (org.eclipse.persistence.queries.FetchGroupTracker)2 JSONArray (org.json.JSONArray)2 JSONObject (org.json.JSONObject)2 MetadataObject (com.haulmont.chile.core.model.MetadataObject)1 AbstractInstance (com.haulmont.chile.core.model.impl.AbstractInstance)1 DataService (com.haulmont.cuba.core.app.DataService)1 DynamicAttributes (com.haulmont.cuba.core.app.dynamicattributes.DynamicAttributes)1 BaseDbGeneratedIdEntity (com.haulmont.cuba.core.entity.BaseDbGeneratedIdEntity)1 CategoryAttributeValue (com.haulmont.cuba.core.entity.CategoryAttributeValue)1