Search in sources :

Example 36 with Module

use of org.qi4j.api.structure.Module 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 37 with Module

use of org.qi4j.api.structure.Module 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 38 with Module

use of org.qi4j.api.structure.Module in project qi4j-sdk by Qi4j.

the class Qi95IssueTest method canCreateAndQueryWithAllInMemory.

@Test
public void canCreateAndQueryWithAllInMemory() throws Exception {
    Application application = createApplication(inMemoryRdf, inMemoryStore, domain);
    try {
        application.activate();
        Module domain = application.findModule("Domain", "Domain");
        UnitOfWorkFactory unitOfWorkFactory = domain;
        createABunchOfStuffAndDoQueries(unitOfWorkFactory, domain);
    } finally {
        application.passivate();
    }
}
Also used : UnitOfWorkFactory(org.qi4j.api.unitofwork.UnitOfWorkFactory) Module(org.qi4j.api.structure.Module) Application(org.qi4j.api.structure.Application) Test(org.junit.Test)

Example 39 with Module

use of org.qi4j.api.structure.Module in project qi4j-sdk by Qi4j.

the class Qi95IssueTest method canCreateAndQueryWithNativeRdfAndJdbm.

@Test
public void canCreateAndQueryWithNativeRdfAndJdbm() throws Exception {
    Application application = createApplication(nativeRdf, jdbmStore, domain);
    try {
        application.activate();
        Module domain = application.findModule("Domain", "Domain");
        UnitOfWorkFactory unitOfWorkFactory = domain;
        createABunchOfStuffAndDoQueries(unitOfWorkFactory, domain);
    } finally {
        application.passivate();
    }
}
Also used : UnitOfWorkFactory(org.qi4j.api.unitofwork.UnitOfWorkFactory) Module(org.qi4j.api.structure.Module) Application(org.qi4j.api.structure.Application) Test(org.junit.Test)

Example 40 with Module

use of org.qi4j.api.structure.Module in project qi4j-sdk by Qi4j.

the class Main method main.

public static void main(String[] args) throws Exception {
    final Application application = new Energy4Java().newApplication(new AppAssembler());
    application.activate();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        @SuppressWarnings("CallToThreadDumpStack")
        public void run() {
            try {
                application.passivate();
            } catch (Exception ex) {
                System.err.println("Unable to passivate Qi4j application!");
                ex.printStackTrace();
            }
        }
    }));
    Module domainModule = application.findModule("app", "domain");
    int exitStatus = 0;
    try {
        UnitOfWork uow = domainModule.newUnitOfWork();
        EntityBuilder<PretextEntity> builder = uow.newEntityBuilder(PretextEntity.class);
        PretextEntity pretext = builder.instance();
        pretext.reason().set("Testing purpose");
        builder.newInstance();
        uow.complete();
        uow = domainModule.newUnitOfWork();
        QueryBuilder<PretextEntity> queryBuilder = domainModule.newQueryBuilder(PretextEntity.class);
        queryBuilder = queryBuilder.where(eq(templateFor(PretextEntity.class).reason(), "Testing purpose"));
        Query<PretextEntity> query = uow.newQuery(queryBuilder);
        pretext = query.find();
        if (pretext == null) {
            System.err.println("ERROR: Unable to find pretext!");
            exitStatus = -1;
        } else {
            System.out.println("SUCCESS: Found Pretext with reason: " + pretext.reason().get());
        }
        uow.discard();
    } finally {
        deleteData(application.findModule("infra", "persistence"));
    }
    System.exit(exitStatus);
}
Also used : UnitOfWork(org.qi4j.api.unitofwork.UnitOfWork) SQLException(java.sql.SQLException) Energy4Java(org.qi4j.bootstrap.Energy4Java) Module(org.qi4j.api.structure.Module) Application(org.qi4j.api.structure.Application)

Aggregations

Module (org.qi4j.api.structure.Module)41 Test (org.junit.Test)28 ModuleAssembly (org.qi4j.bootstrap.ModuleAssembly)18 Application (org.qi4j.api.structure.Application)17 AssemblyException (org.qi4j.bootstrap.AssemblyException)16 SingletonAssembler (org.qi4j.bootstrap.SingletonAssembler)15 ArrayList (java.util.ArrayList)6 Energy4Java (org.qi4j.bootstrap.Energy4Java)6 UnitOfWork (org.qi4j.api.unitofwork.UnitOfWork)5 UnitOfWorkFactory (org.qi4j.api.unitofwork.UnitOfWorkFactory)5 AmbiguousTypeException (org.qi4j.api.composite.AmbiguousTypeException)4 EntityDescriptor (org.qi4j.api.entity.EntityDescriptor)4 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)4 Assembler (org.qi4j.bootstrap.Assembler)4 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