Search in sources :

Example 1 with BaseGenericIdEntity

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

the class ConverterHelper method fetchDynamicAttributes.

public static void fetchDynamicAttributes(Entity entity) {
    if (entity instanceof BaseGenericIdEntity) {
        LoadContext<BaseGenericIdEntity> loadContext = new LoadContext<>(entity.getMetaClass());
        loadContext.setId(entity.getId()).setLoadDynamicAttributes(true);
        DataService dataService = AppBeans.get(DataService.NAME, DataService.class);
        BaseGenericIdEntity reloaded = dataService.load(loadContext);
        if (reloaded != null) {
            ((BaseGenericIdEntity) entity).setDynamicAttributes(reloaded.getDynamicAttributes());
        } else {
            ((BaseGenericIdEntity) entity).setDynamicAttributes(new HashMap<>());
        }
    }
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) LoadContext(com.haulmont.cuba.core.global.LoadContext) DataService(com.haulmont.cuba.core.app.DataService)

Example 2 with BaseGenericIdEntity

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

the class ConverterHelper method getActualMetaProperties.

public static List<MetaProperty> getActualMetaProperties(MetaClass metaClass, Entity entity) {
    List<MetaProperty> result = new ArrayList<MetaProperty>(metaClass.getProperties());
    if (entity instanceof BaseGenericIdEntity && ((BaseGenericIdEntity) entity).getDynamicAttributes() != null) {
        Collection<CategoryAttribute> dynamicAttributes = AppBeans.get(DynamicAttributes.NAME, DynamicAttributes.class).getAttributesForMetaClass(metaClass);
        for (CategoryAttribute dynamicAttribute : dynamicAttributes) {
            result.add(DynamicAttributesUtils.getMetaPropertyPath(metaClass, dynamicAttribute).getMetaProperty());
        }
    }
    Collections.sort(result, PROPERTY_COMPARATOR);
    return result;
}
Also used : CategoryAttribute(com.haulmont.cuba.core.entity.CategoryAttribute) BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) MetaProperty(com.haulmont.chile.core.model.MetaProperty) DynamicAttributes(com.haulmont.cuba.core.app.dynamicattributes.DynamicAttributes)

Example 3 with BaseGenericIdEntity

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

the class JSONConverter method asJavaTree.

