Search in sources :

Example 1 with RelationshipType

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

the class BoltDatabaseService method getOrCreateRelationshipType.

public RelationshipType getOrCreateRelationshipType(final String name) {
    RelationshipType relType = relTypeCache.get(name);
    if (relType == null) {
        relType = new RelationshipTypeImpl(name);
        relTypeCache.put(name, relType);
    }
    return relType;
}
Also used : RelationshipType(org.structr.api.graph.RelationshipType)

Example 2 with RelationshipType

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

the class WebsocketController method getMessageForEvent.

// ----- private methods -----
private WebSocketMessage getMessageForEvent(final SecurityContext securityContext, final ModificationEvent modificationEvent) throws FrameworkException {
    final String callbackId = modificationEvent.getCallbackId();
    if (modificationEvent.isNode()) {
        final NodeInterface node = (NodeInterface) modificationEvent.getGraphObject();
        if (modificationEvent.isDeleted()) {
            final WebSocketMessage message = createMessage("DELETE", callbackId);
            message.setId(modificationEvent.getRemovedProperties().get(GraphObject.id));
            message.setCode(200);
            return message;
        }
        if (modificationEvent.isCreated()) {
            final WebSocketMessage message = createMessage("CREATE", callbackId);
            message.setGraphObject(node);
            message.setResult(Arrays.asList(new GraphObject[] { node }));
            message.setCode(201);
            return message;
        }
        if (modificationEvent.isModified()) {
            final WebSocketMessage message = createMessage("UPDATE", callbackId);
            // at login the securityContext is still null
            if (securityContext != null) {
                // only include changed properties (+ id and type)
                LinkedHashSet<String> propertySet = new LinkedHashSet();
                propertySet.add("id");
                propertySet.add("type");
                for (Iterator<PropertyKey> it = modificationEvent.getModifiedProperties().keySet().iterator(); it.hasNext(); ) {
                    final String jsonName = ((PropertyKey) it.next()).jsonName();
                    if (!propertySet.contains(jsonName)) {
                        propertySet.add(jsonName);
                    }
                }
                for (Iterator<PropertyKey> it = modificationEvent.getRemovedProperties().keySet().iterator(); it.hasNext(); ) {
                    final String jsonName = ((PropertyKey) it.next()).jsonName();
                    if (!propertySet.contains(jsonName)) {
                        propertySet.add(jsonName);
                    }
                }
                if (propertySet.size() > 2) {
                    securityContext.setCustomView(propertySet);
                }
            }
            message.setGraphObject(node);
            message.setResult(Arrays.asList(new GraphObject[] { node }));
            message.setId(node.getUuid());
            message.getModifiedProperties().addAll(modificationEvent.getModifiedProperties().keySet());
            message.getRemovedProperties().addAll(modificationEvent.getRemovedProperties().keySet());
            message.setNodeData(modificationEvent.getData(securityContext));
            message.setCode(200);
            if (securityContext != null) {
                // Clear custom view here. This is necessary because the security context is reused for all websocket frames.
                securityContext.clearCustomView();
            }
            return message;
        }
    } else {
        // handle relationship
        final RelationshipInterface relationship = (RelationshipInterface) modificationEvent.getGraphObject();
        final RelationshipType relType = modificationEvent.getRelationshipType();
        // special treatment of CONTAINS relationships
        if ("CONTAINS".equals(relType.name())) {
            if (modificationEvent.isDeleted()) {
                final WebSocketMessage message = createMessage("REMOVE_CHILD", callbackId);
                message.setNodeData("parentId", relationship.getSourceNodeId());
                message.setId(relationship.getTargetNodeId());
                message.setCode(200);
                return message;
            }
            if (modificationEvent.isCreated()) {
                final WebSocketMessage message = new WebSocketMessage();
                final NodeInterface startNode = relationship.getSourceNode();
                final NodeInterface endNode = relationship.getTargetNode();
                // don't send a notification
                if (startNode == null || endNode == null) {
                    return null;
                }
                message.setResult(Arrays.asList(new GraphObject[] { endNode }));
                message.setId(endNode.getUuid());
                message.setNodeData("parentId", startNode.getUuid());
                message.setCode(200);
                message.setCommand("APPEND_CHILD");
                if (endNode instanceof DOMNode) {
                    org.w3c.dom.Node refNode = ((DOMNode) endNode).getNextSibling();
                    if (refNode != null) {
                        message.setCommand("INSERT_BEFORE");
                        message.setNodeData("refId", ((AbstractNode) refNode).getUuid());
                    }
                } else if (endNode instanceof User) {
                    message.setCommand("APPEND_USER");
                    message.setNodeData("refId", startNode.getUuid());
                } else if (endNode instanceof AbstractFile) {
                    message.setCommand("APPEND_FILE");
                    message.setNodeData("refId", startNode.getUuid());
                }
                return message;
            }
        }
        if (modificationEvent.isDeleted()) {
            final WebSocketMessage message = createMessage("DELETE", callbackId);
            message.setId(modificationEvent.getRemovedProperties().get(GraphObject.id));
            message.setCode(200);
            return message;
        }
        if (modificationEvent.isModified()) {
            final WebSocketMessage message = createMessage("UPDATE", callbackId);
            message.getModifiedProperties().addAll(modificationEvent.getModifiedProperties().keySet());
            message.getRemovedProperties().addAll(modificationEvent.getRemovedProperties().keySet());
            message.setNodeData(modificationEvent.getData(securityContext));
            message.setGraphObject(relationship);
            message.setId(relationship.getUuid());
            message.setCode(200);
            final PropertyMap relProperties = relationship.getProperties();
            // final NodeInterface startNode = relationship.getSourceNode();
            // final NodeInterface endNode = relationship.getTargetNode();
            // relProperties.put(new StringProperty("startNodeId"), startNode.getUuid());
            // relProperties.put(new StringProperty("endNodeId"), endNode.getUuid());
            final Map<String, Object> properties = PropertyMap.javaTypeToInputType(securityContext, relationship.getClass(), relProperties);
            message.setRelData(properties);
            return message;
        }
    }
    return null;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) User(org.structr.web.entity.User) AbstractFile(org.structr.web.entity.AbstractFile) RelationshipType(org.structr.api.graph.RelationshipType) GraphObject(org.structr.core.GraphObject) PropertyMap(org.structr.core.property.PropertyMap) RelationshipInterface(org.structr.core.graph.RelationshipInterface) GraphObject(org.structr.core.GraphObject) WebSocketMessage(org.structr.websocket.message.WebSocketMessage) DOMNode(org.structr.web.entity.dom.DOMNode) NodeInterface(org.structr.core.graph.NodeInterface) PropertyKey(org.structr.core.property.PropertyKey)

