Search in sources :

Example 21 with PropertyConverter

use of org.structr.core.converter.PropertyConverter 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 22 with PropertyConverter

use of org.structr.core.converter.PropertyConverter 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)

Example 23 with PropertyConverter

use of org.structr.core.converter.PropertyConverter in project structr by structr.

the class StructrPropertyValueChannel method getConvertedPropertyValue.

// ----- public static methods -----
public static String getConvertedPropertyValue(final SecurityContext securityContext, final GraphObject graphObject, final PropertyKey key) throws IOException, FrameworkException {
    final PropertyConverter inputConverter = key.inputConverter(securityContext);
    Object actualValue = graphObject.getProperty(key);
    if (inputConverter != null) {
        actualValue = inputConverter.revert(actualValue);
    }
    if (actualValue != null) {
        return actualValue.toString();
    }
    return "";
}
Also used : PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject)

Example 24 with PropertyConverter

use of org.structr.core.converter.PropertyConverter in project structr by structr.

the class AbstractPrimitiveProperty method setProperty.

@Override
public Object setProperty(final SecurityContext securityContext, final GraphObject obj, final T value) throws FrameworkException {
    final PropertyConverter converter = databaseConverter(securityContext, PropertyMap.unwrap(obj));
    Object convertedValue = value;
    if (converter != null) {
        convertedValue = converter.convert(value);
    }
    // use transformators from property
    for (final String fqcn : transformators) {
        // first test, use caching here later..
        final Transformer transformator = getTransformator(fqcn);
        if (transformator != null) {
            convertedValue = transformator.setProperty(PropertyMap.unwrap(obj), this, convertedValue);
        }
    }
    final PropertyContainer propertyContainer = obj.getPropertyContainer();
    if (propertyContainer != null) {
        if (!TransactionCommand.inTransaction()) {
            throw new NotInTransactionException("setProperty outside of transaction");
        }
        boolean internalSystemPropertiesUnlocked = (obj instanceof CreationContainer);
        // collect modified properties
        if (obj instanceof AbstractNode) {
            if (!unvalidated) {
                TransactionCommand.nodeModified(securityContext.getCachedUser(), (AbstractNode) obj, AbstractPrimitiveProperty.this, propertyContainer.hasProperty(dbName()) ? propertyContainer.getProperty(dbName()) : null, value);
            }
            internalSystemPropertiesUnlocked = ((AbstractNode) obj).internalSystemPropertiesUnlocked;
        } else if (obj instanceof AbstractRelationship) {
            if (!unvalidated) {
                TransactionCommand.relationshipModified(securityContext.getCachedUser(), (AbstractRelationship) obj, AbstractPrimitiveProperty.this, propertyContainer.hasProperty(dbName()) ? propertyContainer.getProperty(dbName()) : null, value);
            }
            internalSystemPropertiesUnlocked = ((AbstractRelationship) obj).internalSystemPropertiesUnlocked;
        }
        // catch all sorts of errors and wrap them in a FrameworkException
        try {
            // save space
            if (convertedValue == null) {
                propertyContainer.removeProperty(dbName());
            } else {
                if (!isSystemInternal() || internalSystemPropertiesUnlocked) {
                    propertyContainer.setProperty(dbName(), convertedValue);
                } else {
                    logger.warn("Tried to set internal system property {} to {}. Action was denied.", new Object[] { dbName(), convertedValue });
                }
            }
            updateAccessInformation(securityContext, propertyContainer);
        } catch (final RetryException rex) {
            // don't catch RetryException here
            throw rex;
        } catch (Throwable t) {
            // throw FrameworkException with the given cause
            final FrameworkException fex = new FrameworkException(500, "Unable to set property " + jsonName() + " on entity with ID " + obj.getUuid() + ": " + t.toString());
            fex.initCause(t);
            throw fex;
        }
        if (isIndexed()) {
            // work
            if (!isPassivelyIndexed()) {
                index(obj, convertedValue);
            }
        }
    }
    return null;
}
Also used : PropertyContainer(org.structr.api.graph.PropertyContainer) Transformer(org.structr.schema.Transformer) FrameworkException(org.structr.common.error.FrameworkException) AbstractNode(org.structr.core.entity.AbstractNode) AbstractRelationship(org.structr.core.entity.AbstractRelationship) CreationContainer(org.structr.core.graph.CreationContainer) RetryException(org.structr.api.RetryException) NotInTransactionException(org.structr.api.NotInTransactionException) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject)

Example 25 with PropertyConverter

use of org.structr.core.converter.PropertyConverter in project structr by structr.

the class AbstractPrimitiveProperty method getProperty.

@Override
public T getProperty(final SecurityContext securityContext, final GraphObject obj, final boolean applyConverter, final Predicate<GraphObject> predicate) {
    Object value = null;
    final PropertyContainer propertyContainer = obj.getPropertyContainer();
    if (propertyContainer != null) {
        // this may throw a java.lang.IllegalStateException: Relationship[<id>] has been deleted in this tx
        if (propertyContainer.hasProperty(dbName())) {
            value = propertyContainer.getProperty(dbName());
        }
    }
    if (applyConverter) {
        // apply property converters
        PropertyConverter converter = databaseConverter(securityContext, PropertyMap.unwrap(obj));
        if (converter != null) {
            try {
                value = converter.revert(value);
            } catch (Throwable t) {
                logger.warn("Unable to convert property {} of type {}: {}", new Object[] { dbName(), getClass().getSimpleName(), t });
                logger.warn("", t);
            }
        }
    }
    // use transformators from property
    for (final String fqcn : transformators) {
        // first test, use caching here later..
        final Transformer transformator = getTransformator(fqcn);
        if (transformator != null) {
            value = transformator.getProperty(PropertyMap.unwrap(obj), this, value);
        }
    }
    // no value found, use schema default
    if (value == null) {
        value = defaultValue();
    }
    return (T) value;
}
Also used : PropertyContainer(org.structr.api.graph.PropertyContainer) Transformer(org.structr.schema.Transformer) PropertyConverter(org.structr.core.converter.PropertyConverter) GraphObject(org.structr.core.GraphObject)

Aggregations

PropertyConverter (org.structr.core.converter.PropertyConverter)44 GraphObject (org.structr.core.GraphObject)31 FrameworkException (org.structr.common.error.FrameworkException)28 PropertyKey (org.structr.core.property.PropertyKey)18 SecurityContext (org.structr.common.SecurityContext)11 PropertyMap (org.structr.core.property.PropertyMap)10 ConfigurationProvider (org.structr.schema.ConfigurationProvider)10 Map (java.util.Map)9 AbstractNode (org.structr.core.entity.AbstractNode)6 List (java.util.List)5 App (org.structr.core.app.App)5 StructrApp (org.structr.core.app.StructrApp)5 LinkedList (java.util.LinkedList)4 Test (org.junit.Test)4 StructrTest (org.structr.common.StructrTest)4 Query (org.structr.core.app.Query)4 LinkedHashMap (java.util.LinkedHashMap)3 GraphObjectMap (org.structr.core.GraphObjectMap)3 LinkedHashSet (java.util.LinkedHashSet)2 Entry (java.util.Map.Entry)2