Search in sources :

Example 96 with PropertyKey

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

the class MapPropertyGroup method getGroupedProperties.

// ~--- get methods ----------------------------------------------------
@Override
public PropertyMap getGroupedProperties(SecurityContext securityContext, GraphObject source) {
    PropertyMap groupedProperties = new PropertyMap();
    for (PropertyKey key : propertyKeys) {
        PropertyConverter converter = key.inputConverter(securityContext);
        if (converter != null) {
            try {
                Object convertedValue = converter.revert(source.getProperty(key));
                groupedProperties.put(key, convertedValue);
            } catch (FrameworkException fex) {
                logger.warn("Unable to convert grouped property {} on type {}: {}", new Object[] { key.dbName(), source.getClass().getSimpleName(), fex.getMessage() });
            }
        } else {
            groupedProperties.put(key, source.getProperty(key));
        }
    }
    return groupedProperties;
}
Also used : PropertyMap(org.structr.core.property.PropertyMap) FrameworkException(org.structr.common.error.FrameworkException) PropertyConverter(org.structr.core.converter.PropertyConverter) PropertyKey(org.structr.core.property.PropertyKey)

Example 97 with PropertyKey

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

the class BulkFixNodePropertiesCommand method execute.

@Override
public void execute(Map<String, Object> attributes) throws FrameworkException {
    final String propertyName = (String) attributes.get("name");
    final String entityTypeName = (String) attributes.get("type");
    if (entityTypeName != null) {
        final Class type = SchemaHelper.getEntityClassForRawType(entityTypeName);
        if (type != null) {
            final DatabaseService db = StructrApp.getInstance(securityContext).getDatabaseService();
            final NodeFactory factory = new NodeFactory(securityContext);
            final Iterator<AbstractNode> nodeIterator = Iterables.map(factory, db.getNodesByLabel(entityTypeName)).iterator();
            logger.info("Trying to fix properties of all {} nodes", type.getSimpleName());
            long nodeCount = bulkGraphOperation(securityContext, nodeIterator, 100, "FixNodeProperties", new BulkGraphOperation<AbstractNode>() {

                private void fixProperty(AbstractNode node, Property propertyToFix) {
                    Node databaseNode = node.getNode();
                    if (databaseNode.hasProperty(propertyToFix.dbName())) {
                        // check value with property converter
                        PropertyConverter converter = propertyToFix.databaseConverter(securityContext, node);
                        if (converter != null) {
                            try {
                                Object value = databaseNode.getProperty(propertyToFix.dbName());
                                converter.revert(value);
                            } catch (ClassCastException cce) {
                                // exception, needs fix
                                String databaseName = propertyToFix.dbName();
                                Object databaseValue = databaseNode.getProperty(databaseName);
                                Object correctedValue = propertyToFix.fixDatabaseProperty(databaseValue);
                                if (databaseValue != null && correctedValue != null) {
                                    try {
                                        // try to set database value to corrected value
                                        databaseNode.setProperty(databaseName, correctedValue);
                                    } catch (Throwable t) {
                                        logger.warn("Unable to fix property {} of {} with UUID {} which is of type {}", new Object[] { propertyToFix.dbName(), type.getSimpleName(), node.getUuid(), databaseValue != null ? databaseValue.getClass() : "null" });
                                    }
                                }
                            } catch (Throwable t) {
                                // log exceptions of other types
                                logger.warn("", t);
                            }
                        }
                    }
                }

                @Override
                public void handleGraphObject(SecurityContext securityContext, AbstractNode node) {
                    if (propertyName != null) {
                        PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, propertyName);
                        if (key != null) {
                            // needs type cast to Property to use fixDatabaseProperty method
                            if (key instanceof Property) {
                                fixProperty(node, (Property) key);
                            }
                        }
                    } else {
                        for (PropertyKey key : node.getPropertyKeys(PropertyView.All)) {
                            // needs type cast to Property to use fixDatabaseProperty method
                            if (key instanceof Property) {
                                fixProperty(node, (Property) key);
                            }
                        }
                    }
                }
            });
            logger.info("Fixed {} nodes", nodeCount);
            return;
        }
    }
    logger.info("Unable to determine property and/or entity type to fix.");
}
Also used : AbstractNode(org.structr.core.entity.AbstractNode) Node(org.structr.api.graph.Node) AbstractNode(org.structr.core.entity.AbstractNode) DatabaseService(org.structr.api.DatabaseService) PropertyConverter(org.structr.core.converter.PropertyConverter) SecurityContext(org.structr.common.SecurityContext) Property(org.structr.core.property.Property) PropertyKey(org.structr.core.property.PropertyKey)

Example 98 with PropertyKey

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

the class BulkSetNodePropertiesCommand method execute.

