Search in sources :

Example 6 with MetaClass

use of com.haulmont.chile.core.model.MetaClass 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 7 with MetaClass

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

the class JSONConverter method createEmptyInstance.

/**
 * Creates new entity instance from {@link com.haulmont.cuba.core.global.EntityLoadInfo}
 * and reset fields values
 */
protected Entity createEmptyInstance(EntityLoadInfo loadInfo) throws IllegalAccessException, InstantiationException {
    MetaClass metaClass = loadInfo.getMetaClass();
    Entity instance = metadata.create(metaClass);
    for (MetaProperty metaProperty : metaClass.getProperties()) {
        if (!metaProperty.isReadOnly())
            instance.setValue(metaProperty.getName(), null);
    }
    return instance;
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) MetaClass(com.haulmont.chile.core.model.MetaClass) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 8 with MetaClass

use of com.haulmont.chile.core.model.MetaClass 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 9 with MetaClass

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

the class JSONConverter method _parseEntity.

protected Entity _parseEntity(JSONObject json) {
    try {
        String id = json.getString("id");
        EntityLoadInfo loadInfo = EntityLoadInfo.parse(id);
        if (loadInfo == null)
            throw new IllegalArgumentException("JSON description of entity doesn't contain valid 'id' attribute");
        Entity instance = createEmptyInstance(loadInfo);
        setField(instance, "id", loadInfo.getId());
        MetaClass metaClass = loadInfo.getMetaClass();
        Iterator iter = json.keys();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if ("id".equals(key)) {
                // id was parsed already
                continue;
            }
            MetaProperty property = metaClass.getPropertyNN(key);
            switch(property.getType()) {
                case DATATYPE:
                    String value = null;
                    if (!json.isNull(key)) {
                        value = json.get(key).toString();
                    }
                    setField(instance, key, property.getRange().asDatatype().parse(value));
                    break;
                case ENUM:
                    if (!json.isNull(key)) {
                        setField(instance, key, property.getRange().asEnumeration().parse(json.getString(key)));
                    } else {
                        setField(instance, key, null);
                    }
                    break;
                case COMPOSITION:
                case ASSOCIATION:
                    if ("null".equals(json.get(key).toString())) {
                        setField(instance, key, null);
                        break;
                    }
                    if (!property.getRange().getCardinality().isMany()) {
                        JSONObject jsonChild = json.getJSONObject(key);
                        Object childInstance = _parseEntity(jsonChild);
                        setField(instance, key, childInstance);
                    } else {
                        JSONArray jsonArray = json.getJSONArray(key);
                        Class<?> propertyJavaType = property.getJavaType();
                        Collection<Object> coll;
                        if (List.class.isAssignableFrom(propertyJavaType))
                            coll = new ArrayList<>();
                        else if (Set.class.isAssignableFrom(propertyJavaType))
                            coll = new HashSet<>();
                        else
                            throw new RuntimeException("Datatype " + propertyJavaType.getName() + " of " + metaClass.getName() + "#" + property.getName() + " is not supported");
                        setField(instance, key, 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;
                                Object child = _parseEntity(jsonChild);
                                coll.add(child);
                            }
                        }
                    }
                    break;
                default:
                    throw new IllegalStateException("Unknown property type");
            }
        }
        return instance;
    } catch (Exception e) {
        throw new RuntimeException("Unable to parse entity", e);
    }
}
Also used : BaseGenericIdEntity(com.haulmont.cuba.core.entity.BaseGenericIdEntity) Entity(com.haulmont.cuba.core.entity.Entity) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ParseException(java.text.ParseException) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MimeTypeParseException(javax.activation.MimeTypeParseException) MetaClass(com.haulmont.chile.core.model.MetaClass) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 10 with MetaClass

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

the class XMLConverter method parseEntity.

