Search in sources :

Example 21 with EntityReference

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

the class AbstractEntityFinderTest method script15.

@Test
public void script15() throws EntityFinderException {
    Male person = templateFor(Male.class);
    // should return Ann and Joe Doe
    Iterable<EntityReference> entities = entityFinder.findEntities(Person.class, isNull(person.wife()), NO_SORTING, NO_FIRST_RESULT, NO_MAX_RESULTS, NO_VARIABLES);
    assertNames(entities, ANN, JOE);
}
Also used : EntityReference(org.qi4j.api.entity.EntityReference) Male(org.qi4j.test.indexing.model.Male) Test(org.junit.Test)

Example 22 with EntityReference

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

the class SQLEntityStoreMixin method writeEntityState.

protected void writeEntityState(DefaultEntityState state, Writer writer, String version) throws EntityStoreException {
    try {
        JSONWriter json = new JSONWriter(writer);
        JSONWriter properties = json.object().key(JSONKeys.IDENTITY).value(state.identity().identity()).key(JSONKeys.APPLICATION_VERSION).value(application.version()).key(JSONKeys.TYPE).value(first(state.entityDescriptor().types()).getName()).key(JSONKeys.VERSION).value(version).key(JSONKeys.MODIFIED).value(state.lastModified()).key(JSONKeys.PROPERTIES).object();
        for (PropertyDescriptor persistentProperty : state.entityDescriptor().state().properties()) {
            Object value = state.properties().get(persistentProperty.qualifiedName());
            json.key(persistentProperty.qualifiedName().name());
            if (value == null || ValueType.isPrimitiveValue(value)) {
                json.value(value);
            } else {
                String serialized = valueSerialization.serialize(value);
                if (serialized.startsWith("{")) {
                    json.value(new JSONObject(serialized));
                } else if (serialized.startsWith("[")) {
                    json.value(new JSONArray(serialized));
                } else {
                    json.value(serialized);
                }
            }
        }
        JSONWriter associations = properties.endObject().key(JSONKeys.ASSOCIATIONS).object();
        for (Map.Entry<QualifiedName, EntityReference> stateNameEntityReferenceEntry : state.associations().entrySet()) {
            EntityReference value = stateNameEntityReferenceEntry.getValue();
            associations.key(stateNameEntityReferenceEntry.getKey().name()).value(value != null ? value.identity() : null);
        }
        JSONWriter manyAssociations = associations.endObject().key(JSONKeys.MANY_ASSOCIATIONS).object();
        for (Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations().entrySet()) {
            JSONWriter assocs = manyAssociations.key(stateNameListEntry.getKey().name()).array();
            for (EntityReference entityReference : stateNameListEntry.getValue()) {
                assocs.value(entityReference.identity());
            }
            assocs.endArray();
        }
        JSONWriter namedAssociations = manyAssociations.endObject().key(JSONKeys.NAMED_ASSOCIATIONS).object();
        for (Map.Entry<QualifiedName, Map<String, EntityReference>> stateNameMapEntry : state.namedAssociations().entrySet()) {
            JSONWriter assocs = namedAssociations.key(stateNameMapEntry.getKey().name()).object();
            for (Map.Entry<String, EntityReference> entry : stateNameMapEntry.getValue().entrySet()) {
                assocs.key(entry.getKey()).value(entry.getValue().identity());
            }
            assocs.endObject();
        }
        namedAssociations.endObject().endObject();
    } catch (JSONException e) {
        throw new EntityStoreException("Could not store EntityState", e);
    }
}
Also used : JSONWriter(org.json.JSONWriter) PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) QualifiedName(org.qi4j.api.common.QualifiedName) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) EntityReference(org.qi4j.api.entity.EntityReference) JSONObject(org.json.JSONObject) List(java.util.List) ArrayList(java.util.ArrayList) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 23 with EntityReference

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

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

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

the class SolrEntityQueryMixin method findEntities.

@Override
public Iterable<EntityReference> findEntities(Class<?> resultType, @Optional Specification<Composite> whereClause, @Optional OrderBy[] orderBySegments, @Optional Integer firstResult, @Optional Integer maxResults, Map<String, Object> variables) throws EntityFinderException {
    try {
        QuerySpecification expr = (QuerySpecification) whereClause;
        SolrServer server = solr.solrServer();
        NamedList<Object> list = new NamedList<Object>();
        list.add("q", expr.query());
        list.add("rows", maxResults != 0 ? maxResults : 10000);
        list.add("start", firstResult);
        if (orderBySegments != null && orderBySegments.length > 0) {
            for (OrderBy orderBySegment : orderBySegments) {
                String propName = ((Member) orderBySegment.property().accessor()).getName() + "_for_sort";
                String order = orderBySegment.order() == OrderBy.Order.ASCENDING ? "asc" : "desc";
                list.add("sort", propName + " " + order);
            }
        }
        SolrParams solrParams = SolrParams.toSolrParams(list);
        logger.debug("Search:" + list.toString());
        QueryResponse query = server.query(solrParams);
        SolrDocumentList results = query.getResults();
        List<EntityReference> references = new ArrayList<EntityReference>(results.size());
        for (SolrDocument result : results) {
            references.add(EntityReference.parseEntityReference(result.getFirstValue("id").toString()));
        }
        return references;
    } catch (SolrServerException e) {
        throw new EntityFinderException(e);
    }
}
Also used : OrderBy(org.qi4j.api.query.grammar.OrderBy) NamedList(org.apache.solr.common.util.NamedList) SolrServerException(org.apache.solr.client.solrj.SolrServerException) ArrayList(java.util.ArrayList) SolrDocumentList(org.apache.solr.common.SolrDocumentList) SolrServer(org.apache.solr.client.solrj.SolrServer) QuerySpecification(org.qi4j.api.query.grammar.QuerySpecification) SolrDocument(org.apache.solr.common.SolrDocument) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse) EntityFinderException(org.qi4j.spi.query.EntityFinderException) EntityReference(org.qi4j.api.entity.EntityReference) SolrParams(org.apache.solr.common.params.SolrParams)

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