Search in sources :

Example 1 with GraphModel

use of org.neo4j.ogm.model.GraphModel in project neo4j-ogm by neo4j.

the class GraphEntityMapper method map.

/**
 * @param type                 the type of the entities to return
 * @param graphModelResponse   The response of graph models to work on
 * @param additionalNodeFilter An optional filter to exclude entities based on some nodes from the result
 * @param <T>                  The type of the class of the entities to return
 * @return The list of entities represented by the list of graph models.
 */
<T> List<T> map(Class<T> type, Response<GraphModel> graphModelResponse, BiFunction<GraphModel, Long, Boolean> additionalNodeFilter) {
    // Those are the ids of all mapped nodes.
    Set<Long> mappedNodeIds = new LinkedHashSet<>();
    Set<Long> returnedNodeIds = new LinkedHashSet<>();
    Set<Long> mappedRelationshipIds = new LinkedHashSet<>();
    Set<Long> returnedRelationshipIds = new LinkedHashSet<>();
    // Execute mapping for each individual model
    Consumer<GraphModel> mapContentOfIndividualModel = graphModel -> mapContentOf(graphModel, additionalNodeFilter, returnedNodeIds, mappedRelationshipIds, returnedRelationshipIds, mappedNodeIds);
    GraphModel graphModel = null;
    while ((graphModel = graphModelResponse.next()) != null) {
        mapContentOfIndividualModel.accept(graphModel);
    }
    graphModelResponse.close();
    // Execute postload after all models and only for new ids
    executePostLoad(mappedNodeIds, mappedRelationshipIds);
    // Collect result
    Predicate<Object> entityPresentAndCompatible = entity -> entity != null && type.isAssignableFrom(entity.getClass());
    List<T> results = returnedNodeIds.stream().map(mappingContext::getNodeEntity).filter(entityPresentAndCompatible).map(type::cast).collect(toList());
    // only look for REs if no node entities were found
    if (results.isEmpty()) {
        results = returnedRelationshipIds.stream().map(mappingContext::getRelationshipEntity).filter(entityPresentAndCompatible).map(type::cast).collect(toList());
    }
    return results;
}
Also used : EntityAccessManager(org.neo4j.ogm.metadata.reflect.EntityAccessManager) EndNode(org.neo4j.ogm.annotation.EndNode) EntityInstantiator(org.neo4j.ogm.session.EntityInstantiator) java.util(java.util) CompositeAttributeConverter(org.neo4j.ogm.typeconversion.CompositeAttributeConverter) BiFunction(java.util.function.BiFunction) MethodInfo(org.neo4j.ogm.metadata.MethodInfo) LoggerFactory(org.slf4j.LoggerFactory) Property(org.neo4j.ogm.model.Property) Response(org.neo4j.ogm.response.Response) Direction(org.neo4j.ogm.annotation.Relationship.Direction) GraphModel(org.neo4j.ogm.model.GraphModel) Edge(org.neo4j.ogm.model.Edge) PropertyModel(org.neo4j.ogm.response.model.PropertyModel) Node(org.neo4j.ogm.model.Node) EntityUtils(org.neo4j.ogm.utils.EntityUtils) EntityFactory(org.neo4j.ogm.metadata.reflect.EntityFactory) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) MetaData(org.neo4j.ogm.metadata.MetaData) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Consumer(java.util.function.Consumer) StartNode(org.neo4j.ogm.annotation.StartNode) DescriptorMappings(org.neo4j.ogm.metadata.DescriptorMappings) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) MappingException(org.neo4j.ogm.exception.core.MappingException) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) GraphModel(org.neo4j.ogm.model.GraphModel)

Example 2 with GraphModel

use of org.neo4j.ogm.model.GraphModel in project neo4j-ogm by neo4j.

the class LoadOneDelegate method load.

