Search in sources :

Example 21 with AssociationDescriptor

use of org.qi4j.api.association.AssociationDescriptor in project qi4j-sdk by Qi4j.

the class ValueDeserializerAdapter method deserializeValueComposite.

@SuppressWarnings("unchecked")
private <T> T deserializeValueComposite(ValueCompositeType valueCompositeType, Class<?> valueBuilderType, InputNodeType inputNode) throws Exception {
    final Map<String, Object> stateMap = new HashMap<>();
    // Properties
    for (PropertyDescriptor property : valueCompositeType.properties()) {
        String propertyName = property.qualifiedName().name();
        Object value;
        if (objectHasField(inputNode, propertyName)) {
            value = getObjectFieldValue(inputNode, propertyName, buildDeserializeInputNodeFunction(property.valueType()));
            TREE_PARSING_LOG.trace("In deserializeValueComposite(), getObjectFieldValue( {} ) for key {} returned '{}' of class {}", inputNode, propertyName, value, value == null ? "N/A" : value.getClass());
            if (property.isImmutable()) {
                if (value instanceof Set) {
                    value = Collections.unmodifiableSet((Set<?>) value);
                } else if (value instanceof List) {
                    value = Collections.unmodifiableList((List<?>) value);
                } else if (value instanceof Map) {
                    value = Collections.unmodifiableMap((Map<?, ?>) value);
                }
            }
            TREE_PARSING_LOG.trace("Property {}#{}( {} ) deserialized value is '{}' of class {}", property.qualifiedName().type(), property.qualifiedName().name(), property.valueType(), value, value == null ? "N/A" : value.getClass());
        } else {
            // Serialized object does not contain the field, try to default it
            value = property.initialValue(valuesModule());
            TREE_PARSING_LOG.trace("Property {} was not defined in serialized object and has been defaulted to '{}'", property.qualifiedName(), value);
        }
        stateMap.put(propertyName, value);
    }
    // Associations
    for (AssociationDescriptor association : valueCompositeType.associations()) {
        String associationName = association.qualifiedName().name();
        if (objectHasField(inputNode, associationName)) {
            Object value = getObjectFieldValue(inputNode, associationName, buildDeserializeInputNodeFunction(new ValueType(EntityReference.class)));
            stateMap.put(associationName, value);
        }
    }
    // ManyAssociations
    for (AssociationDescriptor manyAssociation : valueCompositeType.manyAssociations()) {
        String manyAssociationName = manyAssociation.qualifiedName().name();
        if (objectHasField(inputNode, manyAssociationName)) {
            Object value = getObjectFieldValue(inputNode, manyAssociationName, buildDeserializeInputNodeFunction(new CollectionType(Collection.class, new ValueType(EntityReference.class))));
            stateMap.put(manyAssociationName, value);
        }
    }
    // NamedAssociations
    for (AssociationDescriptor namedAssociation : valueCompositeType.namedAssociations()) {
        String namedAssociationName = namedAssociation.qualifiedName().name();
        if (objectHasField(inputNode, namedAssociationName)) {
            Object value = getObjectFieldValue(inputNode, namedAssociationName, buildDeserializeInputNodeFunction(MapType.of(String.class, EntityReference.class)));
            stateMap.put(namedAssociationName, value);
        }
    }
    ValueBuilder<?> valueBuilder = buildNewValueBuilderWithState(valueBuilderType, stateMap);
    // Unchecked cast because the builder could use a type != T
    return (T) valueBuilder.newInstance();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) HashMap(java.util.HashMap) ValueType(org.qi4j.api.type.ValueType) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) CollectionType(org.qi4j.api.type.CollectionType) EntityReference(org.qi4j.api.entity.EntityReference) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 22 with AssociationDescriptor

use of org.qi4j.api.association.AssociationDescriptor in project qi4j-sdk by Qi4j.

the class PreferencesEntityStoreMixin method entityStateOf.

