Search in sources :

Example 16 with Node

use of org.structr.api.graph.Node in project structr by structr.

the class StaticRelationshipResource method doGet.

// ~--- methods --------------------------------------------------------
@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
    // ok, source node exists, fetch it
    final GraphObject sourceEntity = typedIdResource.getEntity();
    if (sourceEntity != null) {
        // first try: look through existing relations
        if (propertyKey == null) {
            if (sourceEntity instanceof NodeInterface) {
                if (!typeResource.isNode) {
                    final NodeInterface source = (NodeInterface) sourceEntity;
                    final Node sourceNode = source.getNode();
                    final Class relationshipType = typeResource.entityClass;
                    final Relation relation = AbstractNode.getRelationshipForType(relationshipType);
                    final Class destNodeType = relation.getOtherType(typedIdResource.getEntityClass());
                    final Set partialResult = new LinkedHashSet<>(typeResource.doGet(sortKey, sortDescending, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults());
                    // filter list according to end node type
                    final Set<GraphObject> set = Iterables.toSet(Iterables.filter(new OtherNodeTypeRelationFilter(securityContext, sourceNode, destNodeType), source.getRelationships(relationshipType)));
                    // intersect partial result with result list
                    set.retainAll(partialResult);
                    final List<GraphObject> finalResult = new LinkedList<>(set);
                    // sort after merge
                    applyDefaultSorting(finalResult, sortKey, sortDescending);
                    // return result
                    return new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
                } else {
                    // what here?
                    throw new NotFoundException("Cannot access relationship collection " + typeResource.getRawType());
                }
            }
        } else {
            Query query = typeResource.query;
            if (query == null) {
                query = StructrApp.getInstance(securityContext).nodeQuery();
            }
            // use search context from type resource
            typeResource.collectSearchAttributes(query);
            final Predicate<GraphObject> predicate = query.toPredicate();
            final Object value = sourceEntity.getProperty(propertyKey, predicate);
            if (value != null) {
                if (value instanceof Iterable) {
                    final Set<Object> propertyResults = new LinkedHashSet<>();
                    Iterator<Object> iter = ((Iterable<Object>) value).iterator();
                    boolean iterableContainsGraphObject = false;
                    while (iter.hasNext()) {
                        Object obj = iter.next();
                        propertyResults.add(obj);
                        if (obj != null && !iterableContainsGraphObject) {
                            if (obj instanceof GraphObject) {
                                iterableContainsGraphObject = true;
                            }
                        }
                    }
                    int rawResultCount = propertyResults.size();
                    if (rawResultCount > 0 && !iterableContainsGraphObject) {
                        GraphObjectMap gObject = new GraphObjectMap();
                        gObject.setProperty(new ArrayProperty(this.typeResource.rawType, Object.class), propertyResults.toArray());
                        Result r = new Result(gObject, true);
                        r.setRawResultCount(rawResultCount);
                        return r;
                    }
                    final List<GraphObject> finalResult = new LinkedList<>();
                    propertyResults.forEach(v -> finalResult.add((GraphObject) v));
                    applyDefaultSorting(finalResult, sortKey, sortDescending);
                    // return result
                    Result r = new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
                    r.setRawResultCount(rawResultCount);
                    return r;
                } else if (value instanceof GraphObject) {
                    return new Result((GraphObject) value, isPrimitiveArray());
                } else {
                    GraphObjectMap gObject = new GraphObjectMap();
                    PropertyKey key;
                    String keyName = this.typeResource.rawType;
                    int resultCount = 1;
                    // FIXME: Dynamically resolve all property types and their result count
                    if (value instanceof String) {
                        key = new StringProperty(keyName);
                    } else if (value instanceof Integer) {
                        key = new IntProperty(keyName);
                    } else if (value instanceof Long) {
                        key = new LongProperty(keyName);
                    } else if (value instanceof Double) {
                        key = new DoubleProperty(keyName);
                    } else if (value instanceof Boolean) {
                        key = new BooleanProperty(keyName);
                    } else if (value instanceof Date) {
                        key = new DateProperty(keyName);
                    } else if (value instanceof String[]) {
                        key = new ArrayProperty(keyName, String.class);
                        resultCount = ((String[]) value).length;
                    } else {
                        key = new GenericProperty(keyName);
                    }
                    gObject.setProperty(key, value);
                    Result r = new Result(gObject, true);
                    r.setRawResultCount(resultCount);
                    return r;
                }
            }
            // check propertyKey to return the right variant of empty result
            if (!(propertyKey instanceof StartNode || propertyKey instanceof EndNode)) {
                return new Result(Collections.EMPTY_LIST, 1, false, true);
            }
        }
    }
    return new Result(Collections.EMPTY_LIST, 0, false, true);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) Query(org.structr.core.app.Query) DateProperty(org.structr.core.property.DateProperty) StartNode(org.structr.core.property.StartNode) EndNode(org.structr.core.property.EndNode) Node(org.structr.api.graph.Node) AbstractNode(org.structr.core.entity.AbstractNode) NotFoundException(org.structr.rest.exception.NotFoundException) StringProperty(org.structr.core.property.StringProperty) GraphObject(org.structr.core.GraphObject) Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult) Relation(org.structr.core.entity.Relation) NodeInterface(org.structr.core.graph.NodeInterface) StartNode(org.structr.core.property.StartNode) ArrayProperty(org.structr.core.property.ArrayProperty) BooleanProperty(org.structr.core.property.BooleanProperty) OtherNodeTypeRelationFilter(org.structr.core.entity.OtherNodeTypeRelationFilter) LinkedList(java.util.LinkedList) Date(java.util.Date) IntProperty(org.structr.core.property.IntProperty) EndNode(org.structr.core.property.EndNode) GraphObjectMap(org.structr.core.GraphObjectMap) LongProperty(org.structr.core.property.LongProperty) GenericProperty(org.structr.core.property.GenericProperty) GraphObject(org.structr.core.GraphObject) DoubleProperty(org.structr.core.property.DoubleProperty) PropertyKey(org.structr.core.property.PropertyKey)