protected void asJavaTree(CommitRequest commitRequest, Entity entity, MetaClass metaClass, JSONObject json) throws JSONException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, IntrospectionException, ParseException {
    Iterator iter = json.keys();
    while (iter.hasNext()) {
        String propertyName = (String) iter.next();
        if ("id".equals(propertyName)) {
            // id was parsed already
            continue;
        }
        // version is readonly property
        if ("version".equals(propertyName)) {
            continue;
        }
        if (entity instanceof BaseGenericIdEntity && "__securityToken".equals(propertyName)) {
            byte[] securityToken = Base64.getDecoder().decode(json.getString("__securityToken"));
            SecurityState securityState = BaseEntityInternalAccess.getOrCreateSecurityState((BaseGenericIdEntity) entity);
            BaseEntityInternalAccess.setSecurityToken(securityState, securityToken);
            continue;
        }
        MetaPropertyPath metaPropertyPath = metadata.getTools().resolveMetaPropertyPath(metaClass, propertyName);
        checkNotNullArgument(metaPropertyPath, "Could not resolve property '%s' in '%s'", propertyName, metaClass);
        MetaProperty property = metaPropertyPath.getMetaProperty();
        if (!attrModifyPermitted(metaClass, property.getName()))
            continue;
        if (entity instanceof BaseGenericIdEntity && DynamicAttributesUtils.isDynamicAttribute(propertyName) && ((BaseGenericIdEntity) entity).getDynamicAttributes() == null) {
            ConverterHelper.fetchDynamicAttributes(entity);
        }
        if (json.get(propertyName) == null) {
            setField(entity, propertyName, null);
            continue;
        }
        switch(property.getType()) {
            case DATATYPE:
                String value = null;
                if (!json.isNull(propertyName)) {
                    value = json.get(propertyName).toString();
                }
                setField(entity, propertyName, property.getRange().asDatatype().parse(value));
                break;
            case ENUM:
                if (!json.isNull(propertyName)) {
                    setField(entity, propertyName, property.getRange().asEnumeration().parse(json.getString(propertyName)));
                } else {
                    setField(entity, propertyName, null);
                }
                break;
            case COMPOSITION:
            case ASSOCIATION:
                if ("null".equals(json.get(propertyName).toString())) {
                    setField(entity, propertyName, null);
                    break;
                }
                MetaClass propertyMetaClass = propertyMetaClass(property);
                // checks if the user permitted to read and update a property
                if (!updatePermitted(propertyMetaClass) && !readPermitted(propertyMetaClass))
                    break;
                if (!property.getRange().getCardinality().isMany()) {
                    JSONObject jsonChild = json.getJSONObject(propertyName);
                    Entity child;
                    MetaClass childMetaClass;
                    if (jsonChild.has("id")) {
                        String id = jsonChild.getString("id");
                        // will be registered later
                        if (commitRequest.getCommitIds().contains(id)) {
                            EntityLoadInfo loadInfo = EntityLoadInfo.parse(id);
                            if (loadInfo == null)
                                throw new IllegalArgumentException("Unable to parse ID: " + id);
                            Entity ref = metadata.create(loadInfo.getMetaClass());
                            ref.setValue("id", loadInfo.getId());
                            setField(entity, propertyName, ref);
                            break;
                        }
                        InstanceRef ref = commitRequest.parseInstanceRefAndRegister(id);
                        childMetaClass = ref.getMetaClass();
                        child = ref.getInstance();
                    } else {
                        childMetaClass = property.getRange().asClass();
                        child = metadata.create(childMetaClass);
                    }
                    asJavaTree(commitRequest, child, childMetaClass, jsonChild);
                    setField(entity, propertyName, child);
                } else {
                    JSONArray jsonArray = json.getJSONArray(propertyName);
                    Collection<Object> coll = property.getRange().isOrdered() ? new ArrayList<>() : new HashSet<>();
                    setField(entity, propertyName, coll);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        Object arrayValue = jsonArray.get(i);
                        if (arrayValue == null)
                            coll.add(null);
                        else {
                            // assuming no simple type here
                            JSONObject jsonChild = (JSONObject) arrayValue;
                            InstanceRef ref = commitRequest.parseInstanceRefAndRegister(jsonChild.getString("id"));
                            Entity child = ref.getInstance();
                            coll.add(child);
                            asJavaTree(commitRequest, child, ref.getMetaClass(), jsonChild);
                        }
                    }
                }
                break;
            default:
                throw new IllegalStateException("Unknown property type");
        }
    }
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) MetaPropertyPath(com.haulmont.chile.core.model.MetaPropertyPath) JSONArray(org.json.JSONArray) SecurityState(com.haulmont.cuba.core.entity.SecurityState) MetaClass(com.haulmont.chile.core.model.MetaClass) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 4 with BaseGenericIdEntity

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

the class JSONConverter method encodeInstance.

/**
 * Encodes the closure of a persistent instance into JSON.
 *
 * @param entity  the managed instance to be encoded. Can be null.
 * @param visited the persistent instances that had been encoded already. Must not be null or immutable.
 * @param view    view on which loaded the entity
 * @return the new element. The element has been appended as a child to the given parent in this method.
 */