public <T, ID extends Serializable> T load(Class<T> type, ID id, int depth) {
    ClassInfo classInfo = session.metaData().classInfo(type.getName());
    if (classInfo == null) {
        throw new IllegalArgumentException(type + " is not a managed entity.");
    }
    final FieldInfo primaryIndexField = classInfo.primaryIndexField();
    if (primaryIndexField != null && !primaryIndexField.isTypeOf(id.getClass())) {
        throw new IllegalArgumentException("Supplied id does not match primary index type on supplied class " + type.getName());
    }
    if (primaryIndexField == null && !(id instanceof Long)) {
        throw new IllegalArgumentException("Supplied id must be of type Long (native graph id) when supplied class " + "does not have primary id " + type.getName());
    }
    Optional<String> labelsOrType = session.determineLabelsOrTypeForLoading(type);
    if (!labelsOrType.isPresent()) {
        logger.warn("Unable to find database label for entity " + type.getName() + " : no results will be returned. Make sure the class is registered, " + "and not abstract without @NodeEntity annotation");
        return null;
    }
    QueryStatements<ID> queryStatements = session.queryStatementsFor(type, depth);
    PagingAndSortingQuery qry = queryStatements.findOneByType(labelsOrType.get(), convertIfNeeded(classInfo, id), depth);
    GraphModelRequest request = new DefaultGraphModelRequest(qry.getStatement(), qry.getParameters());
    return session.doInTransaction(() -> {
        try (Response<GraphModel> response = session.requestHandler().execute(request)) {
            new GraphRowModelMapper(session.metaData(), session.context(), session.getEntityInstantiator()).map(type, response);
            return lookup(type, id);
        }
    }, Transaction.Type.READ_ONLY);
}
Also used : DefaultGraphModelRequest(org.neo4j.ogm.cypher.query.DefaultGraphModelRequest) GraphRowModelMapper(org.neo4j.ogm.context.GraphRowModelMapper) GraphModelRequest(org.neo4j.ogm.request.GraphModelRequest) DefaultGraphModelRequest(org.neo4j.ogm.cypher.query.DefaultGraphModelRequest) GraphModel(org.neo4j.ogm.model.GraphModel) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) PagingAndSortingQuery(org.neo4j.ogm.cypher.query.PagingAndSortingQuery) ClassInfo(org.neo4j.ogm.metadata.ClassInfo)

Example 3 with GraphModel

use of org.neo4j.ogm.model.GraphModel in project neo4j-ogm by neo4j.

the class JsonGraphRowResponseTest method shouldParseDataInFilterGraphResponseCorrectly.

@Test
public void shouldParseDataInFilterGraphResponseCorrectly() throws IOException {
    when(entity.getContent()).thenReturn(filterQueryGraphRowResponse());
    try (Response<GraphRowListModel> rsp = new GraphRowsModelResponse(response)) {
        GraphRowListModel graphRowListModel = rsp.next();
        assertThat(graphRowListModel).isNotNull();
        List<GraphRowModel> graphRowModels = graphRowListModel.model();
        assertThat(graphRowModels).hasSize(8);
        GraphRowModel model = graphRowModels.get(0);
        GraphModel graph = model.getGraph();
        assertThat(graph.getNodes().iterator().next().getId()).isEqualTo(Long.valueOf(26));
        assertThat(graph.getRelationships()).isEmpty();
        Object[] rows = model.getRow();
        assertThat(rows.length).isEqualTo(2);
        Map row1 = (Map) ((List) rows[0]).get(0);
        assertThat(row1.get("name")).isEqualTo("GraphAware");
        assertThat(rows[1]).isEqualTo(26L);
    }
}
Also used : GraphRowModel(org.neo4j.ogm.model.GraphRowModel) GraphModel(org.neo4j.ogm.model.GraphModel) GraphRowListModel(org.neo4j.ogm.model.GraphRowListModel) Map(java.util.Map) Test(org.junit.Test)

Example 4 with GraphModel

use of org.neo4j.ogm.model.GraphModel in project neo4j-ogm by neo4j.

the class GraphEntityMapper method mapContentOf.

private void mapContentOf(GraphModel graphModel, BiFunction<GraphModel, Long, Boolean> additionalNodeFilter, Set<Long> returnedNodeIds, Set<Long> mappedRelationshipIds, Set<Long> returnedRelationshipIds, Set<Long> mappedNodeIds) {
    Predicate<Long> includeInResult = id -> additionalNodeFilter.apply(graphModel, id);
    try {
        Set<Long> newNodeIds = mapNodes(graphModel);
        returnedNodeIds.addAll(newNodeIds.stream().filter(includeInResult).collect(toList()));
        mappedNodeIds.addAll(newNodeIds);
        newNodeIds = mapRelationships(graphModel);
        returnedRelationshipIds.addAll(newNodeIds.stream().filter(includeInResult).collect(toList()));
        mappedRelationshipIds.addAll(newNodeIds);
    } catch (MappingException e) {
        throw e;
    } catch (Exception e) {
        throw new MappingException("Error mapping GraphModel", e);
    }
}
Also used : EntityAccessManager(org.neo4j.ogm.metadata.reflect.EntityAccessManager) EndNode(org.neo4j.ogm.annotation.EndNode) EntityInstantiator(org.neo4j.ogm.session.EntityInstantiator) java.util(java.util) CompositeAttributeConverter(org.neo4j.ogm.typeconversion.CompositeAttributeConverter) BiFunction(java.util.function.BiFunction) MethodInfo(org.neo4j.ogm.metadata.MethodInfo) LoggerFactory(org.slf4j.LoggerFactory) Property(org.neo4j.ogm.model.Property) Response(org.neo4j.ogm.response.Response) Direction(org.neo4j.ogm.annotation.Relationship.Direction) GraphModel(org.neo4j.ogm.model.GraphModel) Edge(org.neo4j.ogm.model.Edge) PropertyModel(org.neo4j.ogm.response.model.PropertyModel) Node(org.neo4j.ogm.model.Node) EntityUtils(org.neo4j.ogm.utils.EntityUtils) EntityFactory(org.neo4j.ogm.metadata.reflect.EntityFactory) Logger(org.slf4j.Logger) Predicate(java.util.function.Predicate) MetaData(org.neo4j.ogm.metadata.MetaData) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Consumer(java.util.function.Consumer) StartNode(org.neo4j.ogm.annotation.StartNode) DescriptorMappings(org.neo4j.ogm.metadata.DescriptorMappings) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) MappingException(org.neo4j.ogm.exception.core.MappingException) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) InvocationTargetException(java.lang.reflect.InvocationTargetException) MappingException(org.neo4j.ogm.exception.core.MappingException) MappingException(org.neo4j.ogm.exception.core.MappingException)

