Search in sources :

Example 81 with PropertyKey

use of org.structr.core.property.PropertyKey in project structr by structr.

the class HtmlServlet method resolvePossiblePropertyNamesForObjectResolution.

private void resolvePossiblePropertyNamesForObjectResolution(final ConfigurationProvider config, final Query query, final String name) {
    for (final String possiblePropertyName : possiblePropertyNamesForEntityResolving) {
        final String[] parts = possiblePropertyName.split("\\.");
        String className = AbstractNode.class.getSimpleName();
        String keyName = AbstractNode.name.jsonName();
        switch(parts.length) {
            case 2:
                className = parts[0];
                keyName = parts[1];
                break;
            default:
                logger.warn("Unable to process key for object resolution {}.", possiblePropertyName);
                break;
        }
        if (StringUtils.isNoneBlank(className, keyName)) {
            final Class type = config.getNodeEntityClass(className);
            if (type != null) {
                final PropertyKey key = StructrApp.key(type, keyName);
                if (key != null) {
                    try {
                        final PropertyConverter converter = key.inputConverter(SecurityContext.getSuperUserInstance());
                        if (converter != null) {
                            // try converted value, fail silenty
                            query.or(key, converter.convert(name));
                        } else {
                            // try unconverted value, fail silently if it doesn't work
                            query.or(key, name);
                        }
                    } catch (FrameworkException ignore) {
                    }
                } else {
                    logger.warn("Unable to find property key {} of type {} defined in key {} used for object resolution.", new Object[] { keyName, className, possiblePropertyName });
                }
            } else {
                logger.warn("Unable to find type {} defined in key {} used for object resolution.", new Object[] { className, possiblePropertyName });
            }
        }
    }
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) PropertyConverter(org.structr.core.converter.PropertyConverter) PropertyKey(org.structr.core.property.PropertyKey)

Example 82 with PropertyKey

use of org.structr.core.property.PropertyKey in project structr by structr.

the class WebSocketDataGSONAdapter method serialize.