protected MyJSONObject encodeInstance(final Entity entity, final Set<Entity> visited, MetaClass metaClass, View view) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
    if (visited == null) {
        throw new IllegalArgumentException("null closure for encoder");
    }
    if (entity == null) {
        return null;
    }
    boolean ref = !visited.add(entity);
    MyJSONObject root = new MyJSONObject(idof(entity), false);
    if (ref) {
        return root;
    }
    if (entity instanceof BaseGenericIdEntity) {
        byte[] securityToken = BaseEntityInternalAccess.getSecurityToken((BaseGenericIdEntity) entity);
        if (securityToken != null) {
            BaseGenericIdEntity baseGenericIdEntity = (BaseGenericIdEntity) entity;
            root.set("__securityToken", Base64.getEncoder().encodeToString(securityToken));
            String[] filteredAttributes = BaseEntityInternalAccess.getFilteredAttributes(baseGenericIdEntity);
            if (filteredAttributes != null) {
                MyJSONObject.Array array = new MyJSONObject.Array();
                Arrays.stream(filteredAttributes).forEach(obj -> array.add("\"" + obj + "\""));
                root.set("__filteredAttributes", array);
            }
        }
    }
    MetadataTools metadataTools = AppBeans.get(MetadataTools.NAME);
    List<MetaProperty> properties = ConverterHelper.getActualMetaProperties(metaClass, entity);
    for (MetaProperty property : properties) {
        if (metadataTools.isPersistent(property) && !PersistenceHelper.isLoaded(entity, property.getName())) {
            continue;
        }
        if (!attrViewPermitted(metaClass, property.getName()))
            continue;
        if (property.equals(metadataTools.getPrimaryKeyProperty(metaClass)) && !property.getJavaType().equals(String.class)) {
            // skipping id for non-String-key entities
            continue;
        }
        if (!isPropertyIncluded(view, property, metadataTools) && !DynamicAttributesUtils.isDynamicAttribute(property.getName())) {
            continue;
        }
        Object value = entity.getValue(property.getName());
        switch(property.getType()) {
            case DATATYPE:
                if (value != null) {
                    root.set(property.getName(), property.getRange().asDatatype().format(value));
                } else if (!DynamicAttributesUtils.isDynamicAttribute(property.getName())) {
                    root.set(property.getName(), null);
                }
                break;
            case ENUM:
                if (value != null) {
                    // noinspection unchecked
                    root.set(property.getName(), property.getRange().asEnumeration().format(value));
                } else {
                    root.set(property.getName(), null);
                }
                break;
            case COMPOSITION:
            case ASSOCIATION:
                {
                    MetaClass meta = propertyMetaClass(property);
                    // checks if the user permitted to read a property's entity
                    if (!readPermitted(meta))
                        break;
                    View propertyView = (view == null || view.getProperty(property.getName()) == null ? null : view.getProperty(property.getName()).getView());
                    if (!property.getRange().getCardinality().isMany()) {
                        if (value == null) {
                            root.set(property.getName(), null);
                        } else {
                            root.set(property.getName(), encodeInstance((Entity) value, visited, property.getRange().asClass(), propertyView));
                        }
                    } else {
                        if (value == null) {
                            root.set(property.getName(), null);
                            break;
                        }
                        MyJSONObject.Array array = new MyJSONObject.Array();
                        root.set(property.getName(), array);
                        Collection<?> members = (Collection<?>) value;
                        for (Object o : members) {
                            if (o == null) {
                                array.add(null);
                            } else {
                                array.add(encodeInstance((Entity) o, visited, property.getRange().asClass(), propertyView));
                            }
                        }
                    }
                    break;
                }
            default:
                throw new IllegalStateException("Unknown property type");
        }
    }
    return root;
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) JSONArray(org.json.JSONArray) MetaClass(com.haulmont.chile.core.model.MetaClass) JSONObject(org.json.JSONObject) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 5 with BaseGenericIdEntity

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

the class XMLConverter2 method encodeEntity.

