Search in sources :

Example 21 with EntityDescriptor

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

the class LevelDBEntityStoreMixin method applyChanges.

@Override
public void applyChanges(MapChanges changes) throws IOException {
    final WriteBatch writeBatch = db.createWriteBatch();
    try {
        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();
                        writeBatch.put(ref.identity().getBytes(charset), jsonState.getBytes(charset));
                    }
                };
            }

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

                    @Override
                    public void close() throws IOException {
                        super.close();
                        String jsonState = toString();
                        writeBatch.put(ref.identity().getBytes(charset), jsonState.getBytes(charset));
                    }
                };
            }

            @Override
            public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor) throws EntityNotFoundException {
                writeBatch.delete(ref.identity().getBytes(charset));
            }
        });
        db.write(writeBatch);
    } finally {
        writeBatch.close();
    }
}
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) WriteBatch(org.iq80.leveldb.WriteBatch) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 22 with EntityDescriptor

use of org.qi4j.api.entity.EntityDescriptor 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 23 with EntityDescriptor

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

the class AbstractRiakMapEntityStore method applyChanges.

@Override
public void applyChanges(MapChanges changes) throws IOException {
    try {
        final Bucket bucket = riakClient.fetchBucket(bucketKey).execute();
        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 {
                        try {
                            super.close();
                            bucket.store(ref.identity(), toString()).execute();
                        } catch (RiakException ex) {
                            throw new EntityStoreException("Unable to apply entity change: newEntity", ex);
                        }
                    }
                };
            }

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

                    @Override
                    public void close() throws IOException {
                        try {
                            super.close();
                            IRiakObject entity = bucket.fetch(ref.identity()).execute();
                            if (entity == null) {
                                throw new EntityNotFoundException(ref);
                            }
                            bucket.store(ref.identity(), toString()).execute();
                        } catch (RiakException ex) {
                            throw new EntityStoreException("Unable to apply entity change: updateEntity", ex);
                        }
                    }
                };
            }

            @Override
            public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor) throws EntityNotFoundException {
                try {
                    IRiakObject entity = bucket.fetch(ref.identity()).execute();
                    if (entity == null) {
                        throw new EntityNotFoundException(ref);
                    }
                    bucket.delete(ref.identity()).execute();
                } catch (RiakException ex) {
                    throw new EntityStoreException("Unable to apply entity change: removeEntity", ex);
                }
            }
        });
    } catch (RiakRetryFailedException ex) {
        throw new EntityStoreException("Unable to apply entity changes.", ex);
    }
}
Also used : IRiakObject(com.basho.riak.client.IRiakObject) IOException(java.io.IOException) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) StringWriter(java.io.StringWriter) Bucket(com.basho.riak.client.bucket.Bucket) EntityReference(org.qi4j.api.entity.EntityReference) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) RiakRetryFailedException(com.basho.riak.client.RiakRetryFailedException) StringWriter(java.io.StringWriter) Writer(java.io.Writer) RiakException(com.basho.riak.client.RiakException)

Example 24 with EntityDescriptor

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

the class EntityResource method post.

