Search in sources :

Example 76 with GraphObject

use of org.structr.core.GraphObject in project structr by structr.

the class ValidationHelper method isValidUniqueProperty.

public static synchronized boolean isValidUniqueProperty(final GraphObject object, final PropertyKey key, final ErrorBuffer errorBuffer) {
    if (key != null) {
        final Object value = object.getProperty(key);
        if (value != null) {
            // validation will only be executed for non-null values
            List<GraphObject> result = null;
            // use declaring class for inheritance-aware uniqueness
            Class type = key.getDeclaringClass();
            if (type == null || (AbstractNode.name.equals(key) && NodeInterface.class.equals(type))) {
                // fallback: object type
                type = object.getClass();
            }
            try {
                if (object instanceof NodeInterface) {
                    result = StructrApp.getInstance().nodeQuery(type).and(key, value).getAsList();
                } else {
                    result = StructrApp.getInstance().relationshipQuery(type).and(key, value).getAsList();
                }
            } catch (FrameworkException fex) {
                logger.warn("", fex);
            }
            if (result != null) {
                for (final GraphObject foundNode : result) {
                    if (foundNode.getId() != object.getId()) {
                        // validation is aborted when the first validation failure occurs, so
                        // we can assume that the object currently exmained is the first
                        // existing object, hence all others get the error message with the
                        // UUID of the first one.
                        errorBuffer.add(new UniqueToken(object.getType(), key, object.getUuid()));
                        // error!
                        return false;
                    }
                }
            }
        }
    }
    // no error
    return true;
}
Also used : UniqueToken(org.structr.common.error.UniqueToken) FrameworkException(org.structr.common.error.FrameworkException) GraphObject(org.structr.core.GraphObject) GraphObject(org.structr.core.GraphObject) NodeInterface(org.structr.core.graph.NodeInterface)

Example 77 with GraphObject

use of org.structr.core.GraphObject in project structr by structr.

the class ValidationHelper method isValidPropertyNotNull.

/**
 * Checks whether the value for the given property key of the given node
 * is a non-empty string.
 *
 * @param node the node
 * @param key the property key
 * @param errorBuffer the error buffer
 *
 * @return true if the condition is valid
 */
public static boolean isValidPropertyNotNull(final GraphObject node, final PropertyKey key, final ErrorBuffer errorBuffer) {
    final String type = node.getType();
    if (key == null) {
        errorBuffer.add(new EmptyPropertyToken(type, UnknownType));
        return false;
    }
    final Object value = node.getProperty(key);
    if (value != null) {
        if (value instanceof Iterable) {
            if (((Iterable) value).iterator().hasNext()) {
                return true;
            }
        } else {
            return true;
        }
    }
    errorBuffer.add(new EmptyPropertyToken(type, key));
    return false;
}
Also used : EmptyPropertyToken(org.structr.common.error.EmptyPropertyToken) GraphObject(org.structr.core.GraphObject)

Example 78 with GraphObject

use of org.structr.core.GraphObject in project structr by structr.

the class ValidationHelper method areValidCompoundUniqueProperties.

public static synchronized boolean areValidCompoundUniqueProperties(final GraphObject object, final ErrorBuffer errorBuffer, final PropertyKey... keys) {
    if (keys != null && keys.length > 0) {
        final PropertyMap properties = new PropertyMap();
        List<GraphObject> result = null;
        Class type = null;
        for (final PropertyKey key : keys) {
            properties.put(key, object.getProperty(key));
            if (type != null) {
                // set type on first iteration
                type = key.getDeclaringClass();
            }
        }
        if (type == null) {
            // fallback: object type
            type = object.getClass();
        }
        try {
            if (object instanceof NodeInterface) {
                result = StructrApp.getInstance().nodeQuery(type).and(properties).disableSorting().getAsList();
            } else {
                result = StructrApp.getInstance().relationshipQuery(type).and(properties).disableSorting().getAsList();
            }
        } catch (FrameworkException fex) {
            logger.warn("", fex);
        }
        if (result != null) {
            for (final GraphObject foundNode : result) {
                if (foundNode.getId() != object.getId()) {
                    // validation is aborted when the first validation failure occurs, so
                    // we can assume that the object currently exmained is the first
                    // existing object, hence all others get the error message with the
                    // UUID of the first one.
                    errorBuffer.add(new CompoundToken(object.getType(), keys, object.getUuid()));
                    // error!
                    return false;
                }
            }
        }
    }
    // no error
    return true;
}
Also used : CompoundToken(org.structr.common.error.CompoundToken) PropertyMap(org.structr.core.property.PropertyMap) FrameworkException(org.structr.common.error.FrameworkException) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey) NodeInterface(org.structr.core.graph.NodeInterface)

