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;
}
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;
}
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));
}
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());
}
}
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");
}
}
Aggregations