private void parseEntity(CommitRequest commitRequest, Object bean, MetaClass metaClass, Node node) throws InstantiationException, IllegalAccessException, InvocationTargetException, IntrospectionException, ParseException {
    MetadataTools metadataTools = AppBeans.get(MetadataTools.NAME);
    NodeList fields = node.getChildNodes();
    for (int i = 0; i < fields.getLength(); i++) {
        Node fieldNode = fields.item(i);
        String fieldName = getFieldName(fieldNode);
        MetaProperty property = metaClass.getProperty(fieldName);
        if (!attrModifyPermitted(metaClass, property.getName()))
            continue;
        if (metadataTools.isTransient(bean, fieldName))
            continue;
        String xmlValue = fieldNode.getTextContent();
        if (isNullValue(fieldNode)) {
            setNullField(bean, fieldName);
            continue;
        }
        Object value;
        switch(property.getType()) {
            case DATATYPE:
                if (property.getAnnotatedElement().isAnnotationPresent(Id.class)) {
                    // it was parsed in the beginning
                    continue;
                }
                Class type = property.getRange().asDatatype().getJavaClass();
                if (!type.equals(String.class) && "null".equals(xmlValue)) {
                    value = null;
                } else {
                    value = property.getRange().asDatatype().parse(xmlValue);
                }
                setField(bean, fieldName, value);
                break;
            case ENUM:
                value = property.getRange().asEnumeration().parse(xmlValue);
                setField(bean, fieldName, value);
                break;
            case COMPOSITION:
            case ASSOCIATION:
                {
                    if ("null".equals(xmlValue)) {
                        setField(bean, fieldName, 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()) {
                        if (property.getAnnotatedElement().isAnnotationPresent(Embedded.class)) {
                            MetaClass embeddedMetaClass = property.getRange().asClass();
                            value = metadata.create(embeddedMetaClass);
                            parseEntity(commitRequest, value, embeddedMetaClass, fieldNode);
                        } else {
                            String id = getRefId(fieldNode);
                            // will be registered later
                            if (commitRequest.getCommitIds().contains(id)) {
                                EntityLoadInfo loadInfo = EntityLoadInfo.parse(id);
                                Entity ref = metadata.create(loadInfo.getMetaClass());
                                ref.setValue("id", loadInfo.getId());
                                setField(bean, fieldName, ref);
                                break;
                            }
                            value = parseEntityReference(fieldNode, commitRequest);
                        }
                        setField(bean, fieldName, value);
                    } else {
                        NodeList memberNodes = fieldNode.getChildNodes();
                        Collection<Object> members = property.getRange().isOrdered() ? new ArrayList<>() : new HashSet<>();
                        for (int memberIndex = 0; memberIndex < memberNodes.getLength(); memberIndex++) {
                            Node memberNode = memberNodes.item(memberIndex);
                            members.add(parseEntityReference(memberNode, commitRequest));
                        }
                        setField(bean, fieldName, members);
                    }
                    break;
                }
            default:
                throw new IllegalStateException("Unknown property type");
        }
    }
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) MetaClass(com.haulmont.chile.core.model.MetaClass) MetaClass(com.haulmont.chile.core.model.MetaClass) Embedded(javax.persistence.Embedded) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Aggregations

MetaClass (com.haulmont.chile.core.model.MetaClass)302 MetaProperty (com.haulmont.chile.core.model.MetaProperty)103 Entity (com.haulmont.cuba.core.entity.Entity)54 MetaPropertyPath (com.haulmont.chile.core.model.MetaPropertyPath)36 Nullable (javax.annotation.Nullable)25 BaseGenericIdEntity (com.haulmont.cuba.core.entity.BaseGenericIdEntity)24 Element (org.dom4j.Element)21 java.util (java.util)18 Inject (javax.inject.Inject)17 CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)16 Test (org.junit.Test)15 EntityManager (com.haulmont.cuba.core.EntityManager)14 CategoryAttribute (com.haulmont.cuba.core.entity.CategoryAttribute)14 com.haulmont.cuba.core.global (com.haulmont.cuba.core.global)13 Metadata (com.haulmont.cuba.core.global.Metadata)13 Logger (org.slf4j.Logger)13 LoggerFactory (org.slf4j.LoggerFactory)13 MetadataTools (com.haulmont.cuba.core.global.MetadataTools)12 Collectors (java.util.stream.Collectors)11 Range (com.haulmont.chile.core.model.Range)10