@Override
public EntityState entityStateOf(EntityStoreUnitOfWork unitOfWork, EntityReference identity) {
    try {
        DefaultEntityStoreUnitOfWork desuw = (DefaultEntityStoreUnitOfWork) unitOfWork;
        Module module = desuw.module();
        if (!root.nodeExists(identity.identity())) {
            throw new NoSuchEntityException(identity, UnknownType.class);
        }
        Preferences entityPrefs = root.node(identity.identity());
        String type = entityPrefs.get("type", null);
        EntityStatus status = EntityStatus.LOADED;
        EntityDescriptor entityDescriptor = module.entityDescriptor(type);
        if (entityDescriptor == null) {
            throw new EntityTypeNotFoundException(type);
        }
        Map<QualifiedName, Object> properties = new HashMap<>();
        Preferences propsPrefs = null;
        for (PropertyDescriptor persistentPropertyDescriptor : entityDescriptor.state().properties()) {
            if (persistentPropertyDescriptor.qualifiedName().name().equals("identity")) {
                // Fake identity property
                properties.put(persistentPropertyDescriptor.qualifiedName(), identity.identity());
                continue;
            }
            if (propsPrefs == null) {
                propsPrefs = entityPrefs.node("properties");
            }
            ValueType propertyType = persistentPropertyDescriptor.valueType();
            Class<?> mainType = propertyType.mainType();
            if (Number.class.isAssignableFrom(mainType)) {
                if (mainType.equals(Long.class)) {
                    properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, LONG_PARSER));
                } else if (mainType.equals(Integer.class)) {
                    properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, INT_PARSER));
                } else if (mainType.equals(Double.class)) {
                    properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, DOUBLE_PARSER));
                } else if (mainType.equals(Float.class)) {
                    properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, FLOAT_PARSER));
                } else {
                    // Load as string even though it's a number
                    String json = propsPrefs.get(persistentPropertyDescriptor.qualifiedName().name(), null);
                    Object value;
                    if (json == null) {
                        value = null;
                    } else {
                        value = valueSerialization.deserialize(persistentPropertyDescriptor.valueType(), json);
                    }
                    properties.put(persistentPropertyDescriptor.qualifiedName(), value);
                }
            } else if (mainType.equals(Boolean.class)) {
                Boolean initialValue = (Boolean) persistentPropertyDescriptor.initialValue(module);
                properties.put(persistentPropertyDescriptor.qualifiedName(), propsPrefs.getBoolean(persistentPropertyDescriptor.qualifiedName().name(), initialValue == null ? false : initialValue));
            } else if (propertyType instanceof ValueCompositeType || propertyType instanceof MapType || propertyType instanceof CollectionType || propertyType instanceof EnumType) {
                String json = propsPrefs.get(persistentPropertyDescriptor.qualifiedName().name(), null);
                Object value;
                if (json == null) {
                    value = null;
                } else {
                    value = valueSerialization.deserialize(persistentPropertyDescriptor.valueType(), json);
                }
                properties.put(persistentPropertyDescriptor.qualifiedName(), value);
            } else {
                String json = propsPrefs.get(persistentPropertyDescriptor.qualifiedName().name(), null);
                if (json == null) {
                    if (persistentPropertyDescriptor.initialValue(module) != null) {
                        properties.put(persistentPropertyDescriptor.qualifiedName(), persistentPropertyDescriptor.initialValue(module));
                    } else {
                        properties.put(persistentPropertyDescriptor.qualifiedName(), null);
                    }
                } else {
                    Object value = valueSerialization.deserialize(propertyType, json);
                    properties.put(persistentPropertyDescriptor.qualifiedName(), value);
                }
            }
        }
        // Associations
        Map<QualifiedName, EntityReference> associations = new HashMap<>();
        Preferences assocs = null;
        for (AssociationDescriptor associationType : entityDescriptor.state().associations()) {
            if (assocs == null) {
                assocs = entityPrefs.node("associations");
            }
            String associatedEntity = assocs.get(associationType.qualifiedName().name(), null);
            EntityReference value = associatedEntity == null ? null : EntityReference.parseEntityReference(associatedEntity);
            associations.put(associationType.qualifiedName(), value);
        }
        // ManyAssociations
        Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>();
        Preferences manyAssocs = null;
        for (AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations()) {
            if (manyAssocs == null) {
                manyAssocs = entityPrefs.node("manyassociations");
            }
            List<EntityReference> references = new ArrayList<>();
            String entityReferences = manyAssocs.get(manyAssociationType.qualifiedName().name(), null);
            if (entityReferences == null) {
                // ManyAssociation not found, default to empty one
                manyAssociations.put(manyAssociationType.qualifiedName(), references);
            } else {
                String[] refs = entityReferences.split("\n");
                for (String ref : refs) {
                    EntityReference value = ref == null ? null : EntityReference.parseEntityReference(ref);
                    references.add(value);
                }
                manyAssociations.put(manyAssociationType.qualifiedName(), references);
            }
        }
        // NamedAssociations
        Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>();
        Preferences namedAssocs = null;
        for (AssociationDescriptor namedAssociationType : entityDescriptor.state().namedAssociations()) {
            if (namedAssocs == null) {
                namedAssocs = entityPrefs.node("namedassociations");
            }
            Map<String, EntityReference> references = new LinkedHashMap<>();
            String entityReferences = namedAssocs.get(namedAssociationType.qualifiedName().name(), null);
            if (entityReferences == null) {
                // NamedAssociation not found, default to empty one
                namedAssociations.put(namedAssociationType.qualifiedName(), references);
            } else {
                String[] namedRefs = entityReferences.split("\n");
                if (namedRefs.length % 2 != 0) {
                    throw new EntityStoreException("Invalid NamedAssociation storage format");
                }
                for (int idx = 0; idx < namedRefs.length; idx += 2) {
                    String name = namedRefs[idx];
                    String ref = namedRefs[idx + 1];
                    references.put(name, EntityReference.parseEntityReference(ref));
                }
                namedAssociations.put(namedAssociationType.qualifiedName(), references);
            }
        }
        return new DefaultEntityState(desuw, entityPrefs.get("version", ""), entityPrefs.getLong("modified", unitOfWork.currentTime()), identity, status, entityDescriptor, properties, associations, manyAssociations, namedAssociations);
    } catch (ValueSerializationException | BackingStoreException e) {
        throw new EntityStoreException(e);
    }
}
Also used : EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) DefaultEntityState(org.qi4j.spi.entitystore.helpers.DefaultEntityState) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) MapType(org.qi4j.api.type.MapType) LinkedHashMap(java.util.LinkedHashMap) EnumType(org.qi4j.api.type.EnumType) CollectionType(org.qi4j.api.type.CollectionType) EntityReference(org.qi4j.api.entity.EntityReference) DefaultEntityStoreUnitOfWork(org.qi4j.spi.entitystore.DefaultEntityStoreUnitOfWork) EntityStatus(org.qi4j.spi.entity.EntityStatus) List(java.util.List) ArrayList(java.util.ArrayList) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) Preferences(java.util.prefs.Preferences) PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) ValueType(org.qi4j.api.type.ValueType) QualifiedName(org.qi4j.api.common.QualifiedName) BackingStoreException(java.util.prefs.BackingStoreException) NoSuchEntityException(org.qi4j.api.unitofwork.NoSuchEntityException) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) Module(org.qi4j.api.structure.Module) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ValueCompositeType(org.qi4j.api.type.ValueCompositeType)

