Search in sources :

Example 1 with EntityDescriptor

use of org.qi4j.api.entity.EntityDescriptor in project qi4j-sdk by Qi4j.

the class ApplicationAssemblerTest method testApplicationAssembler.

@Test
public void testApplicationAssembler() throws AssemblyException {
    Energy4Java is = new Energy4Java();
    ApplicationDescriptor model = is.newApplicationModel(new ApplicationAssembler() {

        @Override
        public ApplicationAssembly assemble(ApplicationAssemblyFactory applicationFactory) throws AssemblyException {
            ApplicationAssembly assembly = applicationFactory.newApplicationAssembly();
            LayerAssembly layer1 = assembly.layer("Layer1");
            ModuleAssembly module = layer1.module("Module1");
            module.services(TestService.class);
            module.entities(TestEntity.class);
            layer1.services(AssemblySpecifications.types(TestService.class)).instantiateOnStartup();
            layer1.services(Specifications.<Object>TRUE()).visibleIn(Visibility.layer);
            layer1.entities(Specifications.<Object>TRUE()).visibleIn(Visibility.application);
            return assembly;
        }
    });
    model.accept(new HierarchicalVisitorAdapter<Object, Object, RuntimeException>() {

        @Override
        public boolean visitEnter(Object visited) throws RuntimeException {
            if (visited instanceof ServiceDescriptor) {
                ServiceDescriptor serviceDescriptor = (ServiceDescriptor) visited;
                Assert.assertTrue(serviceDescriptor.isInstantiateOnStartup());
                Assert.assertTrue(serviceDescriptor.visibility() == Visibility.layer);
                return false;
            } else if (visited instanceof EntityDescriptor) {
                EntityDescriptor entityDescriptor = (EntityDescriptor) visited;
                Assert.assertTrue(entityDescriptor.visibility() == Visibility.application);
                return false;
            }
            return true;
        }
    });
    model.newInstance(is.spi());
}
Also used : ApplicationDescriptor(org.qi4j.api.structure.ApplicationDescriptor) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) ServiceDescriptor(org.qi4j.api.service.ServiceDescriptor) Test(org.junit.Test)

Example 2 with EntityDescriptor

use of org.qi4j.api.entity.EntityDescriptor in project qi4j-sdk by Qi4j.

the class MapEntityStoreMixin method readEntityState.

protected EntityState 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());
            }
            LoggerFactory.getLogger(MapEntityStoreMixin.class).debug("Updated version nr on " + identity + " from " + currentAppVersion + " to " + 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.getJSONObject(JSONKeys.NAMED_ASSOCIATIONS);
        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);
                        Object value = jsonValues.get(name);
                        EntityReference ref = value == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) value);
                        references.put(name, ref);
                    }
                }
                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) 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 3 with EntityDescriptor

use of org.qi4j.api.entity.EntityDescriptor in project qi4j-sdk by Qi4j.

the class JdbmEntityStoreMixin method applyChanges.

@WriteLock
@Override
public void applyChanges(MapChanges changes) throws IOException {
    try {
        changes.visitMap(new MapChanger() {

            @Override
            public Writer newEntity(final EntityReference ref, EntityDescriptor descriptor) throws IOException {
                return new StringWriter(1000) {

                    @Override
                    public void close() throws IOException {
                        super.close();
                        byte[] stateArray = toString().getBytes("UTF-8");
                        long stateIndex = recordManager.insert(stateArray, serializer);
                        String indexKey = ref.toString();
                        index.insert(indexKey.getBytes("UTF-8"), stateIndex, false);
                    }
                };
            }

            @Override
            public Writer updateEntity(final EntityReference ref, EntityDescriptor descriptor) throws IOException {
                return new StringWriter(1000) {

                    @Override
                    public void close() throws IOException {
                        super.close();
                        Long stateIndex = getStateIndex(ref.toString());
                        byte[] stateArray = toString().getBytes("UTF-8");
                        recordManager.update(stateIndex, stateArray, serializer);
                    }
                };
            }

            @Override
            public void removeEntity(EntityReference ref, EntityDescriptor descriptor) throws EntityNotFoundException {
                try {
                    Long stateIndex = getStateIndex(ref.toString());
                    recordManager.delete(stateIndex);
                    index.remove(ref.toString().getBytes("UTF-8"));
                } catch (IOException e) {
                    throw new EntityStoreException(e);
                }
            }
        });
        recordManager.commit();
    } catch (Exception e) {
        e.printStackTrace();
        recordManager.rollback();
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof EntityStoreException) {
            throw (EntityStoreException) e;
        } else {
            throw new IOException(e);
        }
    }
}
Also used : EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) StringWriter(java.io.StringWriter) EntityReference(org.qi4j.api.entity.EntityReference) IOException(java.io.IOException) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) StringWriter(java.io.StringWriter) Writer(java.io.Writer) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) IOException(java.io.IOException) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) WriteLock(org.qi4j.library.locking.WriteLock)

Example 4 with EntityDescriptor

use of org.qi4j.api.entity.EntityDescriptor in project qi4j-sdk by Qi4j.

the class MongoMapEntityStoreMixin method applyChanges.

