Search in sources :

Example 21 with QualifiedName

use of org.qi4j.api.common.QualifiedName 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 22 with QualifiedName

use of org.qi4j.api.common.QualifiedName in project qi4j-sdk by Qi4j.

the class Triples method addTripleAssociation.

public Triple addTripleAssociation(AssociationFunction<?> associationReference, boolean optional) {
    String subject = "?entity";
    if (associationReference.traversedAssociation() != null) {
        subject = addTripleAssociation(associationReference.traversedAssociation(), false).value;
    }
    QualifiedName qualifiedName = QualifiedName.fromAccessor(associationReference.accessor());
    String prefix = addNamespace(qualifiedName.toNamespace());
    return addTriple(subject, prefix + ":" + qualifiedName.name(), optional);
}
Also used : QualifiedName(org.qi4j.api.common.QualifiedName)

Example 23 with QualifiedName

use of org.qi4j.api.common.QualifiedName in project qi4j-sdk by Qi4j.

the class PreferencesEntityStoreMixin method writeEntityState.

protected void writeEntityState(DefaultEntityState state, Preferences entityPrefs, String identity, long lastModified) throws EntityStoreException {
    try {
        // Store into Preferences API
        entityPrefs.put("type", first(state.entityDescriptor().types()).getName());
        entityPrefs.put("version", identity);
        entityPrefs.putLong("modified", lastModified);
        // Properties
        Preferences propsPrefs = entityPrefs.node("properties");
        for (PropertyDescriptor persistentProperty : state.entityDescriptor().state().properties()) {
            if (persistentProperty.qualifiedName().name().equals("identity")) {
                // Skip Identity.identity()
                continue;
            }
            Object value = state.properties().get(persistentProperty.qualifiedName());
            if (value == null) {
                propsPrefs.remove(persistentProperty.qualifiedName().name());
            } else {
                ValueType valueType = persistentProperty.valueType();
                Class<?> mainType = valueType.mainType();
                if (Number.class.isAssignableFrom(mainType)) {
                    if (mainType.equals(Long.class)) {
                        propsPrefs.putLong(persistentProperty.qualifiedName().name(), (Long) value);
                    } else if (mainType.equals(Integer.class)) {
                        propsPrefs.putInt(persistentProperty.qualifiedName().name(), (Integer) value);
                    } else if (mainType.equals(Double.class)) {
                        propsPrefs.putDouble(persistentProperty.qualifiedName().name(), (Double) value);
                    } else if (mainType.equals(Float.class)) {
                        propsPrefs.putFloat(persistentProperty.qualifiedName().name(), (Float) value);
                    } else {
                        // Store as string even though it's a number
                        String jsonString = valueSerialization.serialize(value);
                        propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
                    }
                } else if (mainType.equals(Boolean.class)) {
                    propsPrefs.putBoolean(persistentProperty.qualifiedName().name(), (Boolean) value);
                } else if (valueType instanceof ValueCompositeType || valueType instanceof MapType || valueType instanceof CollectionType || valueType instanceof EnumType) {
                    String jsonString = valueSerialization.serialize(value);
                    propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
                } else {
                    String jsonString = valueSerialization.serialize(value);
                    propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
                }
            }
        }
        // Associations
        if (!state.associations().isEmpty()) {
            Preferences assocsPrefs = entityPrefs.node("associations");
            for (Map.Entry<QualifiedName, EntityReference> association : state.associations().entrySet()) {
                if (association.getValue() == null) {
                    assocsPrefs.remove(association.getKey().name());
                } else {
                    assocsPrefs.put(association.getKey().name(), association.getValue().identity());
                }
            }
        }
        // ManyAssociations
        if (!state.manyAssociations().isEmpty()) {
            Preferences manyAssocsPrefs = entityPrefs.node("manyassociations");
            for (Map.Entry<QualifiedName, List<EntityReference>> manyAssociation : state.manyAssociations().entrySet()) {
                StringBuilder manyAssocs = new StringBuilder();
                for (EntityReference entityReference : manyAssociation.getValue()) {
                    if (manyAssocs.length() > 0) {
                        manyAssocs.append("\n");
                    }
                    manyAssocs.append(entityReference.identity());
                }
                if (manyAssocs.length() > 0) {
                    manyAssocsPrefs.put(manyAssociation.getKey().name(), manyAssocs.toString());
                }
            }
        }
        // NamedAssociations
        if (!state.namedAssociations().isEmpty()) {
            Preferences namedAssocsPrefs = entityPrefs.node("namedassociations");
            for (Map.Entry<QualifiedName, Map<String, EntityReference>> namedAssociation : state.namedAssociations().entrySet()) {
                StringBuilder namedAssocs = new StringBuilder();
                for (Map.Entry<String, EntityReference> namedRef : namedAssociation.getValue().entrySet()) {
                    if (namedAssocs.length() > 0) {
                        namedAssocs.append("\n");
                    }
                    namedAssocs.append(namedRef.getKey()).append("\n").append(namedRef.getValue().identity());
                }
                if (namedAssocs.length() > 0) {
                    namedAssocsPrefs.put(namedAssociation.getKey().name(), namedAssocs.toString());
                }
            }
        }
    } catch (ValueSerializationException e) {
        throw new EntityStoreException("Could not store EntityState", e);
    }
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) ValueType(org.qi4j.api.type.ValueType) QualifiedName(org.qi4j.api.common.QualifiedName) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) MapType(org.qi4j.api.type.MapType) EnumType(org.qi4j.api.type.EnumType) CollectionType(org.qi4j.api.type.CollectionType) EntityReference(org.qi4j.api.entity.EntityReference) List(java.util.List) ArrayList(java.util.ArrayList) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) Preferences(java.util.prefs.Preferences) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ValueCompositeType(org.qi4j.api.type.ValueCompositeType)