Example 23 with AssociationDescriptor

use of org.qi4j.api.association.AssociationDescriptor in project qi4j-sdk by Qi4j.

the class SQLEntityStoreMixin method readEntityState.

protected DefaultEntityState readEntityState(DefaultEntityStoreUnitOfWork unitOfWork, Reader entityState) throws EntityStoreException {
    try {
        Module module = unitOfWork.module();
        JSONObject jsonObject = new JSONObject(new JSONTokener(entityState));
        EntityStatus status = EntityStatus.LOADED;
        String version = jsonObject.getString(JSONKeys.VERSION);
        long modified = jsonObject.getLong(JSONKeys.MODIFIED);
        String identity = jsonObject.getString(JSONKeys.IDENTITY);
        // Check if version is correct
        String currentAppVersion = jsonObject.optString(JSONKeys.APPLICATION_VERSION, "0.0");
        if (!currentAppVersion.equals(application.version())) {
            if (migration != null) {
                migration.migrate(jsonObject, application.version(), this);
            } else {
                // Do nothing - set version to be correct
                jsonObject.put(JSONKeys.APPLICATION_VERSION, application.version());
            }
            LOGGER.trace("Updated version nr on {} from {} to {}", identity, currentAppVersion, application.version());
            // State changed
            status = EntityStatus.UPDATED;
        }
        String type = jsonObject.getString(JSONKeys.TYPE);
        EntityDescriptor entityDescriptor = module.entityDescriptor(type);
        if (entityDescriptor == null) {
            throw new EntityTypeNotFoundException(type);
        }
        Map<QualifiedName, Object> properties = new HashMap<>();
        JSONObject props = jsonObject.getJSONObject(JSONKeys.PROPERTIES);
        for (PropertyDescriptor propertyDescriptor : entityDescriptor.state().properties()) {
            Object jsonValue;
            try {
                jsonValue = props.get(propertyDescriptor.qualifiedName().name());
            } catch (JSONException e) {
                // Value not found, default it
                Object initialValue = propertyDescriptor.initialValue(module);
                properties.put(propertyDescriptor.qualifiedName(), initialValue);
                status = EntityStatus.UPDATED;
                continue;
            }
            if (JSONObject.NULL.equals(jsonValue)) {
                properties.put(propertyDescriptor.qualifiedName(), null);
            } else {
                Object value = valueSerialization.deserialize(propertyDescriptor.valueType(), jsonValue.toString());
                properties.put(propertyDescriptor.qualifiedName(), value);
            }
        }
        Map<QualifiedName, EntityReference> associations = new HashMap<>();
        JSONObject assocs = jsonObject.getJSONObject(JSONKeys.ASSOCIATIONS);
        for (AssociationDescriptor associationType : entityDescriptor.state().associations()) {
            try {
                Object jsonValue = assocs.get(associationType.qualifiedName().name());
                EntityReference value = jsonValue == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) jsonValue);
                associations.put(associationType.qualifiedName(), value);
            } catch (JSONException e) {
                // Association not found, default it to null
                associations.put(associationType.qualifiedName(), null);
                status = EntityStatus.UPDATED;
            }
        }
        JSONObject manyAssocs = jsonObject.getJSONObject(JSONKeys.MANY_ASSOCIATIONS);
        Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>();
        for (AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations()) {
            List<EntityReference> references = new ArrayList<>();
            try {
                JSONArray jsonValues = manyAssocs.getJSONArray(manyAssociationType.qualifiedName().name());
                for (int i = 0; i < jsonValues.length(); i++) {
                    Object jsonValue = jsonValues.getString(i);
                    EntityReference value = jsonValue == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) jsonValue);
                    references.add(value);
                }
                manyAssociations.put(manyAssociationType.qualifiedName(), references);
            } catch (JSONException e) {
                // ManyAssociation not found, default to empty one
                manyAssociations.put(manyAssociationType.qualifiedName(), references);
            }
        }
        JSONObject namedAssocs = jsonObject.has(JSONKeys.NAMED_ASSOCIATIONS) ? jsonObject.getJSONObject(JSONKeys.NAMED_ASSOCIATIONS) : new JSONObject();
        Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>();
        for (AssociationDescriptor namedAssociationType : entityDescriptor.state().namedAssociations()) {
            Map<String, EntityReference> references = new LinkedHashMap<>();
            try {
                JSONObject jsonValues = namedAssocs.getJSONObject(namedAssociationType.qualifiedName().name());
                JSONArray names = jsonValues.names();
                if (names != null) {
                    for (int idx = 0; idx < names.length(); idx++) {
                        String name = names.getString(idx);
                        String jsonValue = jsonValues.getString(name);
                        references.put(name, EntityReference.parseEntityReference(jsonValue));
                    }
                }
                namedAssociations.put(namedAssociationType.qualifiedName(), references);
            } catch (JSONException e) {
                // NamedAssociation not found, default to empty one
                namedAssociations.put(namedAssociationType.qualifiedName(), references);
            }
        }
        return new DefaultEntityState(unitOfWork, version, modified, EntityReference.parseEntityReference(identity), status, entityDescriptor, properties, associations, manyAssociations, namedAssociations);
    } catch (JSONException e) {
        throw new EntityStoreException(e);
    }
}
Also used : EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) DefaultEntityState(org.qi4j.spi.entitystore.helpers.DefaultEntityState) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) LinkedHashMap(java.util.LinkedHashMap) EntityReference(org.qi4j.api.entity.EntityReference) EntityStatus(org.qi4j.spi.entity.EntityStatus) List(java.util.List) ArrayList(java.util.ArrayList) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) QualifiedName(org.qi4j.api.common.QualifiedName) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONTokener(org.json.JSONTokener) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) Module(org.qi4j.api.structure.Module) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 24 with AssociationDescriptor