Example 3 with RelationshipType

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

the class SyncCommand method importDatabase.

private static void importDatabase(final DatabaseService graphDb, final SecurityContext securityContext, final ZipInputStream zis, boolean doValidation, final Long batchSize) throws FrameworkException, IOException {
    final App app = StructrApp.getInstance();
    final DataInputStream dis = new DataInputStream(new BufferedInputStream(zis));
    final long internalBatchSize = batchSize != null ? batchSize : 200;
    final String uuidPropertyName = GraphObject.id.dbName();
    final Map<String, Node> uuidMap = new LinkedHashMap<>();
    final Set<Long> deletedNodes = new HashSet<>();
    double t0 = System.nanoTime();
    PropertyContainer currentObject = null;
    String currentKey = null;
    boolean finished = false;
    long totalNodeCount = 0;
    long totalRelCount = 0;
    do {
        try (final Tx tx = app.tx(doValidation)) {
            final List<Relationship> rels = new LinkedList<>();
            final List<Node> nodes = new LinkedList<>();
            long nodeCount = 0;
            long relCount = 0;
            do {
                try {
                    // store current position
                    dis.mark(4);
                    // read one byte
                    byte objectType = dis.readByte();
                    // skip newlines
                    if (objectType == '\n') {
                        continue;
                    }
                    if (objectType == 'N') {
                        // break loop after 200 objects, commit and restart afterwards
                        if (nodeCount + relCount >= internalBatchSize) {
                            dis.reset();
                            break;
                        }
                        currentObject = graphDb.createNode(Collections.EMPTY_SET, Collections.EMPTY_MAP);
                        nodeCount++;
                        // store for later use
                        nodes.add((Node) currentObject);
                    } else if (objectType == 'R') {
                        // break look after 200 objects, commit and restart afterwards
                        if (nodeCount + relCount >= internalBatchSize) {
                            dis.reset();
                            break;
                        }
                        String startId = (String) deserialize(dis);
                        String endId = (String) deserialize(dis);
                        String relTypeName = (String) deserialize(dis);
                        Node endNode = uuidMap.get(endId);
                        Node startNode = uuidMap.get(startId);
                        if (startNode != null && endNode != null) {
                            if (deletedNodes.contains(startNode.getId()) || deletedNodes.contains(endNode.getId())) {
                                System.out.println("NOT creating relationship between deleted nodes..");
                                currentObject = null;
                                currentKey = null;
                            } else {
                                RelationshipType relType = RelationshipType.forName(relTypeName);
                                currentObject = startNode.createRelationshipTo(endNode, relType);
                                // store for later use
                                rels.add((Relationship) currentObject);
                                relCount++;
                            }
                        } else {
                            System.out.println("NOT creating relationship of type " + relTypeName + ", start: " + startId + ", end: " + endId);
                            currentObject = null;
                            currentKey = null;
                        }
                    } else {
                        // reset if not at the beginning of a line
                        dis.reset();
                        if (currentKey == null) {
                            try {
                                currentKey = (String) deserialize(dis);
                            } catch (Throwable t) {
                                logger.warn("", t);
                            }
                        } else {
                            final Object obj = deserialize(dis);
                            if (obj != null && currentObject != null) {
                                if (uuidPropertyName.equals(currentKey) && currentObject instanceof Node) {
                                    final String uuid = (String) obj;
                                    uuidMap.put(uuid, (Node) currentObject);
                                }
                                if (currentKey.length() != 0) {
                                    // store object in DB
                                    currentObject.setProperty(currentKey, obj);
                                    // set type label
                                    if (currentObject instanceof Node && NodeInterface.type.dbName().equals(currentKey)) {
                                        ((Node) currentObject).addLabel(graphDb.forName(Label.class, (String) obj));
                                    }
                                } else {
                                    logger.error("Invalid property key for value {}, ignoring", obj);
                                }
                            } else {
                                logger.warn("No current object to store property in.");
                            }
                            currentKey = null;
                        }
                    }
                } catch (EOFException eofex) {
                    finished = true;
                }
            } while (!finished);
            totalNodeCount += nodeCount;
            totalRelCount += relCount;
            logger.info("Imported {} nodes and {} rels, committing transaction..", new Object[] { totalNodeCount, totalRelCount });
            tx.success();
        }
    } while (!finished);
    // build schema
    try (final Tx tx = app.tx()) {
        SchemaHelper.reloadSchema(new ErrorBuffer(), securityContext.getSessionId());
        tx.success();
    } catch (FrameworkException fex) {
        logger.warn("", fex);
    }
    final Map<String, Object> params = new HashMap<>();
    params.put("removeUnused", false);
    // set correct labels after schema has been compiled
    app.command(BulkCreateLabelsCommand.class).execute(params);
    double t1 = System.nanoTime();
    double time = ((t1 - t0) / 1000000000.0);
    DecimalFormat decimalFormat = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
    logger.info("Import done in {} s", decimalFormat.format(time));
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) PropertyContainer(org.structr.api.graph.PropertyContainer) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Node(org.structr.api.graph.Node) AbstractNode(org.structr.core.entity.AbstractNode) AbstractSchemaNode(org.structr.core.entity.AbstractSchemaNode) DecimalFormat(java.text.DecimalFormat) RelationshipType(org.structr.api.graph.RelationshipType) LinkedHashMap(java.util.LinkedHashMap) BufferedInputStream(java.io.BufferedInputStream) EOFException(java.io.EOFException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) FrameworkException(org.structr.common.error.FrameworkException) DataInputStream(java.io.DataInputStream) LinkedList(java.util.LinkedList) ErrorBuffer(org.structr.common.error.ErrorBuffer) AbstractRelationship(org.structr.core.entity.AbstractRelationship) Relationship(org.structr.api.graph.Relationship) GraphObject(org.structr.core.GraphObject)