Example 24 with QualifiedName

use of org.qi4j.api.common.QualifiedName in project qi4j-sdk by Qi4j.

the class Triples method addTriple.

public Triple addTriple(final PropertyFunction<?> propertyFunction, boolean optional) {
    String subject = "?entity";
    if (propertyFunction.traversedAssociation() != null) {
        subject = addTripleAssociation(propertyFunction.traversedAssociation(), false).value;
    } else if (propertyFunction.traversedProperty() != null) {
        subject = addTriple(propertyFunction.traversedProperty(), false).value;
    }
    QualifiedName qualifiedName = QualifiedName.fromAccessor(propertyFunction.accessor());
    String prefix = addNamespace(qualifiedName.toNamespace());
    return addTriple(subject, prefix + ":" + qualifiedName.name(), optional);
}
Also used : QualifiedName(org.qi4j.api.common.QualifiedName)

Example 25 with QualifiedName

use of org.qi4j.api.common.QualifiedName in project qi4j-sdk by Qi4j.

the class AbstractSQLIndexing method syncQNamesInsertPSs.

private void syncQNamesInsertPSs(Connection connection, Map<QualifiedName, PreparedStatement> qNameInsertPSs, Set<QualifiedName> qNames) throws SQLException {
    Set<QualifiedName> copy = new HashSet<QualifiedName>(qNames);
    copy.removeAll(qNameInsertPSs.keySet());
    for (QualifiedName qName : copy) {
        QNameInfo info = this._state.qNameInfos().get().get(qName);
        if (info == null) {
            throw new InternalError("Could not find database information about qualified name [" + qName + "]");
        }
        QNameType type = info.getQNameType();
        if (type.equals(QNameType.PROPERTY)) {
            qNameInsertPSs.put(qName, this.createInsertPropertyPS(connection, info));
        } else if (type.equals(QNameType.ASSOCIATION)) {
            qNameInsertPSs.put(qName, this.createInsertAssociationPS(connection, info));
        } else if (type.equals(QNameType.MANY_ASSOCIATION)) {
            qNameInsertPSs.put(qName, this.createInsertManyAssociationPS(connection, info));
        } else {
            throw new IllegalArgumentException("Did not know what to do with QName of type " + type + ".");
        }
    }
}
Also used : QNameType(org.qi4j.index.sql.support.common.QNameInfo.QNameType) QualifiedName(org.qi4j.api.common.QualifiedName) QNameInfo(org.qi4j.index.sql.support.common.QNameInfo) HashSet(java.util.HashSet)

Aggregations

QualifiedName (org.qi4j.api.common.QualifiedName)27 HashMap (java.util.HashMap)11 Map (java.util.Map)10 PropertyDescriptor (org.qi4j.api.property.PropertyDescriptor)10 EntityReference (org.qi4j.api.entity.EntityReference)9 ArrayList (java.util.ArrayList)8 List (java.util.List)7 AssociationDescriptor (org.qi4j.api.association.AssociationDescriptor)7 LinkedHashMap (java.util.LinkedHashMap)6 EntityDescriptor (org.qi4j.api.entity.EntityDescriptor)6 QNameInfo (org.qi4j.index.sql.support.common.QNameInfo)6 EntityStoreException (org.qi4j.spi.entitystore.EntityStoreException)6 Type (java.lang.reflect.Type)5 Member (java.lang.reflect.Member)4 JSONArray (org.json.JSONArray)4 JSONException (org.json.JSONException)4 JSONObject (org.json.JSONObject)4 AccessibleObject (java.lang.reflect.AccessibleObject)3 TypeVariable (java.lang.reflect.TypeVariable)3 HashSet (java.util.HashSet)3