// ~--- methods --------------------------------------------------------
@Override
public JsonElement serialize(WebSocketMessage src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject root = new JsonObject();
    JsonObject jsonNodeData = new JsonObject();
    JsonObject jsonRelData = new JsonObject();
    JsonArray removedProperties = new JsonArray();
    JsonArray modifiedProperties = new JsonArray();
    if (src.getCommand() != null) {
        root.add("command", new JsonPrimitive(src.getCommand()));
    }
    if (src.getId() != null) {
        root.add("id", new JsonPrimitive(src.getId()));
    }
    if (src.getPageId() != null) {
        root.add("pageId", new JsonPrimitive(src.getPageId()));
    }
    if (src.getMessage() != null) {
        root.add("message", new JsonPrimitive(src.getMessage()));
    }
    if (src.getJsonErrorObject() != null) {
        root.add("error", src.getJsonErrorObject());
    }
    if (src.getCode() != 0) {
        root.add("code", new JsonPrimitive(src.getCode()));
    }
    if (src.getSessionId() != null) {
        root.add("sessionId", new JsonPrimitive(src.getSessionId()));
    }
    if (src.getCallback() != null) {
        root.add("callback", new JsonPrimitive(src.getCallback()));
    }
    if (src.getButton() != null) {
        root.add("button", new JsonPrimitive(src.getButton()));
    }
    if (src.getParent() != null) {
        root.add("parent", new JsonPrimitive(src.getParent()));
    }
    if (src.getView() != null) {
        root.add("view", new JsonPrimitive(src.getView()));
    }
    if (src.getSortKey() != null) {
        root.add("sort", new JsonPrimitive(src.getSortKey()));
    }
    if (src.getSortOrder() != null) {
        root.add("order", new JsonPrimitive(src.getSortOrder()));
    }
    if (src.getPageSize() > 0) {
        root.add("pageSize", new JsonPrimitive(src.getPageSize()));
    }
    if (src.getPage() > 0) {
        root.add("page", new JsonPrimitive(src.getPage()));
    }
    JsonArray nodesWithChildren = new JsonArray();
    Set<String> nwc = src.getNodesWithChildren();
    if ((nwc != null) && !src.getNodesWithChildren().isEmpty()) {
        for (String nodeId : nwc) {
            nodesWithChildren.add(new JsonPrimitive(nodeId));
        }
        root.add("nodesWithChildren", nodesWithChildren);
    }
    // serialize session valid flag (output only)
    root.add("sessionValid", new JsonPrimitive(src.isSessionValid()));
    // UPDATE only, serialize only removed and modified properties and use the correct values
    if ((src.getGraphObject() != null)) {
        if (!src.getModifiedProperties().isEmpty()) {
            for (PropertyKey modifiedKey : src.getModifiedProperties()) {
                modifiedProperties.add(toJsonPrimitive(modifiedKey));
            }
            root.add("modifiedProperties", modifiedProperties);
        }
        if (!src.getRemovedProperties().isEmpty()) {
            for (PropertyKey removedKey : src.getRemovedProperties()) {
                removedProperties.add(toJsonPrimitive(removedKey));
            }
            root.add("removedProperties", removedProperties);
        }
    }
    // serialize node data
    if (src.getNodeData() != null) {
        for (Entry<String, Object> entry : src.getNodeData().entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value != null) {
                jsonNodeData.add(key, toJsonPrimitive(value));
            }
        }
        root.add("data", jsonNodeData);
    }
    // serialize relationship data
    if (src.getRelData() != null) {
        for (Entry<String, Object> entry : src.getRelData().entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value != null) {
                jsonRelData.add(key, toJsonPrimitive(value));
            }
        }
        root.add("relData", jsonRelData);
    }
    // serialize result list
    if (src.getResult() != null) {
        if ("GRAPHQL".equals(src.getCommand())) {
            try {
                if (src.getResult() != null && !src.getResult().isEmpty()) {
                    final GraphObject firstResultObject = src.getResult().get(0);
                    final SecurityContext securityContext = firstResultObject.getSecurityContext();
                    final StringWriter output = new StringWriter();
                    final String query = (String) src.getNodeData().get("query");
                    final Document doc = GraphQLRequest.parse(new Parser(), query);
                    final GraphQLWriter graphQLWriter = new GraphQLWriter(false);
                    graphQLWriter.stream(securityContext, output, new GraphQLRequest(securityContext, doc, query));
                    JsonElement graphQLResult = new JsonParser().parse(output.toString());
                    root.add("result", graphQLResult);
                } else {
                    root.add("result", new JsonArray());
                }
            } catch (IOException | FrameworkException ex) {
                logger.warn("Unable to set process GraphQL query", ex);
            }
        } else {
            if (src.getView() != null) {
                try {
                    propertyView.set(null, src.getView());
                } catch (FrameworkException fex) {
                    logger.warn("Unable to set property view", fex);
                }
            } else {
                try {
                    propertyView.set(null, PropertyView.Ui);
                } catch (FrameworkException fex) {
                    logger.warn("Unable to set property view", fex);
                }
            }
            JsonArray result = new JsonArray();
            for (GraphObject obj : src.getResult()) {
                result.add(graphObjectSerializer.serialize(obj, System.currentTimeMillis()));
            }
            root.add("result", result);
        }
        root.add("rawResultCount", toJsonPrimitive(src.getRawResultCount()));
    }
    return root;
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) Document(graphql.language.Document) JsonParser(com.google.gson.JsonParser) Parser(graphql.parser.Parser) JsonArray(com.google.gson.JsonArray) GraphQLRequest(org.structr.core.graphql.GraphQLRequest) GraphQLWriter(org.structr.rest.serialization.GraphQLWriter) StringWriter(java.io.StringWriter) JsonElement(com.google.gson.JsonElement) SecurityContext(org.structr.common.SecurityContext) JsonObject(com.google.gson.JsonObject) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey) JsonParser(com.google.gson.JsonParser)

Example 83 with PropertyKey

use of org.structr.core.property.PropertyKey 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 84 with PropertyKey

use of org.structr.core.property.PropertyKey in project structr by structr.

the class CreateAndAppendDOMNodeCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String parentId = (String) nodeData.get("parentId");
    final String childContent = (String) nodeData.get("childContent");
    final String pageId = webSocketData.getPageId();
    Boolean inheritVisibilityFlags = (Boolean) nodeData.get("inheritVisibilityFlags");
    if (inheritVisibilityFlags == null) {
        inheritVisibilityFlags = false;
    }
    // remove configuration elements from the nodeData so we don't set it on the node
    nodeData.remove("parentId");
    nodeData.remove("inheritVisibilityFlags");
    if (pageId != null) {
        // check for parent ID before creating any nodes
        if (parentId == null) {
            getWebSocket().send(MessageBuilder.status().code(422).message("Cannot add node without parentId").build(), true);
            return;
        }
        // check if parent node with given ID exists
        final DOMNode parentNode = getDOMNode(parentId);
        if (parentNode == null) {
            getWebSocket().send(MessageBuilder.status().code(404).message("Parent node not found").build(), true);
            return;
        }
        final Document document = getPage(pageId);
        if (document != null) {
            final String tagName = (String) nodeData.get("tagName");
            nodeData.remove("tagName");
            try {
                DOMNode newNode;
                if (tagName != null && "comment".equals(tagName)) {
                    newNode = (DOMNode) document.createComment("#comment");
                } else if (tagName != null && "template".equals(tagName)) {
                    newNode = (DOMNode) document.createTextNode("#template");
                    try {
                        newNode.unlockSystemPropertiesOnce();
                        newNode.setProperties(newNode.getSecurityContext(), new PropertyMap(NodeInterface.type, Template.class.getSimpleName()));
                    } catch (FrameworkException fex) {
                        logger.warn("Unable to set type of node {} to Template: {}", new Object[] { newNode.getUuid(), fex.getMessage() });
                    }
                } else if (tagName != null && !tagName.isEmpty()) {
                    if ("custom".equals(tagName)) {
                        try {
                            // experimental: create DOM element with literal tag
                            newNode = (DOMElement) StructrApp.getInstance(webSocket.getSecurityContext()).create(DOMElement.class, new NodeAttribute(StructrApp.key(DOMElement.class, "tag"), "custom"), new NodeAttribute(StructrApp.key(DOMElement.class, "hideOnDetail"), false), new NodeAttribute(StructrApp.key(DOMElement.class, "hideOnIndex"), false));
                            if (newNode != null && document != null) {
                                newNode.doAdopt((Page) document);
                            }
                        } catch (FrameworkException fex) {
                            // abort
                            getWebSocket().send(MessageBuilder.status().code(422).message(fex.getMessage()).build(), true);
                            return;
                        }
                    } else {
                        newNode = (DOMNode) document.createElement(tagName);
                    }
                } else {
                    newNode = (DOMNode) document.createTextNode("#text");
                }
                // Instantiate node again to get correct class
                newNode = getDOMNode(newNode.getUuid());
                // append new node to parent
                if (newNode != null) {
                    parentNode.appendChild(newNode);
                    for (Entry entry : nodeData.entrySet()) {
                        final String key = (String) entry.getKey();
                        final Object val = entry.getValue();
                        PropertyKey propertyKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(newNode.getClass(), key);
                        if (propertyKey != null) {
                            try {
                                Object convertedValue = val;
                                PropertyConverter inputConverter = propertyKey.inputConverter(SecurityContext.getSuperUserInstance());
                                if (inputConverter != null) {
                                    convertedValue = inputConverter.convert(val);
                                }
                                newNode.setProperties(newNode.getSecurityContext(), new PropertyMap(propertyKey, convertedValue));
                            } catch (FrameworkException fex) {
                                logger.warn("Unable to set node property {} of node {} to {}: {}", new Object[] { propertyKey, newNode.getUuid(), val, fex.getMessage() });
                            }
                        }
                    }
                    PropertyMap visibilityFlags = null;
                    if (inheritVisibilityFlags) {
                        visibilityFlags = new PropertyMap();
                        visibilityFlags.put(DOMNode.visibleToAuthenticatedUsers, parentNode.getProperty(DOMNode.visibleToAuthenticatedUsers));
                        visibilityFlags.put(DOMNode.visibleToPublicUsers, parentNode.getProperty(DOMNode.visibleToPublicUsers));
                        try {
                            newNode.setProperties(newNode.getSecurityContext(), visibilityFlags);
                        } catch (FrameworkException fex) {
                            logger.warn("Unable to inherit visibility flags for node {} from parent node {}", newNode, parentNode);
                        }
                    }
                    // create a child text node if content is given
                    if (StringUtils.isNotBlank(childContent)) {
                        final DOMNode childNode = (DOMNode) document.createTextNode(childContent);
                        newNode.appendChild(childNode);
                        if (inheritVisibilityFlags) {
                            try {
                                childNode.setProperties(childNode.getSecurityContext(), visibilityFlags);
                            } catch (FrameworkException fex) {
                                logger.warn("Unable to inherit visibility flags for node {} from parent node {}", childNode, newNode);
                            }
                        }
                    }
                }
            } catch (DOMException dex) {
                // send DOM exception
                getWebSocket().send(MessageBuilder.status().code(422).message(dex.getMessage()).build(), true);
            }
        } else {
            getWebSocket().send(MessageBuilder.status().code(404).message("Page not found").build(), true);
        }
    } else {
        getWebSocket().send(MessageBuilder.status().code(422).message("Cannot create node without pageId").build(), true);
    }
}
Also used : NodeAttribute(org.structr.core.graph.NodeAttribute) FrameworkException(org.structr.common.error.FrameworkException) Document(org.w3c.dom.Document) Template(org.structr.web.entity.dom.Template) DOMException(org.w3c.dom.DOMException) Entry(java.util.Map.Entry) PropertyMap(org.structr.core.property.PropertyMap) PropertyConverter(org.structr.core.converter.PropertyConverter) DOMNode(org.structr.web.entity.dom.DOMNode) PropertyKey(org.structr.core.property.PropertyKey)