// ~--- methods --------------------------------------------------------
@Override
public void execute(final Map<String, Object> properties) throws FrameworkException {
    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    final SecurityContext superUserContext = SecurityContext.getSuperUserInstance();
    final NodeFactory nodeFactory = new NodeFactory(superUserContext);
    final String type = (String) properties.get("type");
    if (StringUtils.isBlank(type)) {
        throw new FrameworkException(422, "Type must not be empty");
    }
    final Class cls = SchemaHelper.getEntityClassForRawType(type);
    if (cls == null) {
        throw new FrameworkException(422, "Invalid type " + type);
    }
    if (graphDb != null) {
        final App app = StructrApp.getInstance(securityContext);
        Iterator<AbstractNode> nodeIterator = null;
        if (properties.containsKey(AbstractNode.type.dbName())) {
            try (final Tx tx = app.tx()) {
                nodeIterator = app.nodeQuery(cls).getResult().getResults().iterator();
                properties.remove(AbstractNode.type.dbName());
                tx.success();
            }
        } else {
            nodeIterator = Iterables.map(nodeFactory, graphDb.getAllNodes()).iterator();
        }
        // remove "type" so it won't be set later
        properties.remove("type");
        final long count = bulkGraphOperation(securityContext, nodeIterator, 1000, "SetNodeProperties", new BulkGraphOperation<AbstractNode>() {

            @Override
            public void handleGraphObject(SecurityContext securityContext, AbstractNode node) {
                // Treat only "our" nodes
                if (node.getProperty(GraphObject.id) != null) {
                    for (Entry entry : properties.entrySet()) {
                        String key = (String) entry.getKey();
                        Object val = null;
                        // allow to set new type
                        if (key.equals("newType")) {
                            key = "type";
                        }
                        PropertyConverter inputConverter = StructrApp.key(cls, key).inputConverter(securityContext);
                        if (inputConverter != null) {
                            try {
                                val = inputConverter.convert(entry.getValue());
                            } catch (FrameworkException ex) {
                                logger.error("", ex);
                            }
                        } else {
                            val = entry.getValue();
                        }
                        PropertyKey propertyKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(node.getClass(), key);
                        if (propertyKey != null) {
                            try {
                                node.unlockSystemPropertiesOnce();
                                node.setProperty(propertyKey, val);
                            } catch (FrameworkException fex) {
                                logger.warn("Unable to set node property {} of node {} to {}: {}", new Object[] { propertyKey, node.getUuid(), val, fex.getMessage() });
                            }
                        }
                    }
                }
            }

            @Override
            public void handleThrowable(SecurityContext securityContext, Throwable t, AbstractNode node) {
                logger.warn("Unable to set properties of node {}: {}", new Object[] { node.getUuid(), t.getMessage() });
            }

            @Override
            public void handleTransactionFailure(SecurityContext securityContext, Throwable t) {
                logger.warn("Unable to set node properties: {}", t.getMessage());
            }
        });
        logger.info("Fixed {} nodes ...", count);
    }
    logger.info("Done");
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) DatabaseService(org.structr.api.DatabaseService) Entry(java.util.Map.Entry) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey)

Example 99 with PropertyKey

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

Example 100 with PropertyKey

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

the class SearchFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    try {
        if (sources == null) {
            throw new IllegalArgumentException();
        }
        final SecurityContext securityContext = ctx.getSecurityContext();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        final Query query = StructrApp.getInstance(securityContext).nodeQuery();
        applyRange(securityContext, query);
        Class type = null;
        if (sources.length >= 1 && sources[0] != null) {
            final String typeString = sources[0].toString();
            type = config.getNodeEntityClass(typeString);
            if (type != null) {
                query.andTypes(type);
            } else {
                logger.warn("Error in search(): type {} not found.", typeString);
                return "Error in search(): type " + typeString + " not found.";
            }
        }
        // exit gracefully instead of crashing..
        if (type == null) {
            logger.warn("Error in search(): no type specified. Parameters: {}", getParametersAsString(sources));
            return "Error in search(): no type specified.";
        }
        // experimental: disable result count, prevents instantiation
        // of large collections just for counting all the objects..
        securityContext.ignoreResultCount(true);
        // extension for native javascript objects
        if (sources.length == 2 && sources[1] instanceof Map) {
            final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]);
            for (final Map.Entry<PropertyKey, Object> entry : map.entrySet()) {
                query.and(entry.getKey(), entry.getValue(), false);
            }
        } else {
            final int parameter_count = sources.length;
            if (parameter_count % 2 == 0) {
                throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_SEARCH);
            }
            for (int c = 1; c < parameter_count; c += 2) {
                final PropertyKey key = StructrApp.key(type, sources[c].toString());
                if (key != null) {
                    final PropertyConverter inputConverter = key.inputConverter(securityContext);
                    Object value = sources[c + 1];
                    if (inputConverter != null) {
                        value = inputConverter.convert(value);
                    }
                    query.and(key, value, false);
                }
            }
        }
        // return search results
        return query.getAsList();
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    } finally {
        resetRange();
    }
}
Also used : Query(org.structr.core.app.Query) FrameworkException(org.structr.common.error.FrameworkException) ConfigurationProvider(org.structr.schema.ConfigurationProvider) PropertyMap(org.structr.core.property.PropertyMap) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) 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