@Override
public void applyChanges(MapChanges changes) throws IOException {
    db.requestStart();
    final DBCollection entities = db.getCollection(collectionName);
    changes.visitMap(new MapChanger() {

        @Override
        public Writer newEntity(final EntityReference ref, EntityDescriptor entityDescriptor) throws IOException {
            return new StringWriter(1000) {

                @Override
                public void close() throws IOException {
                    super.close();
                    String jsonState = toString();
                    DBObject bsonState = (DBObject) JSON.parse(jsonState);
                    BasicDBObject entity = new BasicDBObject();
                    entity.put(IDENTITY_COLUMN, ref.identity());
                    entity.put(STATE_COLUMN, bsonState);
                    entities.insert(entity, writeConcern);
                }
            };
        }

        @Override
        public Writer updateEntity(final EntityReference ref, EntityDescriptor entityDescriptor) throws IOException {
            return new StringWriter(1000) {

                @Override
                public void close() throws IOException {
                    super.close();
                    DBObject bsonState = (DBObject) JSON.parse(toString());
                    BasicDBObject entity = new BasicDBObject();
                    entity.put(IDENTITY_COLUMN, ref.identity());
                    entity.put(STATE_COLUMN, bsonState);
                    entities.update(byIdentity(ref), entity, false, false, writeConcern);
                }
            };
        }

        @Override
        public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor) throws EntityNotFoundException {
            DBObject entity = entities.findOne(byIdentity(ref));
            if (entity == null) {
                throw new EntityNotFoundException(ref);
            }
            entities.remove(entity, writeConcern);
        }
    });
    db.requestDone();
}
Also used : DBCollection(com.mongodb.DBCollection) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) BasicDBObject(com.mongodb.BasicDBObject) StringWriter(java.io.StringWriter) EntityReference(org.qi4j.api.entity.EntityReference) IOException(java.io.IOException) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 5 with EntityDescriptor

use of org.qi4j.api.entity.EntityDescriptor in project qi4j-sdk by Qi4j.

the class AbstractSQLStartup method constructApplicationInfo.

private ApplicationInfo constructApplicationInfo(Boolean setQNameTableNameToNull) throws SQLException {
    final ApplicationInfo appInfo = new ApplicationInfo();
    final List<CompositeDescriptorInfo> valueDescriptors = new ArrayList<>();
    final Deque<Object> currentPath = new ArrayDeque<>();
    _app.descriptor().accept(new HierarchicalVisitorAdapter<Object, Object, RuntimeException>() {

        @Override
        public boolean visitEnter(Object visited) throws RuntimeException {
            if (visited instanceof LayerDescriptor || visited instanceof ModuleDescriptor) {
                currentPath.push(visited);
            }
            if (visited instanceof EntityDescriptor || visited instanceof ValueDescriptor) {
                // TODO filter non-visible descriptors away.
                if (visited instanceof EntityDescriptor) {
                    EntityDescriptor entityDescriptor = (EntityDescriptor) visited;
                    if (entityDescriptor.queryable()) {
                        LOGGER.debug("THIS ONE WORKS: {}", entityDescriptor);
                        appInfo.entityDescriptors.put(first(entityDescriptor.types()).getName(), entityDescriptor);
                    }
                } else {
                    valueDescriptors.add(new CompositeDescriptorInfo((LayerDescriptor) Iterables.first(Iterables.skip(1, currentPath)), (ModuleDescriptor) Iterables.first(currentPath), (CompositeDescriptor) visited));
                }
                return false;
            }
            return true;
        }

        @Override
        public boolean visitLeave(Object visited) {
            if (visited instanceof LayerDescriptor || visited instanceof ModuleDescriptor) {
                currentPath.pop();
            }
            return true;
        }
    });
    for (EntityDescriptor descriptor : appInfo.entityDescriptors.values()) {
        Set<QualifiedName> newQNames = new HashSet<>();
        this.extractPropertyQNames(descriptor, this._state.qNameInfos().get(), newQNames, valueDescriptors, appInfo.enumValues, setQNameTableNameToNull);
        this.extractAssociationQNames(descriptor, this._state.qNameInfos().get(), newQNames, setQNameTableNameToNull);
        this.extractManyAssociationQNames(descriptor, this._state.qNameInfos().get(), newQNames, setQNameTableNameToNull);
        this._state.entityUsedQNames().get().put(descriptor, newQNames);
    }
    appInfo.usedValueComposites.addAll(valueDescriptors);
    return appInfo;
}
Also used : ValueDescriptor(org.qi4j.api.value.ValueDescriptor) QualifiedName(org.qi4j.api.common.QualifiedName) ArrayList(java.util.ArrayList) ArrayDeque(java.util.ArrayDeque) ModuleDescriptor(org.qi4j.api.structure.ModuleDescriptor) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) LayerDescriptor(org.qi4j.api.structure.LayerDescriptor) HashSet(java.util.HashSet)

Aggregations

EntityDescriptor (org.qi4j.api.entity.EntityDescriptor)24 EntityReference (org.qi4j.api.entity.EntityReference)11 PropertyDescriptor (org.qi4j.api.property.PropertyDescriptor)8 EntityStoreException (org.qi4j.spi.entitystore.EntityStoreException)8 IOException (java.io.IOException)6 Writer (java.io.Writer)6 AssociationDescriptor (org.qi4j.api.association.AssociationDescriptor)6 QualifiedName (org.qi4j.api.common.QualifiedName)6 EntityNotFoundException (org.qi4j.spi.entitystore.EntityNotFoundException)6 StringWriter (java.io.StringWriter)5 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 EntityTypeNotFoundException (org.qi4j.api.unitofwork.EntityTypeNotFoundException)5 HashSet (java.util.HashSet)4 LinkedHashMap (java.util.LinkedHashMap)4 List (java.util.List)4 JSONException (org.json.JSONException)4 JSONObject (org.json.JSONObject)4 ValueDescriptor (org.qi4j.api.value.ValueDescriptor)4