use of org.qi4j.api.association.AssociationDescriptor in project qi4j-sdk by Qi4j.

the class ValueToEntityMixin method doUnQualifiedUpdate.

private void doUnQualifiedUpdate(AssociationStateHolder eState, AssociationStateDescriptor eStateDesc, AssociationStateHolder vState, AssociationStateDescriptor vStateDesc) {
    for (PropertyDescriptor ePropDesc : eStateDesc.properties()) {
        if (IDENTITY_STATE_NAME.equals(ePropDesc.qualifiedName())) {
            // Ignore Identity, could be logged
            continue;
        }
        try {
            PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(ePropDesc.qualifiedName().name());
            eState.propertyFor(ePropDesc.accessor()).set(vState.propertyFor(vPropDesc.accessor()).get());
        } catch (IllegalArgumentException propNotFoundOnValue) {
        // Property not found on Value, do nothing
        }
    }
    for (AssociationDescriptor eAssocDesc : eStateDesc.associations()) {
        Association<Object> eAssoc = eState.associationFor(eAssocDesc.accessor());
        try {
            AssociationDescriptor vAssocDesc = vStateDesc.getAssociationByName(eAssocDesc.qualifiedName().name());
            eAssoc.set(vState.associationFor(vAssocDesc.accessor()).get());
        } catch (IllegalArgumentException assocNotFoundOnValue) {
            // Association not found on Value, find Property<String> and load associated Entity
            try {
                PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(eAssocDesc.qualifiedName().name());
                if (STRING_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                    String assocId = (String) vState.propertyFor(vPropDesc.accessor()).get();
                    if (assocId != null) {
                        eAssoc.set(module.currentUnitOfWork().get((Class) eAssocDesc.type(), assocId));
                    } else {
                        eAssoc.set(null);
                    }
                }
            } catch (IllegalArgumentException propNotFoundOnValue) {
            // Do nothing
            }
        }
    }
    for (AssociationDescriptor eAssocDesc : eStateDesc.manyAssociations()) {
        ManyAssociation<Object> eManyAssoc = eState.manyAssociationFor(eAssocDesc.accessor());
        try {
            AssociationDescriptor vAssDesc = vStateDesc.getManyAssociationByName(eAssocDesc.qualifiedName().name());
            ManyAssociation<Object> vManyAss = vState.manyAssociationFor(vAssDesc.accessor());
            for (Object ass : eManyAssoc.toList()) {
                eManyAssoc.remove(ass);
            }
            for (Object ass : vManyAss.toList()) {
                eManyAssoc.add(ass);
            }
        } catch (IllegalArgumentException assNotFoundOnValue) {
            // ManyAssociation not found on Value, find Property<List<String>> and load associated Entities
            try {
                PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(eAssocDesc.qualifiedName().name());
                if (STRING_COLLECTION_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                    Collection<String> vAssocState = (Collection) vState.propertyFor(vPropDesc.accessor()).get();
                    for (Object ass : eManyAssoc.toList()) {
                        eManyAssoc.remove(ass);
                    }
                    if (vAssocState != null) {
                        for (String eachAssoc : vAssocState) {
                            eManyAssoc.add(module.currentUnitOfWork().get((Class) eAssocDesc.type(), eachAssoc));
                        }
                    }
                }
            } catch (IllegalArgumentException propNotFoundOnValue) {
            // Do nothing
            }
        }
    }
    for (AssociationDescriptor eAssocDesc : eStateDesc.namedAssociations()) {
        NamedAssociation<Object> eNamedAssoc = eState.namedAssociationFor(eAssocDesc.accessor());
        try {
            AssociationDescriptor vAssocDesc = vStateDesc.getNamedAssociationByName(eAssocDesc.qualifiedName().name());
            NamedAssociation<Object> vNamedAssoc = vState.namedAssociationFor(vAssocDesc.accessor());
            for (String assocName : Iterables.toList(eNamedAssoc)) {
                eNamedAssoc.remove(assocName);
            }
            for (Map.Entry<String, Object> assocEntry : vNamedAssoc.toMap().entrySet()) {
                eNamedAssoc.put(assocEntry.getKey(), assocEntry.getValue());
            }
        } catch (IllegalArgumentException assocNotFoundOnValue) {
            // NamedAssociation not found on Value, find Property<Map<String,String>> and load associated Entities
            try {
                PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(eAssocDesc.qualifiedName().name());
                if (STRING_MAP_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                    Map<String, String> vAssocState = (Map) vState.propertyFor(vPropDesc.accessor()).get();
                    for (String assocName : Iterables.toList(eNamedAssoc)) {
                        eNamedAssoc.remove(assocName);
                    }
                    if (vAssocState != null) {
                        for (Map.Entry<String, String> assocEntry : vAssocState.entrySet()) {
                            eNamedAssoc.put(assocEntry.getKey(), module.currentUnitOfWork().get((Class) eAssocDesc.type(), assocEntry.getValue()));
                        }
                    }
                }
            } catch (IllegalArgumentException propNotFoundOnValue) {
            // Do nothing
            }
        }
    }
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) Collection(java.util.Collection) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 25 with AssociationDescriptor

