Search in sources :

Example 6 with EntityTypeNotFoundException

use of org.qi4j.api.unitofwork.EntityTypeNotFoundException 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);
        }
        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<QualifiedName, Object>();
        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, new NumberParser<Long>() {

                        @Override
                        public Long parse(String str) {
                            return Long.parseLong(str);
                        }
                    }));
                } else if (mainType.equals(Integer.class)) {
                    properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, new NumberParser<Integer>() {

                        @Override
                        public Integer parse(String str) {
                            return Integer.parseInt(str);
                        }
                    }));
                } else if (mainType.equals(Double.class)) {
                    properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, new NumberParser<Double>() {

                        @Override
                        public Double parse(String str) {
                            return Double.parseDouble(str);
                        }
                    }));
                } else if (mainType.equals(Float.class)) {
                    properties.put(persistentPropertyDescriptor.qualifiedName(), this.getNumber(propsPrefs, persistentPropertyDescriptor, new NumberParser<Float>() {

                        @Override
                        public Float parse(String str) {
                            return Float.parseFloat(str);
                        }
                    }));
                } 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<QualifiedName, EntityReference>();
        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<QualifiedName, List<EntityReference>>();
        Preferences manyAssocs = null;
        for (AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations()) {
            if (manyAssocs == null) {
                manyAssocs = entityPrefs.node("manyassociations");
            }
            List<EntityReference> references = new ArrayList<EntityReference>();
            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);
            }
        }
        return new DefaultEntityState(desuw, entityPrefs.get("version", ""), entityPrefs.getLong("modified", unitOfWork.currentTime()), identity, status, entityDescriptor, properties, associations, manyAssociations);
    } catch (ValueSerializationException e) {
        throw new EntityStoreException(e);
    } catch (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) ArrayList(java.util.ArrayList) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) MapType(org.qi4j.api.type.MapType) 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) ValueCompositeType(org.qi4j.api.type.ValueCompositeType)

Example 7 with EntityTypeNotFoundException

use of org.qi4j.api.unitofwork.EntityTypeNotFoundException 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("version");
        long modified = jsonObject.getLong("modified");
        String identity = jsonObject.getString("identity");
        // Check if version is correct
        String currentAppVersion = jsonObject.optString(MapEntityStore.JSONKeys.application_version.name(), "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(MapEntityStore.JSONKeys.application_version.name(), application.version());
            }
            LOGGER.trace("Updated version nr on {} from {} to {}", new Object[] { identity, currentAppVersion, application.version() });
            // State changed
            status = EntityStatus.UPDATED;
        }
        String type = jsonObject.getString("type");
        EntityDescriptor entityDescriptor = module.entityDescriptor(type);
        if (entityDescriptor == null) {
            throw new EntityTypeNotFoundException(type);
        }
        Map<QualifiedName, Object> properties = new HashMap<QualifiedName, Object>();
        JSONObject props = jsonObject.getJSONObject("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<QualifiedName, EntityReference>();
        JSONObject assocs = jsonObject.getJSONObject("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("manyassociations");
        Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<QualifiedName, List<EntityReference>>();
        for (AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations()) {
            List<EntityReference> references = new ArrayList<EntityReference>();
            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);
            }
        }
        return new DefaultEntityState(unitOfWork, version, modified, EntityReference.parseEntityReference(identity), status, entityDescriptor, properties, associations, manyAssociations);
    } 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) ArrayList(java.util.ArrayList) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) 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)

Example 8 with EntityTypeNotFoundException

use of org.qi4j.api.unitofwork.EntityTypeNotFoundException in project qi4j-sdk by Qi4j.

the class ContextResource method select.

protected <T> T select(Class<T> entityClass, String id) throws ResourceException {
    try {
        T composite = module.currentUnitOfWork().get(entityClass, id);
        current().select(composite);
        return composite;
    } catch (EntityTypeNotFoundException e) {
        throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
    } catch (NoSuchEntityException e) {
        throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND);
    }
}
Also used : EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) ResourceException(org.restlet.resource.ResourceException) NoSuchEntityException(org.qi4j.api.unitofwork.NoSuchEntityException)

Example 9 with EntityTypeNotFoundException

use of org.qi4j.api.unitofwork.EntityTypeNotFoundException in project qi4j-sdk by Qi4j.

the class JSONMapEntityStoreMixin method readEntityState.

protected JSONEntityState 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("version");
        long modified = jsonObject.getLong("modified");
        String identity = jsonObject.getString("identity");
        // Check if version is correct
        String currentAppVersion = jsonObject.optString(MapEntityStore.JSONKeys.application_version.name(), "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(MapEntityStore.JSONKeys.application_version.name(), application.version());
            }
            LoggerFactory.getLogger(getClass()).debug("Updated version nr on " + identity + " from " + currentAppVersion + " to " + application.version());
            // State changed
            status = EntityStatus.UPDATED;
        }
        String type = jsonObject.getString("type");
        EntityDescriptor entityDescriptor = module.entityDescriptor(type);
        if (entityDescriptor == null) {
            throw new EntityTypeNotFoundException(type);
        }
        return new JSONEntityState(unitOfWork, valueSerialization, version, modified, EntityReference.parseEntityReference(identity), status, entityDescriptor, jsonObject);
    } catch (JSONException e) {
        throw new EntityStoreException(e);
    }
}
Also used : JSONTokener(org.json.JSONTokener) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) JSONObject(org.json.JSONObject) EntityStatus(org.qi4j.spi.entity.EntityStatus) JSONException(org.json.JSONException) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) Module(org.qi4j.api.structure.Module)