Example 79 with GraphObject

use of org.structr.core.GraphObject in project structr by structr.

the class PathResolvingComparator method resolve.

// ----- private methods -----
private Comparable resolve(final GraphObject obj, final String path) {
    final ConfigurationProvider config = StructrApp.getConfiguration();
    final String[] parts = path.split("[\\.]+");
    GraphObject current = obj;
    int pos = 0;
    for (final String part : parts) {
        final Class type = current.getEntityType();
        final PropertyKey key = config.getPropertyKeyForJSONName(type, part, false);
        if (key == null) {
            logger.warn("Unknown key {} while resolving path {} for sorting.", part, path);
            return null;
        }
        final Object value = current.getProperty(key);
        if (value != null) {
            // last part of path?
            if (++pos == parts.length) {
                if (value instanceof Comparable) {
                    return (Comparable) value;
                }
                logger.warn("Path evaluation result of component {} of type {} in {} cannot be used for sorting.", part, value.getClass().getSimpleName(), path);
                return null;
            }
            if (value instanceof GraphObject) {
                current = (GraphObject) value;
            } else {
                logger.warn("Path component {} of type {} in {} cannot be evaluated further.", part, value.getClass().getSimpleName(), path);
                return null;
            }
        }
    }
    return null;
}
Also used : ConfigurationProvider(org.structr.schema.ConfigurationProvider) GraphObject(org.structr.core.GraphObject) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey)

Example 80 with GraphObject

use of org.structr.core.GraphObject in project structr by structr.

the class CreateNodeCommand method execute.

