Search in sources :

Example 51 with EntityReference

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

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

the class SQLEntityFinder method findEntities.

@Override
public Iterable<EntityReference> findEntities(Class<?> resultType, @Optional Specification<Composite> whereClause, @Optional OrderBy[] orderBySegments, @Optional final Integer firstResult, @Optional final Integer maxResults, Map<String, Object> variables) throws EntityFinderException {
    // TODO what is Qi4j's policy on negative firstResult and/or maxResults? JDBC has its own way of interpreting
    // these values - does it match with Qi4j's way?
    Iterable<EntityReference> result;
    if (maxResults == null || maxResults > 0) {
        final List<Object> values = new ArrayList<>();
        final List<Integer> valueSQLTypes = new ArrayList<>();
        final String query = this.parser.constructQuery(resultType, whereClause, orderBySegments, firstResult, maxResults, variables, values, valueSQLTypes, false);
        result = this.performQuery(new DoQuery<Iterable<EntityReference>>() {

            @Override
            public Iterable<EntityReference> doIt(Connection connection) throws SQLException {
                PreparedStatement ps = null;
                ResultSet rs = null;
                List<EntityReference> resultList = new ArrayList<>(maxResults == null ? 100 : maxResults);
                try {
                    // TODO possibility to further optimize by setting fetch size (not too small not too little).
                    Integer rsType = parser.getResultSetType(firstResult, maxResults);
                    ps = createPS(connection, query, values, valueSQLTypes, rsType, ResultSet.CLOSE_CURSORS_AT_COMMIT);
                    rs = ps.executeQuery();
                    if (firstResult != null && !parser.isFirstResultSettingSupported() && rsType != ResultSet.TYPE_FORWARD_ONLY) {
                        rs.absolute(firstResult);
                    }
                    Integer i = 0;
                    while (rs.next() && (maxResults == null || i < maxResults)) {
                        resultList.add(new EntityReference(rs.getString(1)));
                        ++i;
                    }
                } finally {
                    SQLUtil.closeQuietly(rs);
                    SQLUtil.closeQuietly(ps);
                }
                return resultList;
            }
        });
    } else {
        result = new ArrayList<>(0);
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) EntityReference(org.qi4j.api.entity.EntityReference) ResultSet(java.sql.ResultSet)

Example 53 with EntityReference

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

the class ValueToEntityMixin method doUnqualifiedConversion.

private <T> EntityBuilder<?> doUnqualifiedConversion(Class<T> entityType, String identity, final AssociationStateHolder vState, final AssociationStateDescriptor vStateDesc) {
    Function<PropertyDescriptor, Object> props = new Function<PropertyDescriptor, Object>() {

        @Override
        public Object map(PropertyDescriptor ePropDesc) {
            String propName = ePropDesc.qualifiedName().name();
            try {
                PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(propName);
                return vState.propertyFor(vPropDesc.accessor()).get();
            } catch (IllegalArgumentException propNotFoundOnValue) {
                // Property not found on Value
                return null;
            }
        }
    };
    Function<AssociationDescriptor, EntityReference> assocs = new Function<AssociationDescriptor, EntityReference>() {

        @Override
        public EntityReference map(AssociationDescriptor eAssocDesc) {
            String assocName = eAssocDesc.qualifiedName().name();
            try {
                AssociationDescriptor vAssocDesc = vStateDesc.getAssociationByName(assocName);
                Object assocEntity = vState.associationFor(vAssocDesc.accessor()).get();
                return assocEntity == null ? null : EntityReference.entityReferenceFor(assocEntity);
            } catch (IllegalArgumentException assocNotFoundOnValue) {
                // Association not found on Value, find Property<String> and convert to Association
                try {
                    PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(assocName);
                    if (STRING_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                        String assocId = (String) vState.propertyFor(vPropDesc.accessor()).get();
                        return assocId == null ? null : EntityReference.parseEntityReference(assocId);
                    }
                    return null;
                } catch (IllegalArgumentException propNotFoundOnValue) {
                    return null;
                }
            }
        }
    };
    Function<AssociationDescriptor, Iterable<EntityReference>> manyAssocs = new Function<AssociationDescriptor, Iterable<EntityReference>>() {

        @Override
        public Iterable<EntityReference> map(AssociationDescriptor eAssocDesc) {
            String assocName = eAssocDesc.qualifiedName().name();
            try {
                AssociationDescriptor vAssocDesc = vStateDesc.getManyAssociationByName(assocName);
                ManyAssociation<Object> vManyAssoc = vState.manyAssociationFor(vAssocDesc.accessor());
                return MANY_ASSOC_TO_ENTITY_REF_ITERABLE.map(vManyAssoc);
            } catch (IllegalArgumentException assocNotFoundOnValue) {
                // ManyAssociation not found on Value, find List<String> and convert to ManyAssociation
                try {
                    PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(assocName);
                    if (STRING_COLLECTION_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                        Collection<String> vAssocState = (Collection) vState.propertyFor(vPropDesc.accessor()).get();
                        return STRING_COLLEC_TO_ENTITY_REF_ITERABLE.map(vAssocState);
                    }
                    return Iterables.empty();
                } catch (IllegalArgumentException propNotFoundOnValue) {
                    return Iterables.empty();
                }
            }
        }
    };
    Function<AssociationDescriptor, Map<String, EntityReference>> namedAssocs = new Function<AssociationDescriptor, Map<String, EntityReference>>() {

        @Override
        public Map<String, EntityReference> map(AssociationDescriptor eAssocDesc) {
            String assocName = eAssocDesc.qualifiedName().name();
            try {
                AssociationDescriptor vAssocDesc = vStateDesc.getNamedAssociationByName(assocName);
                NamedAssociation<Object> vAssocState = vState.namedAssociationFor(vAssocDesc.accessor());
                return NAMED_ASSOC_TO_ENTITY_REF_MAP.map(vAssocState);
            } catch (IllegalArgumentException assocNotFoundOnValue) {
                // Find Map<String,String> Property and convert to NamedAssociation
                try {
                    PropertyDescriptor vPropDesc = vStateDesc.findPropertyModelByName(assocName);
                    if (STRING_MAP_TYPE_SPEC.satisfiedBy(vPropDesc.valueType())) {
                        Map<String, String> vAssocState = (Map) vState.propertyFor(vPropDesc.accessor()).get();
                        return STRING_MAP_TO_ENTITY_REF_MAP.map(vAssocState);
                    }
                    return Collections.EMPTY_MAP;
                } catch (IllegalArgumentException propNotFoundOnValue) {
                    return Collections.EMPTY_MAP;
                }
            }
        }
    };
    return module.currentUnitOfWork().newEntityBuilderWithState(entityType, identity, props, assocs, manyAssocs, namedAssocs);
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) Function(org.qi4j.functional.Function) EntityReference(org.qi4j.api.entity.EntityReference) Collection(java.util.Collection) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 54 with EntityReference

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

the class EntityStateSerializer method serialize.

public void serialize(final EntityState entityState, final boolean includeNonQueryable, final Graph graph) {
    ValueFactory values = graph.getValueFactory();
    EntityReference identity = entityState.identity();
    URI entityUri = createEntityURI(values, identity);
    graph.add(entityUri, Rdfs.TYPE, values.createURI(Classes.toURI(first(entityState.entityDescriptor().types()))));
    serializeProperties(entityState, graph, entityUri, entityState.entityDescriptor(), includeNonQueryable);
    serializeAssociations(entityState, graph, entityUri, entityState.entityDescriptor().state().associations(), includeNonQueryable);
    serializeManyAssociations(entityState, graph, entityUri, entityState.entityDescriptor().state().manyAssociations(), includeNonQueryable);
}
Also used : EntityReference(org.qi4j.api.entity.EntityReference) ValueFactory(org.openrdf.model.ValueFactory) URI(org.openrdf.model.URI)

Example 55 with EntityReference

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

the class EntityStateSerializer method serializeAssociations.

private void serializeAssociations(final EntityState entityState, final Graph graph, URI entityUri, final Iterable<? extends AssociationDescriptor> associations, final boolean includeNonQueryable) {
    ValueFactory values = graph.getValueFactory();
    // Associations
    for (AssociationDescriptor associationType : associations) {
        if (!(includeNonQueryable || associationType.queryable())) {
            // Skip non-queryable
            continue;
        }
        EntityReference associatedId = entityState.associationValueOf(associationType.qualifiedName());
        if (associatedId != null) {
            URI assocURI = values.createURI(associationType.qualifiedName().toURI());
            URI assocEntityURI = values.createURI(associatedId.toURI());
            graph.add(entityUri, assocURI, assocEntityURI);
        }
    }
}
Also used : EntityReference(org.qi4j.api.entity.EntityReference) ValueFactory(org.openrdf.model.ValueFactory) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) URI(org.openrdf.model.URI)

Aggregations

EntityReference (org.qi4j.api.entity.EntityReference)60 Test (org.junit.Test)23 ArrayList (java.util.ArrayList)13 AssociationDescriptor (org.qi4j.api.association.AssociationDescriptor)12 EntityDescriptor (org.qi4j.api.entity.EntityDescriptor)11 PropertyDescriptor (org.qi4j.api.property.PropertyDescriptor)11 Person (org.qi4j.test.indexing.model.Person)11 HashMap (java.util.HashMap)9 Map (java.util.Map)9 QualifiedName (org.qi4j.api.common.QualifiedName)9 EntityNotFoundException (org.qi4j.spi.entitystore.EntityNotFoundException)9 EntityStoreException (org.qi4j.spi.entitystore.EntityStoreException)9 Writer (java.io.Writer)8 IOException (java.io.IOException)7 LinkedHashMap (java.util.LinkedHashMap)7 List (java.util.List)7 JSONException (org.json.JSONException)6 JSONObject (org.json.JSONObject)6 StringWriter (java.io.StringWriter)5 JSONArray (org.json.JSONArray)5