@Override
public Representation post(Representation entityRepresentation, Variant variant) throws ResourceException {
    Usecase usecase = UsecaseBuilder.newUsecase("Update entity");
    EntityStoreUnitOfWork unitOfWork = entityStore.newUnitOfWork(usecase, module, System.currentTimeMillis());
    EntityState entity = getEntityState(unitOfWork);
    Form form = new Form(entityRepresentation);
    try {
        final EntityDescriptor descriptor = entity.entityDescriptor();
        // Parse JSON into properties
        for (PropertyDescriptor persistentProperty : descriptor.state().properties()) {
            if (!persistentProperty.isImmutable()) {
                String formValue = form.getFirstValue(persistentProperty.qualifiedName().name(), null);
                if (formValue == null) {
                    entity.setPropertyValue(persistentProperty.qualifiedName(), null);
                } else {
                    entity.setPropertyValue(persistentProperty.qualifiedName(), valueSerialization.deserialize(persistentProperty.valueType(), formValue));
                }
            }
        }
        for (AssociationDescriptor associationType : descriptor.state().associations()) {
            String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
            if (newStringAssociation == null || newStringAssociation.isEmpty()) {
                entity.setAssociationValue(associationType.qualifiedName(), null);
            } else {
                entity.setAssociationValue(associationType.qualifiedName(), EntityReference.parseEntityReference(newStringAssociation));
            }
        }
        for (AssociationDescriptor associationType : descriptor.state().manyAssociations()) {
            String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
            ManyAssociationState manyAssociation = entity.manyAssociationValueOf(associationType.qualifiedName());
            if (newStringAssociation == null) {
                // Remove "left-overs"
                for (EntityReference entityReference : manyAssociation) {
                    manyAssociation.remove(entityReference);
                }
                continue;
            }
            BufferedReader bufferedReader = new BufferedReader(new StringReader(newStringAssociation));
            String identity;
            try {
                // Synchronize old and new association
                int index = 0;
                while ((identity = bufferedReader.readLine()) != null) {
                    EntityReference reference = new EntityReference(identity);
                    if (manyAssociation.count() < index && manyAssociation.get(index).equals(reference)) {
                        continue;
                    }
                    try {
                        unitOfWork.entityStateOf(reference);
                        manyAssociation.remove(reference);
                        manyAssociation.add(index++, reference);
                    } catch (EntityNotFoundException e) {
                    // Ignore this entity - doesn't exist
                    }
                }
                // Remove "left-overs"
                while (manyAssociation.count() > index) {
                    manyAssociation.remove(manyAssociation.get(index));
                }
            } catch (IOException e) {
            // Ignore
            }
        }
        for (AssociationDescriptor associationType : descriptor.state().namedAssociations()) {
            String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
            NamedAssociationState namedAssociation = entity.namedAssociationValueOf(associationType.qualifiedName());
            if (newStringAssociation == null) {
                // Remove "left-overs"
                for (String name : namedAssociation) {
                    namedAssociation.remove(name);
                }
                continue;
            }
            Set<String> names = new HashSet<>();
            BufferedReader bufferedReader = new BufferedReader(new StringReader(newStringAssociation));
            String line;
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    String name = line;
                    line = bufferedReader.readLine();
                    if (line == null) {
                        break;
                    }
                    String identity = line;
                    EntityReference reference = new EntityReference(identity);
                    try {
                        unitOfWork.entityStateOf(reference);
                        namedAssociation.remove(name);
                        namedAssociation.put(name, reference);
                        names.add(name);
                    } catch (EntityNotFoundException e) {
                    // Ignore this entity - doesn't exist
                    }
                }
                // Remove "left-overs"
                for (String assocName : Iterables.toList(namedAssociation)) {
                    if (!names.contains(assocName)) {
                        namedAssociation.remove(assocName);
                    }
                }
            } catch (IOException e) {
            // Ignore
            }
        }
    } catch (ValueSerializationException | IllegalArgumentException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
    }
    try {
        unitOfWork.applyChanges().commit();
    } catch (ConcurrentEntityStateModificationException e) {
        throw new ResourceException(Status.CLIENT_ERROR_CONFLICT);
    } catch (EntityNotFoundException e) {
        throw new ResourceException(Status.CLIENT_ERROR_GONE);
    }
    getResponse().setStatus(Status.SUCCESS_RESET_CONTENT);
    return new EmptyRepresentation();
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) EntityStoreUnitOfWork(org.qi4j.spi.entitystore.EntityStoreUnitOfWork) Form(org.restlet.data.Form) NamedAssociationState(org.qi4j.spi.entity.NamedAssociationState) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) EntityState(org.qi4j.spi.entity.EntityState) JSONEntityState(org.qi4j.spi.entitystore.helpers.JSONEntityState) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) IOException(java.io.IOException) ManyAssociationState(org.qi4j.spi.entity.ManyAssociationState) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) ConcurrentEntityStateModificationException(org.qi4j.spi.entitystore.ConcurrentEntityStateModificationException) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) EntityReference(org.qi4j.api.entity.EntityReference) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ResourceException(org.restlet.resource.ResourceException) Usecase(org.qi4j.api.usecase.Usecase) 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