Search in sources :

Example 1 with FetchGroup

use of org.eclipse.persistence.queries.FetchGroup 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 2 with FetchGroup

use of org.eclipse.persistence.queries.FetchGroup in project cuba by cuba-platform.

the class FetchGroupManager method addView.

public void addView(JpaQuery query, String queryString, View view, boolean singleResultExpected) {
    Preconditions.checkNotNullArgument(query, "query is null");
    Preconditions.checkNotNullArgument(view, "view is null");
    Map<String, Object> hints = query.getHints();
    AttributeGroup ag = null;
    if (view.loadPartialEntities()) {
        if (hints != null)
            ag = (FetchGroup) hints.get(QueryHints.FETCH_GROUP);
        if (ag == null)
            ag = new FetchGroup();
    } else {
        if (hints != null)
            ag = (LoadGroup) hints.get(QueryHints.LOAD_GROUP);
        if (ag == null)
            ag = new LoadGroup();
    }
    applyView(query, queryString, ag, view, singleResultExpected);
}
Also used : AttributeGroup(org.eclipse.persistence.queries.AttributeGroup) FetchGroup(org.eclipse.persistence.queries.FetchGroup) LoadGroup(org.eclipse.persistence.queries.LoadGroup)

Example 3 with FetchGroup

use of org.eclipse.persistence.queries.FetchGroup in project cuba by cuba-platform.

the class FetchGroupManager method applyView.

private void applyView(JpaQuery query, String queryString, AttributeGroup attrGroup, View view, boolean singleResultExpected) {
    boolean useFetchGroup = attrGroup instanceof FetchGroup;
    FetchGroupDescription description = calculateFetchGroup(queryString, view, singleResultExpected, useFetchGroup);
    if (attrGroup instanceof FetchGroup)
        ((FetchGroup) attrGroup).setShouldLoadAll(true);
    if (log.isTraceEnabled())
        log.trace((useFetchGroup ? "Fetch" : "Load") + " group for " + view + ":\n" + description.getAttributes().stream().collect(Collectors.joining("\n")));
    for (String attribute : description.getAttributes()) {
        attrGroup.addAttribute(attribute);
    }
    MetaClass metaClass = metadata.getClassNN(view.getEntityClass());
    if (!metadataTools.isCacheable(metaClass)) {
        query.setHint(useFetchGroup ? QueryHints.FETCH_GROUP : QueryHints.LOAD_GROUP, attrGroup);
    }
    if (log.isDebugEnabled()) {
        String fetchModes = description.getHints().entrySet().stream().map(e -> e.getKey() + "=" + (e.getValue().equals(QueryHints.LEFT_FETCH) ? "JOIN" : "BATCH")).collect(Collectors.joining(", "));
        log.debug("Fetch modes for " + view + ": " + (fetchModes.equals("") ? "<none>" : fetchModes));
    }
    for (Map.Entry<String, String> entry : description.getHints().entrySet()) {
        query.setHint(entry.getValue(), entry.getKey());
    }
    if (description.hasBatches()) {
        query.setHint(QueryHints.BATCH_TYPE, "IN");
    }
}
Also used : SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) java.util(java.util) LoggerFactory(org.slf4j.LoggerFactory) MetaPropertyPath(com.haulmont.chile.core.model.MetaPropertyPath) StringUtils(org.apache.commons.lang3.StringUtils) MetaClass(com.haulmont.chile.core.model.MetaClass) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) JpaQuery(org.eclipse.persistence.jpa.JpaQuery) Inject(javax.inject.Inject) AttributeGroup(org.eclipse.persistence.queries.AttributeGroup) Method(java.lang.reflect.Method) Nullable(javax.annotation.Nullable) Logger(org.slf4j.Logger) ClassUtils(org.springframework.util.ClassUtils) Range(com.haulmont.chile.core.model.Range) MetaProperty(com.haulmont.chile.core.model.MetaProperty) EmbeddableEntity(com.haulmont.cuba.core.entity.EmbeddableEntity) QueryHints(org.eclipse.persistence.config.QueryHints) Collectors(java.util.stream.Collectors) Preconditions(com.haulmont.bali.util.Preconditions) Component(org.springframework.stereotype.Component) FetchGroup(org.eclipse.persistence.queries.FetchGroup) LoadGroup(org.eclipse.persistence.queries.LoadGroup) BaseUuidEntity(com.haulmont.cuba.core.entity.BaseUuidEntity) Entity(com.haulmont.cuba.core.entity.Entity) MetaClass(com.haulmont.chile.core.model.MetaClass) FetchGroup(org.eclipse.persistence.queries.FetchGroup)

Example 4 with FetchGroup

use of org.eclipse.persistence.queries.FetchGroup in project cuba by cuba-platform.

the class PersistenceTools method getReferenceId.

/**
 * Returns an ID of directly referenced entity without loading it from DB.
 * <p>
 * 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 (!entityStates.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.containsAttributeInternal(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 5 with FetchGroup

use of org.eclipse.persistence.queries.FetchGroup in project cuba by cuba-platform.

the class EclipseLinkDescriptorEventListener method postClone.

@Override
public void postClone(DescriptorEvent event) {
    // in shared cache mode, postBuild event is missed, so we repeat it here
    if (event.getObject() instanceof BaseGenericIdEntity) {
        BaseEntityInternalAccess.setNew((BaseGenericIdEntity) event.getObject(), false);
        BaseEntityInternalAccess.setDetached((BaseGenericIdEntity) event.getObject(), false);
    }
    if (event.getObject() instanceof FetchGroupTracker) {
        FetchGroupTracker entity = (FetchGroupTracker) event.getObject();
        FetchGroup fetchGroup = entity._persistence_getFetchGroup();
        if (fetchGroup != null && !(fetchGroup instanceof CubaEntityFetchGroup))
            entity._persistence_setFetchGroup(new CubaEntityFetchGroup(fetchGroup));
    }
    if (event.getObject() instanceof Entity)
        support.registerInstance((Entity) event.getObject(), event.getSession());
}
Also used : FetchGroupTracker(org.eclipse.persistence.queries.FetchGroupTracker) FetchGroup(org.eclipse.persistence.queries.FetchGroup)

Aggregations

FetchGroup (org.eclipse.persistence.queries.FetchGroup)11 FetchGroupTracker (org.eclipse.persistence.queries.FetchGroupTracker)8 MetaClass (com.haulmont.chile.core.model.MetaClass)3 MetaProperty (com.haulmont.chile.core.model.MetaProperty)3 AttributeGroup (org.eclipse.persistence.queries.AttributeGroup)3 LoadGroup (org.eclipse.persistence.queries.LoadGroup)3 BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)2 Entity (com.haulmont.cuba.core.entity.Entity)2 Method (java.lang.reflect.Method)2 Preconditions (com.haulmont.bali.util.Preconditions)1 MetaPropertyPath (com.haulmont.chile.core.model.MetaPropertyPath)1 Range (com.haulmont.chile.core.model.Range)1 BaseUuidEntity (com.haulmont.cuba.core.entity.BaseUuidEntity)1 EmbeddableEntity (com.haulmont.cuba.core.entity.EmbeddableEntity)1 SoftDelete (com.haulmont.cuba.core.entity.SoftDelete)1 com.haulmont.cuba.core.global (com.haulmont.cuba.core.global)1 CubaEntityFetchGroup (com.haulmont.cuba.core.sys.persistence.CubaEntityFetchGroup)1 java.util (java.util)1 Collectors (java.util.stream.Collectors)1 Nullable (javax.annotation.Nullable)1