Example 4 with RelationshipType

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

the class IsInGroupFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    try {
        if (!arrayHasLengthAndAllElementsNotNull(sources, 2)) {
            return "";
        }
        if (!(sources[0] instanceof Group)) {
            logger.warn("Error: first argument is not a Group. Parameters: {}", getParametersAsString(sources));
            return "Error: first argument is not a Group.";
        }
        if (!(sources[1] instanceof Principal)) {
            logger.warn("Error: second argument is not a Principal. Parameters: {}", getParametersAsString(sources));
            return "Error: second argument is not a Principal.";
        }
        final RelationshipType type = StructrApp.getInstance().getDatabaseService().forName(RelationshipType.class, "CONTAINS");
        final Group group = (Group) sources[0];
        final Principal user = (Principal) sources[1];
        return group.hasRelationshipTo(type, user);
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Also used : Group(org.structr.core.entity.Group) RelationshipType(org.structr.api.graph.RelationshipType) Principal(org.structr.core.entity.Principal)

Example 5 with RelationshipType

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

the class BasicTest method test05CheckRelationshipEntities.

/**
 * Create a node for each configured entity class and check the type
 */
@Test
public void test05CheckRelationshipEntities() {
    try (final Tx tx = app.tx()) {
        List<Class> entityList = null;
        try {
            entityList = getClasses("org.structr.core.entity");
        } catch (IOException | ClassNotFoundException ex) {
            logger.error("Unable to get list of entity classes", ex);
        }
        assertTrue(entityList.contains(AbstractRelationship.class));
        assertTrue(entityList.contains(GenericRelationship.class));
        for (Class entityClass : entityList) {
            // Class entityClass = entity.getValue();
            if (AbstractRelationship.class.isAssignableFrom(entityClass)) {
                String type = entityClass.getSimpleName();
                logger.info("Creating relationship of type {}", type);
                List<GenericNode> nodes = createTestNodes(GenericNode.class, 2);
                final NodeInterface startNode = nodes.get(0);
                final NodeInterface endNode = nodes.get(1);
                final RelationshipType relType = RelType.IS_AT;
                NodeHasLocation rel = app.create(startNode, endNode, NodeHasLocation.class);
                assertTrue(rel != null);
                assertTrue(rel.getType().equals(relType.name()));
            }
        }
        tx.success();
    } catch (Throwable ex) {
        logger.warn("", ex);
        logger.error(ex.toString());
        fail("Unexpected exception");
    }
}
Also used : Tx(org.structr.core.graph.Tx) AbstractRelationship(org.structr.core.entity.AbstractRelationship) GenericNode(org.structr.core.entity.GenericNode) RelationshipType(org.structr.api.graph.RelationshipType) IOException(java.io.IOException) GenericRelationship(org.structr.core.entity.GenericRelationship) NodeHasLocation(org.structr.core.entity.relationship.NodeHasLocation) NodeInterface(org.structr.core.graph.NodeInterface) Test(org.junit.Test)

Aggregations

RelationshipType (org.structr.api.graph.RelationshipType)7 LinkedHashSet (java.util.LinkedHashSet)2 Direction (org.structr.api.graph.Direction)2 GraphObject (org.structr.core.GraphObject)2 IterableAdapter (org.structr.core.IterableAdapter)2 AbstractRelationship (org.structr.core.entity.AbstractRelationship)2 NodeInterface (org.structr.core.graph.NodeInterface)2 RelationshipFactory (org.structr.core.graph.RelationshipFactory)2 BufferedInputStream (java.io.BufferedInputStream)1 DataInputStream (java.io.DataInputStream)1 EOFException (java.io.EOFException)1 IOException (java.io.IOException)1 DecimalFormat (java.text.DecimalFormat)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedList (java.util.LinkedList)1 Test (org.junit.Test)1 Node (org.structr.api.graph.Node)1 PropertyContainer (org.structr.api.graph.PropertyContainer)1