Search in sources :

Example 6 with MetaProperty

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

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

Example 8 with MetaProperty

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

the class XMLConverter method encodeEntityInstance.

/**
 * Encodes the closure of a persistent instance into a XML element.
 *
 * @param visited
 * @param entity    the managed instance to be encoded. Can be null.
 * @param parent    the parent XML element to which the new XML element be added. Must not be null. Must be
 *                  owned by a document.
 * @param isRef
 * @param metaClass @return the new element. The element has been appended as a child to the given parent in this method.
 * @param view view on which loaded the entity
 */
private Element encodeEntityInstance(HashSet<Entity> visited, final Entity entity, final Element parent, boolean isRef, MetaClass metaClass, View view) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
    if (!readPermitted(metaClass))
        return null;
    if (parent == null)
        throw new NullPointerException("No parent specified");
    Document doc = parent.getOwnerDocument();
    if (doc == null)
        throw new NullPointerException("No document specified");
    if (entity == null) {
        return encodeRef(parent, entity);
    }
    isRef |= !visited.add(entity);
    if (isRef) {
        return encodeRef(parent, entity);
    }
    Element root = doc.createElement(ELEMENT_INSTANCE);
    parent.appendChild(root);
    root.setAttribute(ATTR_ID, ior(entity));
    MetadataTools metadataTools = AppBeans.get(MetadataTools.NAME);
    List<MetaProperty> properties = ConverterHelper.getOrderedProperties(metaClass);
    for (MetaProperty property : properties) {
        Element child;
        if (!attrViewPermitted(metaClass, property.getName()))
            continue;
        if (!isPropertyIncluded(view, property, metadataTools)) {
            continue;
        }
        Object value = entity.getValue(property.getName());
        switch(property.getType()) {
            case DATATYPE:
                String nodeType;
                if (property.equals(metadataTools.getPrimaryKeyProperty(metaClass)) && !property.getJavaType().equals(String.class)) {
                    // skipping id for non-String-key entities
                    continue;
                } else if (property.getAnnotatedElement().isAnnotationPresent(Version.class)) {
                    nodeType = "version";
                } else {
                    nodeType = "basic";
                }
                child = doc.createElement(nodeType);
                child.setAttribute(ATTR_NAME, property.getName());
                if (value == null) {
                    encodeNull(child);
                } else {
                    String str = property.getRange().asDatatype().format(value);
                    encodeBasic(child, str, property.getJavaType());
                }
                break;
            case ENUM:
                child = doc.createElement("enum");
                child.setAttribute(ATTR_NAME, property.getName());
                if (value == null) {
                    encodeNull(child);
                } else {
                    // noinspection unchecked
                    String str = property.getRange().asEnumeration().format(value);
                    encodeBasic(child, str, property.getJavaType());
                }
                break;
            case COMPOSITION:
            case ASSOCIATION:
                {
                    MetaClass meta = propertyMetaClass(property);
                    // checks if the user permitted to read a property
                    if (!readPermitted(meta)) {
                        child = null;
                        break;
                    }
                    View propertyView = (view == null ? null : view.getProperty(property.getName()).getView());
                    if (!property.getRange().getCardinality().isMany()) {
                        boolean isEmbedded = property.getAnnotatedElement().isAnnotationPresent(Embedded.class);
                        child = doc.createElement(isEmbedded ? "embedded" : property.getRange().getCardinality().name().replace(UNDERSCORE, DASH).toLowerCase());
                        child.setAttribute(ATTR_NAME, property.getName());
                        if (isEmbedded) {
                            encodeEntityInstance(visited, (Entity) value, child, false, property.getRange().asClass(), propertyView);
                        } else {
                            encodeEntityInstance(visited, (Entity) value, child, false, property.getRange().asClass(), propertyView);
                        }
                    } else {
                        child = doc.createElement(getCollectionReferenceTag(property));
                        child.setAttribute(ATTR_NAME, property.getName());
                        child.setAttribute(ATTR_MEMBER_TYPE, typeOfEntityProperty(property));
                        if (value == null) {
                            encodeNull(child);
                            break;
                        }
                        Collection<?> members = (Collection<?>) value;
                        for (Object o : members) {
                            Element member = doc.createElement(ELEMENT_MEMBER);
                            child.appendChild(member);
                            if (o == null) {
                                encodeNull(member);
                            } else {
                                encodeEntityInstance(visited, (Entity) o, member, true, property.getRange().asClass(), propertyView);
                            }
                        }
                    }
                    break;
                }
            default:
                throw new IllegalStateException("Unknown property type");
        }
        if (child != null) {
            root.appendChild(child);
        }
    }
    return root;
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) MetaClass(com.haulmont.chile.core.model.MetaClass) Version(javax.persistence.Version) Embedded(javax.persistence.Embedded) MetaProperty(com.haulmont.chile.core.model.MetaProperty)

Example 9 with MetaProperty

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

Example 10 with MetaProperty

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

the class RemoveAction method checkRemovePermission.

protected boolean checkRemovePermission() {
    CollectionDatasource ds = target.getDatasource();
    if (ds instanceof PropertyDatasource) {
        PropertyDatasource propertyDatasource = (PropertyDatasource) ds;
        MetaClass parentMetaClass = propertyDatasource.getMaster().getMetaClass();
        MetaProperty metaProperty = propertyDatasource.getProperty();
        boolean modifyPermitted = security.isEntityAttrPermitted(parentMetaClass, metaProperty.getName(), EntityAttrAccess.MODIFY);
        if (!modifyPermitted) {
            return false;
        }
        if (metaProperty.getRange().getCardinality() != Range.Cardinality.MANY_TO_MANY) {
            boolean deletePermitted = security.isEntityOpPermitted(ds.getMetaClass(), EntityOp.DELETE);
            if (!deletePermitted) {
                return false;
            }
        }
    } else {
        boolean entityOpPermitted = security.isEntityOpPermitted(ds.getMetaClass(), EntityOp.DELETE);
        if (!entityOpPermitted) {
            return false;
        }
    }
    return true;
}
Also used : MetaClass(com.haulmont.chile.core.model.MetaClass) PropertyDatasource(com.haulmont.cuba.gui.data.PropertyDatasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) 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