protected void encodeEntity(Entity entity, HashSet<Entity> visited, View view, Element parentEl) throws Exception {
    if (entity == null) {
        parentEl.addAttribute("null", "true");
        return;
    }
    if (!readPermitted(entity.getMetaClass()))
        throw new IllegalAccessException();
    Element instanceEl = parentEl.addElement("instance");
    instanceEl.addAttribute("id", EntityLoadInfo.create(entity).toString());
    boolean entityAlreadyVisited = !visited.add(entity);
    if (entityAlreadyVisited) {
        return;
    }
    if (entity instanceof BaseGenericIdEntity) {
        byte[] securityToken = BaseEntityInternalAccess.getSecurityToken((BaseGenericIdEntity) entity);
        if (securityToken != null) {
            BaseGenericIdEntity baseGenericIdEntity = (BaseGenericIdEntity) entity;
            instanceEl.addElement("__securityToken").setText(Base64.getEncoder().encodeToString(securityToken));
            String[] filteredAttributes = BaseEntityInternalAccess.getFilteredAttributes(baseGenericIdEntity);
            if (filteredAttributes != null) {
                Element filteredAttributesElement = instanceEl.addElement("__filteredAttributes");
                Arrays.stream(filteredAttributes).forEach(obj -> filteredAttributesElement.addElement("a").setText(obj));
            }
        }
    }
    MetaClass metaClass = entity.getMetaClass();
    List<MetaProperty> orderedProperties = ConverterHelper.getActualMetaProperties(metaClass, entity);
    for (MetaProperty property : orderedProperties) {
        if (metadataTools.isPersistent(property) && !PersistenceHelper.isLoaded(entity, property.getName())) {
            continue;
        }
        if (!attrViewPermitted(metaClass, property.getName()))
            continue;
        if (!isPropertyIncluded(view, property) && !DynamicAttributesUtils.isDynamicAttribute(property.getName())) {
            continue;
        }
        Object value = entity.getValue(property.getName());
        switch(property.getType()) {
            case DATATYPE:
                if (property.equals(metadataTools.getPrimaryKeyProperty(metaClass)) && !property.getJavaType().equals(String.class)) {
                    // skipping id for non-String-key entities
                    continue;
                }
                Element fieldEl = instanceEl.addElement("field");
                fieldEl.addAttribute("name", property.getName());
                if (value != null) {
                    fieldEl.setText(property.getRange().asDatatype().format(value));
                } else if (!DynamicAttributesUtils.isDynamicAttribute(property.getName())) {
                    encodeNull(fieldEl);
                }
                break;
            case ENUM:
                fieldEl = instanceEl.addElement("field");
                fieldEl.addAttribute("name", property.getName());
                if (value == null) {
                    encodeNull(fieldEl);
                } else {
                    fieldEl.setText(property.getRange().asEnumeration().format(value));
                }
                break;
            case COMPOSITION:
            case ASSOCIATION:
                MetaClass meta = propertyMetaClass(property);
                // checks if the user permitted to read a property
                if (!readPermitted(meta)) {
                    break;
                }
                View propertyView = null;
                if (view != null) {
                    ViewProperty vp = view.getProperty(property.getName());
                    if (vp != null)
                        propertyView = vp.getView();
                }
                if (!property.getRange().getCardinality().isMany()) {
                    Element referenceEl = instanceEl.addElement("reference");
                    referenceEl.addAttribute("name", property.getName());
                    encodeEntity((Entity) value, visited, propertyView, referenceEl);
                } else {
                    Element collectionEl = instanceEl.addElement("collection");
                    collectionEl.addAttribute("name", property.getName());
                    if (value == null) {
                        encodeNull(collectionEl);
                        break;
                    }
                    for (Object childEntity : (Collection) value) {
                        encodeEntity((Entity) childEntity, visited, propertyView, collectionEl);
                    }
                }
                break;
            default:
                throw new IllegalStateException("Unknown property type");
        }
    }
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Element(org.dom4j.Element) MetaClass(com.haulmont.chile.core.model.MetaClass) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

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