use of org.qi4j.api.association.AssociationDescriptor in project qi4j-sdk by Qi4j.

the class ValueToEntityMixin method doUnqualifiedConversion.

private <T> EntityBuilder<?> doUnqualifiedConversion(Class<T> entityType, String identity, final AssociationStateHolder vState, final AssociationStateDescriptor vStateDesc) {
    Function<PropertyDescriptor, Object> props = new Function<PropertyDescriptor, Object>() {

        @Override
        public Object map(PropertyDescriptor ePropDesc) {
            String propName = ePropDesc.qualifiedName().name();
            try {
                PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(propName);
                return vState.propertyFor(vPropDesc.accessor()).get();
            } catch (IllegalArgumentException propNotFoundOnValue) {
                // Property not found on Value
                return null;
            }
        }
    };
    Function<AssociationDescriptor, EntityReference> assocs = new Function<AssociationDescriptor, EntityReference>() {

        @Override
        public EntityReference map(AssociationDescriptor eAssocDesc) {
            String assocName = eAssocDesc.qualifiedName().name();
            try {
                AssociationDescriptor vAssocDesc = vStateDesc.getAssociationByName(assocName);
                Object assocEntity = vState.associationFor(vAssocDesc.accessor()).get();
                return assocEntity == null ? null : EntityReference.entityReferenceFor(assocEntity);
            } catch (IllegalArgumentException assocNotFoundOnValue) {
                // Association not found on Value, find Property<String> and convert to Association
                try {
                    PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(assocName);
                    if (STRING_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                        String assocId = (String) vState.propertyFor(vPropDesc.accessor()).get();
                        return assocId == null ? null : EntityReference.parseEntityReference(assocId);
                    }
                    return null;
                } catch (IllegalArgumentException propNotFoundOnValue) {
                    return null;
                }
            }
        }
    };
    Function<AssociationDescriptor, Iterable<EntityReference>> manyAssocs = new Function<AssociationDescriptor, Iterable<EntityReference>>() {

        @Override
        public Iterable<EntityReference> map(AssociationDescriptor eAssocDesc) {
            String assocName = eAssocDesc.qualifiedName().name();
            try {
                AssociationDescriptor vAssocDesc = vStateDesc.getManyAssociationByName(assocName);
                ManyAssociation<Object> vManyAssoc = vState.manyAssociationFor(vAssocDesc.accessor());
                return MANY_ASSOC_TO_ENTITY_REF_ITERABLE.map(vManyAssoc);
            } catch (IllegalArgumentException assocNotFoundOnValue) {
                // ManyAssociation not found on Value, find List<String> and convert to ManyAssociation
                try {
                    PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(assocName);
                    if (STRING_COLLECTION_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                        Collection<String> vAssocState = (Collection) vState.propertyFor(vPropDesc.accessor()).get();
                        return STRING_COLLEC_TO_ENTITY_REF_ITERABLE.map(vAssocState);
                    }
                    return Iterables.empty();
                } catch (IllegalArgumentException propNotFoundOnValue) {
                    return Iterables.empty();
                }
            }
        }
    };
    Function<AssociationDescriptor, Map<String, EntityReference>> namedAssocs = new Function<AssociationDescriptor, Map<String, EntityReference>>() {

        @Override
        public Map<String, EntityReference> map(AssociationDescriptor eAssocDesc) {
            String assocName = eAssocDesc.qualifiedName().name();
            try {
                AssociationDescriptor vAssocDesc = vStateDesc.getNamedAssociationByName(assocName);
                NamedAssociation<Object> vAssocState = vState.namedAssociationFor(vAssocDesc.accessor());
                return NAMED_ASSOC_TO_ENTITY_REF_MAP.map(vAssocState);
            } catch (IllegalArgumentException assocNotFoundOnValue) {
                // Find Map<String,String> Property and convert to NamedAssociation
                try {
                    PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(assocName);
                    if (STRING_MAP_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                        Map<String, String> vAssocState = (Map) vState.propertyFor(vPropDesc.accessor()).get();
                        return STRING_MAP_TO_ENTITY_REF_MAP.map(vAssocState);
                    }
                    return Collections.EMPTY_MAP;
                } catch (IllegalArgumentException propNotFoundOnValue) {
                    return Collections.EMPTY_MAP;
                }
            }
        }
    };
    return module.currentUnitOfWork().newEntityBuilderWithState(entityType, identity, props, assocs, manyAssocs, namedAssocs);
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) Function(org.qi4j.functional.Function) EntityReference(org.qi4j.api.entity.EntityReference) Collection(java.util.Collection) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

AssociationDescriptor (org.qi4j.api.association.AssociationDescriptor)28 PropertyDescriptor (org.qi4j.api.property.PropertyDescriptor)15 EntityReference (org.qi4j.api.entity.EntityReference)13 Map (java.util.Map)8 QualifiedName (org.qi4j.api.common.QualifiedName)7 LinkedHashMap (java.util.LinkedHashMap)6 EntityDescriptor (org.qi4j.api.entity.EntityDescriptor)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 List (java.util.List)5 UnitOfWork (org.qi4j.api.unitofwork.UnitOfWork)5 Test (org.junit.Test)4 URI (org.openrdf.model.URI)4 ValueFactory (org.openrdf.model.ValueFactory)4 AbstractQi4jTest (org.qi4j.test.AbstractQi4jTest)4 Collection (java.util.Collection)3 AssociationStateDescriptor (org.qi4j.api.association.AssociationStateDescriptor)3 HashSet (java.util.HashSet)2 JSONArray (org.json.JSONArray)2 JSONException (org.json.JSONException)2