Example 17 with Node

use of org.structr.api.graph.Node in project structr by structr.

the class DeleteSpatialIndexCommand method execute.

@Override
public void execute(Map<String, Object> attributes) throws FrameworkException {
    final DatabaseService graphDb = StructrApp.getInstance().getService(NodeService.class).getGraphDb();
    final List<Node> toDelete = new LinkedList<>();
    for (final Node node : graphDb.getAllNodes()) {
        try {
            if (node.hasProperty("bbox") && node.hasProperty("gtype") && node.hasProperty("id") && node.hasProperty("latitude") && node.hasProperty("longitude")) {
                toDelete.add(node);
            }
        } catch (Throwable t) {
        }
    }
    final App app = StructrApp.getInstance(securityContext);
    try (final Tx tx = app.tx()) {
        for (Node node : toDelete) {
            logger.info("Deleting node {}", node);
            try {
                for (Relationship rel : node.getRelationships()) {
                    rel.delete();
                }
                node.delete();
            } catch (Throwable t) {
                logger.warn("", t);
            }
        }
        tx.success();
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Tx(org.structr.core.graph.Tx) NodeService(org.structr.core.graph.NodeService) Node(org.structr.api.graph.Node) Relationship(org.structr.api.graph.Relationship) DatabaseService(org.structr.api.DatabaseService) LinkedList(java.util.LinkedList)

Example 18 with Node

use of org.structr.api.graph.Node in project structr by structr.

the class NodeWrapperTest method testDeleteException.

@Test
public void testDeleteException() {
    try {
        Settings.DatabasePath.setValue(Files.createTempDirectory("structr-test").toFile().getAbsolutePath());
        Settings.ConnectionUrl.setValue(Settings.TestingConnectionUrl.getValue());
    } catch (IOException ioex) {
        logger.warn("", ioex);
    }
    final BoltDatabaseService s = new BoltDatabaseService();
    s.initialize();
    // create new node
    try (final Transaction tx = s.beginTx()) {
        final Node node1 = s.createNode(Collections.EMPTY_SET, Collections.EMPTY_MAP);
        final Node node2 = s.createNode(Collections.EMPTY_SET, Collections.EMPTY_MAP);
        final Relationship rel = node1.createRelationshipTo(node2, s.forName(RelationshipType.class, "TEST"));
        rel.delete();
        tx.success();
    } catch (Throwable t) {
        t.printStackTrace();
        fail("Unexpected exception.");
    }
    s.shutdown();
}
Also used : Transaction(org.structr.api.Transaction) Node(org.structr.api.graph.Node) Relationship(org.structr.api.graph.Relationship) RelationshipType(org.structr.api.graph.RelationshipType) IOException(java.io.IOException) Test(org.junit.Test)

Example 19 with Node

use of org.structr.api.graph.Node in project structr by structr.

the class Synchronize method onRequest.

@Override
public void onRequest(final CloudConnection serverConnection) throws IOException, FrameworkException {
    final DatabaseService graphDb = StructrApp.getInstance().getDatabaseService();
    final String uuidPropertyName = GraphObject.id.dbName();
    final Set<Long> visitedObjectIDs = new HashSet<>();
    for (final Node node : graphDb.getAllNodes()) {
        if (!visitedObjectIDs.contains(node.getId())) {
            final String hash = contentHashCode(node, visitedObjectIDs);
            final Object uuid = node.getProperty(uuidPropertyName, null);
            if (uuid != null && uuid instanceof String) {
                serverConnection.send(new Diff(uuid.toString(), hash));
            }
        }
    }
    // clear set of visited objects because node and relationship IDs are offsets and can overlap.
    visitedObjectIDs.clear();
    for (final Relationship relationship : graphDb.getAllRelationships()) {
        if (!visitedObjectIDs.contains(relationship.getId())) {
            final String hash = contentHashCode(relationship, visitedObjectIDs);
            final Object uuid = relationship.getProperty(uuidPropertyName, null);
            if (uuid != null && uuid instanceof String) {
                serverConnection.send(new Diff(uuid.toString(), hash));
            }
        }
    }
    serverConnection.send(new Finish());
}
Also used : Node(org.structr.api.graph.Node) Relationship(org.structr.api.graph.Relationship) GraphObject(org.structr.core.GraphObject) DatabaseService(org.structr.api.DatabaseService) Finish(org.structr.cloud.message.Finish) HashSet(java.util.HashSet)

Example 20 with Node

use of org.structr.api.graph.Node in project structr by structr.

the class UpdateTransmission method doRemote.

@Override
public Boolean doRemote(final CloudConnection client) throws IOException, FrameworkException {
    // send synchronization request first
    client.send(new Synchronize());
    // send all node and relationship data
    final DatabaseService graphDb = StructrApp.getInstance().getDatabaseService();
    final NodeFactory nodeFactory = new NodeFactory(SecurityContext.getSuperUserInstance());
    final RelationshipFactory relFactory = new RelationshipFactory(SecurityContext.getSuperUserInstance());
    for (final Node neo4jNode : graphDb.getAllNodes()) {
        final NodeInterface node = nodeFactory.instantiate(neo4jNode);
        if (node instanceof File) {
            PushTransmission.sendFile(client, (File) node, CloudService.CHUNK_SIZE);
        } else {
            client.send(new NodeDataContainer(node, 0));
        }
    }
    for (final Relationship relationship : graphDb.getAllRelationships()) {
        final RelationshipInterface relationshipInterface = relFactory.instantiate(relationship);
        client.send(new RelationshipDataContainer(relationshipInterface, 0));
    }
    // wait for end of transmission
    client.waitForTransmission();
    return true;
}
Also used : NodeFactory(org.structr.core.graph.NodeFactory) RelationshipDataContainer(org.structr.cloud.message.RelationshipDataContainer) RelationshipFactory(org.structr.core.graph.RelationshipFactory) Node(org.structr.api.graph.Node) Relationship(org.structr.api.graph.Relationship) RelationshipInterface(org.structr.core.graph.RelationshipInterface) NodeDataContainer(org.structr.cloud.message.NodeDataContainer) DatabaseService(org.structr.api.DatabaseService) File(org.structr.dynamic.File) NodeInterface(org.structr.core.graph.NodeInterface)

Aggregations

Node (org.structr.api.graph.Node)24 Relationship (org.structr.api.graph.Relationship)13 AbstractNode (org.structr.core.entity.AbstractNode)11 LinkedList (java.util.LinkedList)8 GraphObject (org.structr.core.GraphObject)8 DatabaseService (org.structr.api.DatabaseService)7 LinkedHashSet (java.util.LinkedHashSet)5 AbstractRelationship (org.structr.core.entity.AbstractRelationship)5 LinkedHashMap (java.util.LinkedHashMap)4 List (java.util.List)4 FrameworkException (org.structr.common.error.FrameworkException)4 AbstractSchemaNode (org.structr.core.entity.AbstractSchemaNode)4 PropertyKey (org.structr.core.property.PropertyKey)4 Test (org.junit.Test)3 Transaction (org.structr.api.Transaction)3 App (org.structr.core.app.App)3 StructrApp (org.structr.core.app.StructrApp)3 IOException (java.io.IOException)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2