Example 10 with EntityTypeNotFoundException

use of org.qi4j.api.unitofwork.EntityTypeNotFoundException in project qi4j-sdk by Qi4j.

the class PrivateEntityUnitOfWorkTest method givenAppWithPrivateEntityWhenUnitOfWorkCanSeeItThenCanCommit.

@Test
public void givenAppWithPrivateEntityWhenUnitOfWorkCanSeeItThenCanCommit() throws Exception {
    System.setProperty("qi4j.compacttrace", "off");
    Energy4Java is = new Energy4Java();
    Application app = is.newApplication(new ApplicationAssembler() {

        public ApplicationAssembly assemble(ApplicationAssemblyFactory applicationFactory) throws AssemblyException {
            return applicationFactory.newApplicationAssembly(new Assembler[][][] { { { new Assembler() {

                public void assemble(ModuleAssembly module) throws AssemblyException {
                    module.objects(PrivateEntityUnitOfWorkTest.class);
                }
            } } }, { { new Assembler() {

                public void assemble(ModuleAssembly module) throws AssemblyException {
                    module.entities(ProductEntity.class);
                    module.entities(ProductCatalogEntity.class).visibleIn(application);
                    module.values(ProductInfo.class);
                    new EntityTestAssembler().assemble(module);
                }
            } } } });
        }
    });
    app.activate();
    Module module = app.findModule("Layer 1", "Module 1");
    module.injectTo(this);
    UnitOfWork unitOfWork = uowf.newUnitOfWork();
    try {
        unitOfWork.newEntity(ProductEntity.class);
        fail("Should not be able to create product here");
    } catch (EntityTypeNotFoundException e) {
        // Ok
        ProductCatalog catalog = unitOfWork.newEntity(ProductCatalog.class, "1");
        unitOfWork.complete();
    }
    unitOfWork = uowf.newUnitOfWork();
    String id;
    try {
        ProductCatalog catalog = unitOfWork.get(ProductCatalog.class, "1");
        id = ((Identity) catalog.newProduct()).identity().get();
        unitOfWork.complete();
    } finally {
        unitOfWork.discard();
    }
    unitOfWork = module.newUnitOfWork();
    try {
        ProductCatalog catalog = unitOfWork.get(ProductCatalog.class, "1");
        Product product = catalog.findProduct(id);
        product.price().set(100);
        unitOfWork.complete();
    } finally {
        unitOfWork.discard();
    }
}
Also used : ApplicationAssemblyFactory(org.qi4j.bootstrap.ApplicationAssemblyFactory) UnitOfWork(org.qi4j.api.unitofwork.UnitOfWork) EntityTypeNotFoundException(org.qi4j.api.unitofwork.EntityTypeNotFoundException) ApplicationAssembly(org.qi4j.bootstrap.ApplicationAssembly) AssemblyException(org.qi4j.bootstrap.AssemblyException) ModuleAssembly(org.qi4j.bootstrap.ModuleAssembly) ApplicationAssembler(org.qi4j.bootstrap.ApplicationAssembler) EntityTestAssembler(org.qi4j.test.EntityTestAssembler) Energy4Java(org.qi4j.bootstrap.Energy4Java) Assembler(org.qi4j.bootstrap.Assembler) ApplicationAssembler(org.qi4j.bootstrap.ApplicationAssembler) EntityTestAssembler(org.qi4j.test.EntityTestAssembler) Module(org.qi4j.api.structure.Module) Identity(org.qi4j.api.entity.Identity) Application(org.qi4j.api.structure.Application) Test(org.junit.Test)

Aggregations

EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)10 EntityDescriptor (org.qi4j.api.entity.EntityDescriptor)5 Module (org.qi4j.api.structure.Module)5 EntityStatus (org.qi4j.spi.entity.EntityStatus)4 EntityStoreException (org.qi4j.spi.entitystore.EntityStoreException)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 List (java.util.List)3 JSONException (org.json.JSONException)3 JSONObject (org.json.JSONObject)3 JSONTokener (org.json.JSONTokener)3 AssociationDescriptor (org.qi4j.api.association.AssociationDescriptor)3 QualifiedName (org.qi4j.api.common.QualifiedName)3 EntityReference (org.qi4j.api.entity.EntityReference)3 PropertyDescriptor (org.qi4j.api.property.PropertyDescriptor)3 NoSuchEntityException (org.qi4j.api.unitofwork.NoSuchEntityException)3 JSONArray (org.json.JSONArray)2 IdentityGenerator (org.qi4j.api.entity.IdentityGenerator)2 NoSuchServiceException (org.qi4j.api.service.NoSuchServiceException)2 EntityModel (org.qi4j.runtime.entity.EntityModel)2