Example 5 with GraphModel

use of org.neo4j.ogm.model.GraphModel in project neo4j-ogm by neo4j.

the class GraphRowListModelMapper method map.

public <T> Iterable<T> map(Class<T> type, Response<GraphRowListModel> response) {
    Set<Long> idsOfResultEntities = new LinkedHashSet<>();
    Response<GraphModel> graphResponse = new Response<GraphModel>() {

        GraphRowListModel currentIteratedModel;

        int currentIndex = 0;

        @Override
        public GraphModel next() {
            if (currentIteratedModel == null) {
                currentIteratedModel = response.next();
                if (currentIteratedModel == null) {
                    return null;
                }
                currentIndex = 0;
            }
            List<GraphRowModel> listOfRowModels = currentIteratedModel.model();
            if (listOfRowModels.size() <= currentIndex) {
                currentIteratedModel = null;
                return next();
            }
            GraphRowModel graphRowModel = listOfRowModels.get(currentIndex++);
            Set<Long> idsInCurrentRow = Arrays.stream(graphRowModel.getRow()).filter(Number.class::isInstance).map(Number.class::cast).map(Number::longValue).collect(toSet());
            idsOfResultEntities.addAll(idsInCurrentRow);
            return graphRowModel.getGraph();
        }

        @Override
        public void close() {
            response.close();
        }

        @Override
        public String[] columns() {
            return response.columns();
        }
    };
    // although it looks like that the `idsOfResultEntities` will stay empty, they won't, trust us.
    BiFunction<GraphModel, Long, Boolean> includeModelObject = (graphModel, nativeId) -> idsOfResultEntities.contains(nativeId);
    return delegate.map(type, graphResponse, includeModelObject);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) EntityInstantiator(org.neo4j.ogm.session.EntityInstantiator) Arrays(java.util.Arrays) List(java.util.List) GraphRowModel(org.neo4j.ogm.model.GraphRowModel) MetaData(org.neo4j.ogm.metadata.MetaData) BiFunction(java.util.function.BiFunction) Set(java.util.Set) Response(org.neo4j.ogm.response.Response) GraphModel(org.neo4j.ogm.model.GraphModel) GraphRowListModel(org.neo4j.ogm.model.GraphRowListModel) Collectors(java.util.stream.Collectors) LinkedHashSet(java.util.LinkedHashSet) GraphRowModel(org.neo4j.ogm.model.GraphRowModel) Response(org.neo4j.ogm.response.Response) GraphModel(org.neo4j.ogm.model.GraphModel) GraphRowListModel(org.neo4j.ogm.model.GraphRowListModel)

Aggregations

GraphModel (org.neo4j.ogm.model.GraphModel)9 ClassInfo (org.neo4j.ogm.metadata.ClassInfo)4 Response (org.neo4j.ogm.response.Response)4 BiFunction (java.util.function.BiFunction)3 Collectors (java.util.stream.Collectors)3 GraphRowModelMapper (org.neo4j.ogm.context.GraphRowModelMapper)3 DefaultGraphModelRequest (org.neo4j.ogm.cypher.query.DefaultGraphModelRequest)3 PagingAndSortingQuery (org.neo4j.ogm.cypher.query.PagingAndSortingQuery)3 FieldInfo (org.neo4j.ogm.metadata.FieldInfo)3 MetaData (org.neo4j.ogm.metadata.MetaData)3 GraphRowListModel (org.neo4j.ogm.model.GraphRowListModel)3 Node (org.neo4j.ogm.model.Node)3 GraphModelRequest (org.neo4j.ogm.request.GraphModelRequest)3 EntityInstantiator (org.neo4j.ogm.session.EntityInstantiator)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 java.util (java.util)2 LinkedHashSet (java.util.LinkedHashSet)2 Consumer (java.util.function.Consumer)2 Predicate (java.util.function.Predicate)2 Test (org.junit.Test)2