public T execute(final PropertyMap attributes) throws FrameworkException {
    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    final Principal user = securityContext.getUser(false);
    T node = null;
    if (graphDb != null) {
        final NodeFactory<T> nodeFactory = new NodeFactory<>(securityContext);
        final PropertyMap properties = new PropertyMap(attributes);
        final PropertyMap toNotify = new PropertyMap();
        final Object typeObject = properties.get(AbstractNode.type);
        final Class nodeType = getTypeOrGeneric(typeObject);
        final Set<String> labels = TypeProperty.getLabelsForType(nodeType);
        final CreationContainer tmp = new CreationContainer();
        final Date now = new Date();
        final boolean isCreation = true;
        // use user-supplied UUID?
        String uuid = properties.get(GraphObject.id);
        if (uuid == null) {
            // no, create new one
            uuid = getNextUuid();
            properties.put(GraphObject.id, uuid);
        } else {
            // enable UUID validation
            securityContext.uuidWasSetManually(true);
        }
        // use property keys to set property values on creation dummy
        // set default values for common properties in creation query
        GraphObject.id.setProperty(securityContext, tmp, uuid);
        GraphObject.type.setProperty(securityContext, tmp, nodeType.getSimpleName());
        AbstractNode.createdDate.setProperty(securityContext, tmp, now);
        AbstractNode.lastModifiedDate.setProperty(securityContext, tmp, now);
        // default property values
        AbstractNode.visibleToPublicUsers.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.visibleToPublicUsers, false));
        AbstractNode.visibleToAuthenticatedUsers.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.visibleToAuthenticatedUsers, false));
        AbstractNode.hidden.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.hidden, false));
        AbstractNode.deleted.setProperty(securityContext, tmp, getOrDefault(properties, AbstractNode.deleted, false));
        if (user != null) {
            final String userId = user.getProperty(GraphObject.id);
            AbstractNode.createdBy.setProperty(securityContext, tmp, userId);
            AbstractNode.lastModifiedBy.setProperty(securityContext, tmp, userId);
        }
        // prevent double setting of properties
        properties.remove(AbstractNode.id);
        properties.remove(AbstractNode.type);
        properties.remove(AbstractNode.visibleToPublicUsers);
        properties.remove(AbstractNode.visibleToAuthenticatedUsers);
        properties.remove(AbstractNode.hidden);
        properties.remove(AbstractNode.deleted);
        properties.remove(AbstractNode.lastModifiedDate);
        properties.remove(AbstractNode.lastModifiedBy);
        properties.remove(AbstractNode.createdDate);
        properties.remove(AbstractNode.createdBy);
        // move properties to creation container that can be set directly on creation
        tmp.filterIndexableForCreation(securityContext, properties, tmp, toNotify);
        // collect default values and try to set them on creation
        for (final PropertyKey key : StructrApp.getConfiguration().getPropertySet(nodeType, PropertyView.All)) {
            if (key instanceof AbstractPrimitiveProperty && !tmp.hasProperty(key.jsonName())) {
                final Object defaultValue = key.defaultValue();
                if (defaultValue != null) {
                    key.setProperty(securityContext, tmp, defaultValue);
                }
            }
        }
        node = (T) nodeFactory.instantiateWithType(createNode(graphDb, user, labels, tmp.getData()), nodeType, null, isCreation);
        if (node != null) {
            TransactionCommand.nodeCreated(user, node);
            securityContext.disableModificationOfAccessTime();
            node.setProperties(securityContext, properties);
            securityContext.enableModificationOfAccessTime();
            // ensure modification callbacks are called (necessary for validation)
            for (final Entry<PropertyKey, Object> entry : toNotify.entrySet()) {
                final PropertyKey key = entry.getKey();
                final Object value = entry.getValue();
                if (!key.isUnvalidated()) {
                    TransactionCommand.nodeModified(securityContext.getCachedUser(), (AbstractNode) node, key, null, value);
                }
            }
            properties.clear();
            // ensure indexing of newly created node
            node.addToIndex();
            // invalidate UUID cache
            StructrApp.invalidate(uuid);
        }
    }
    if (node != null) {
        // notify node of its creation
        node.onNodeCreation();
        // iterate post creation transformations
        final Set<Transformation<GraphObject>> transformations = StructrApp.getConfiguration().getEntityCreationTransformations(node.getClass());
        for (Transformation<GraphObject> transformation : transformations) {
            transformation.apply(securityContext, node);
        }
    }
    return node;
}
Also used : Transformation(org.structr.core.Transformation) DatabaseService(org.structr.api.DatabaseService) GraphObject(org.structr.core.GraphObject) Date(java.util.Date) PropertyMap(org.structr.core.property.PropertyMap) AbstractPrimitiveProperty(org.structr.core.property.AbstractPrimitiveProperty) GraphObject(org.structr.core.GraphObject) Principal(org.structr.core.entity.Principal) PropertyKey(org.structr.core.property.PropertyKey)

Aggregations

GraphObject (org.structr.core.GraphObject)151 FrameworkException (org.structr.common.error.FrameworkException)58 PropertyKey (org.structr.core.property.PropertyKey)39 LinkedList (java.util.LinkedList)35 SecurityContext (org.structr.common.SecurityContext)25 App (org.structr.core.app.App)25 StructrApp (org.structr.core.app.StructrApp)24 Tx (org.structr.core.graph.Tx)23 List (java.util.List)22 PropertyConverter (org.structr.core.converter.PropertyConverter)22 AbstractNode (org.structr.core.entity.AbstractNode)18 GraphObjectMap (org.structr.core.GraphObjectMap)17 NodeInterface (org.structr.core.graph.NodeInterface)17 LinkedHashSet (java.util.LinkedHashSet)15 PropertyMap (org.structr.core.property.PropertyMap)13 Map (java.util.Map)12 RestMethodResult (org.structr.rest.RestMethodResult)11 ConfigurationProvider (org.structr.schema.ConfigurationProvider)10 Result (org.structr.core.Result)9 ArrayList (java.util.ArrayList)8