Example 85 with PropertyKey

use of org.structr.core.property.PropertyKey in project structr by structr.

the class ListCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final SecurityContext securityContext = getWebSocket().getSecurityContext();
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String rawType = (String) nodeData.get("type");
    final String properties = (String) webSocketData.getNodeData().get("properties");
    final boolean rootOnly = Boolean.TRUE.equals((Boolean) nodeData.get("rootOnly"));
    Class type = SchemaHelper.getEntityClassForRawType(rawType);
    if (type == null) {
        getWebSocket().send(MessageBuilder.status().code(404).message("Type " + rawType + " not found").build(), true);
        return;
    }
    if (properties != null) {
        securityContext.setCustomView(StringUtils.split(properties, ","));
    }
    final String sortOrder = webSocketData.getSortOrder();
    final String sortKey = webSocketData.getSortKey();
    final int pageSize = webSocketData.getPageSize();
    final int page = webSocketData.getPage();
    final PropertyKey sortProperty = StructrApp.key(type, sortKey);
    final Query query = StructrApp.getInstance(securityContext).nodeQuery(type).sort(sortProperty).order("desc".equals(sortOrder)).page(page).pageSize(pageSize);
    if (File.class.isAssignableFrom(type)) {
        if (rootOnly) {
            query.and(StructrApp.key(File.class, "hasParent"), false);
        }
        // inverted as isThumbnail is not necessarily present in all objects inheriting from FileBase
        query.not().and(StructrApp.key(Image.class, "isThumbnail"), true);
    }
    // important
    if (Folder.class.isAssignableFrom(type) && rootOnly) {
        query.and(StructrApp.key(Folder.class, "hasParent"), false);
    }
    try {
        // do search
        final Result result = query.getResult();
        // save raw result count
        // filteredResults.size();
        int resultCountBeforePaging = result.getRawResultCount();
        // set full result list
        webSocketData.setResult(result.getResults());
        webSocketData.setRawResultCount(resultCountBeforePaging);
        // send only over local connection
        getWebSocket().send(webSocketData, true);
    } catch (FrameworkException fex) {
        logger.warn("Exception occured", fex);
        getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true);
    }
}
Also used : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) Image(org.structr.web.entity.Image) Folder(org.structr.web.entity.Folder) Result(org.structr.core.Result) SecurityContext(org.structr.common.SecurityContext) File(org.structr.web.entity.File) PropertyKey(org.structr.core.property.PropertyKey)

Aggregations

PropertyKey (org.structr.core.property.PropertyKey)177 FrameworkException (org.structr.common.error.FrameworkException)108 Test (org.junit.Test)69 NodeInterface (org.structr.core.graph.NodeInterface)62 Tx (org.structr.core.graph.Tx)61 GraphObject (org.structr.core.GraphObject)59 StructrTest (org.structr.common.StructrTest)39 PropertyMap (org.structr.core.property.PropertyMap)37 List (java.util.List)31 Result (org.structr.core.Result)28 ConfigurationProvider (org.structr.schema.ConfigurationProvider)27 SecurityContext (org.structr.common.SecurityContext)26 LinkedList (java.util.LinkedList)22 StringProperty (org.structr.core.property.StringProperty)22 ErrorToken (org.structr.common.error.ErrorToken)20 Map (java.util.Map)18 PropertyConverter (org.structr.core.converter.PropertyConverter)18 NodeAttribute (org.structr.core.graph.NodeAttribute)17 App (org.structr.core.app.App)16 StructrApp (org.structr.core.app.StructrApp)16