Search in sources :

Example 46 with GraphObjectMap

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

the class StaticRelationshipResource method doGet.

// ~--- methods --------------------------------------------------------
@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
    // ok, source node exists, fetch it
    final GraphObject sourceEntity = typedIdResource.getEntity();
    if (sourceEntity != null) {
        // first try: look through existing relations
        if (propertyKey == null) {
            if (sourceEntity instanceof NodeInterface) {
                if (!typeResource.isNode) {
                    final NodeInterface source = (NodeInterface) sourceEntity;
                    final Node sourceNode = source.getNode();
                    final Class relationshipType = typeResource.entityClass;
                    final Relation relation = AbstractNode.getRelationshipForType(relationshipType);
                    final Class destNodeType = relation.getOtherType(typedIdResource.getEntityClass());
                    final Set partialResult = new LinkedHashSet<>(typeResource.doGet(sortKey, sortDescending, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults());
                    // filter list according to end node type
                    final Set<GraphObject> set = Iterables.toSet(Iterables.filter(new OtherNodeTypeRelationFilter(securityContext, sourceNode, destNodeType), source.getRelationships(relationshipType)));
                    // intersect partial result with result list
                    set.retainAll(partialResult);
                    final List<GraphObject> finalResult = new LinkedList<>(set);
                    // sort after merge
                    applyDefaultSorting(finalResult, sortKey, sortDescending);
                    // return result
                    return new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
                } else {
                    // what here?
                    throw new NotFoundException("Cannot access relationship collection " + typeResource.getRawType());
                }
            }
        } else {
            Query query = typeResource.query;
            if (query == null) {
                query = StructrApp.getInstance(securityContext).nodeQuery();
            }
            // use search context from type resource
            typeResource.collectSearchAttributes(query);
            final Predicate<GraphObject> predicate = query.toPredicate();
            final Object value = sourceEntity.getProperty(propertyKey, predicate);
            if (value != null) {
                if (value instanceof Iterable) {
                    final Set<Object> propertyResults = new LinkedHashSet<>();
                    Iterator<Object> iter = ((Iterable<Object>) value).iterator();
                    boolean iterableContainsGraphObject = false;
                    while (iter.hasNext()) {
                        Object obj = iter.next();
                        propertyResults.add(obj);
                        if (obj != null && !iterableContainsGraphObject) {
                            if (obj instanceof GraphObject) {
                                iterableContainsGraphObject = true;
                            }
                        }
                    }
                    int rawResultCount = propertyResults.size();
                    if (rawResultCount > 0 && !iterableContainsGraphObject) {
                        GraphObjectMap gObject = new GraphObjectMap();
                        gObject.setProperty(new ArrayProperty(this.typeResource.rawType, Object.class), propertyResults.toArray());
                        Result r = new Result(gObject, true);
                        r.setRawResultCount(rawResultCount);
                        return r;
                    }
                    final List<GraphObject> finalResult = new LinkedList<>();
                    propertyResults.forEach(v -> finalResult.add((GraphObject) v));
                    applyDefaultSorting(finalResult, sortKey, sortDescending);
                    // return result
                    Result r = new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
                    r.setRawResultCount(rawResultCount);
                    return r;
                } else if (value instanceof GraphObject) {
                    return new Result((GraphObject) value, isPrimitiveArray());
                } else {
                    GraphObjectMap gObject = new GraphObjectMap();
                    PropertyKey key;
                    String keyName = this.typeResource.rawType;
                    int resultCount = 1;
                    // FIXME: Dynamically resolve all property types and their result count
                    if (value instanceof String) {
                        key = new StringProperty(keyName);
                    } else if (value instanceof Integer) {
                        key = new IntProperty(keyName);
                    } else if (value instanceof Long) {
                        key = new LongProperty(keyName);
                    } else if (value instanceof Double) {
                        key = new DoubleProperty(keyName);
                    } else if (value instanceof Boolean) {
                        key = new BooleanProperty(keyName);
                    } else if (value instanceof Date) {
                        key = new DateProperty(keyName);
                    } else if (value instanceof String[]) {
                        key = new ArrayProperty(keyName, String.class);
                        resultCount = ((String[]) value).length;
                    } else {
                        key = new GenericProperty(keyName);
                    }
                    gObject.setProperty(key, value);
                    Result r = new Result(gObject, true);
                    r.setRawResultCount(resultCount);
                    return r;
                }
            }
            // check propertyKey to return the right variant of empty result
            if (!(propertyKey instanceof StartNode || propertyKey instanceof EndNode)) {
                return new Result(Collections.EMPTY_LIST, 1, false, true);
            }
        }
    }
    return new Result(Collections.EMPTY_LIST, 0, false, true);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) Query(org.structr.core.app.Query) DateProperty(org.structr.core.property.DateProperty) StartNode(org.structr.core.property.StartNode) EndNode(org.structr.core.property.EndNode) Node(org.structr.api.graph.Node) AbstractNode(org.structr.core.entity.AbstractNode) NotFoundException(org.structr.rest.exception.NotFoundException) StringProperty(org.structr.core.property.StringProperty) GraphObject(org.structr.core.GraphObject) Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult) Relation(org.structr.core.entity.Relation) NodeInterface(org.structr.core.graph.NodeInterface) StartNode(org.structr.core.property.StartNode) ArrayProperty(org.structr.core.property.ArrayProperty) BooleanProperty(org.structr.core.property.BooleanProperty) OtherNodeTypeRelationFilter(org.structr.core.entity.OtherNodeTypeRelationFilter) LinkedList(java.util.LinkedList) Date(java.util.Date) IntProperty(org.structr.core.property.IntProperty) EndNode(org.structr.core.property.EndNode) GraphObjectMap(org.structr.core.GraphObjectMap) LongProperty(org.structr.core.property.LongProperty) GenericProperty(org.structr.core.property.GenericProperty) GraphObject(org.structr.core.GraphObject) DoubleProperty(org.structr.core.property.DoubleProperty) PropertyKey(org.structr.core.property.PropertyKey)

Example 47 with GraphObjectMap

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

the class LogResource method histogram.

private Result histogram(final LogState state) throws FrameworkException {
    // sort entries before creating the histogram
    state.sortEntries();
    final String dateFormat = state.aggregate();
    final long startTimestamp = state.beginTimestamp();
    final long endTimestamp = state.endTimestamp();
    final GraphObjectMap result = new GraphObjectMap();
    final long interval = findInterval(dateFormat);
    final long start = alignDateOnFormat(dateFormat, startTimestamp);
    final TreeMap<Long, Map<String, Object>> countMap = toHistogramCountMap(state);
    final Set<String> countProperties = getCountProperties(countMap);
    for (long current = start; current <= endTimestamp; current += interval) {
        final Map<Long, Map<String, Object>> counts = countMap.subMap(current, true, current + interval, false);
        final GraphObjectMap sum = new GraphObjectMap();
        // whether there are actual values or not)
        for (final String key : countProperties) {
            sum.put(new IntProperty(key), 0);
        }
        // evaluate counts
        for (final Map<String, Object> count : counts.values()) {
            for (final String key : countProperties) {
                final IntProperty prop = new IntProperty(key);
                Integer sumValue = sum.get(prop);
                if (sumValue == null) {
                    sumValue = 0;
                }
                Integer entryValue = (Integer) count.get(key);
                if (entryValue == null) {
                    entryValue = 0;
                }
                sum.put(prop, sumValue + entryValue);
            }
        }
        result.put(new GenericProperty(Long.toString(current)), sum);
    }
    return new Result(result, false);
}
Also used : Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult) IntProperty(org.structr.core.property.IntProperty) GraphObjectMap(org.structr.core.GraphObjectMap) GenericProperty(org.structr.core.property.GenericProperty) GraphObject(org.structr.core.GraphObject) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PropertyMap(org.structr.core.property.PropertyMap) TreeMap(java.util.TreeMap)

Example 48 with GraphObjectMap

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

the class LogResource method aggregate.

private Result aggregate(final LogState state) throws FrameworkException {
    // sort entries before aggregation
    state.sortEntries();
    final long startTimestamp = state.beginTimestamp();
    final long endTimestamp = state.endTimestamp();
    final GraphObjectMap result = new GraphObjectMap();
    final long interval = findInterval(state.aggregate());
    final long start = alignDateOnFormat(state.aggregate(), startTimestamp);
    final TreeMap<Long, Map<String, Object>> countMap = toAggregatedCountMap(state);
    final Set<String> countProperties = getCountProperties(countMap);
    for (long current = start; current <= endTimestamp; current += interval) {
        final Map<Long, Map<String, Object>> counts = countMap.subMap(current, true, current + interval, false);
        final GraphObjectMap sum = new GraphObjectMap();
        // whether there are actual values or not)
        for (final String key : countProperties) {
            sum.put(new IntProperty(key), 0);
        }
        // evaluate counts
        for (final Map<String, Object> count : counts.values()) {
            for (final String key : countProperties) {
                final IntProperty prop = new IntProperty(key);
                Integer sumValue = sum.get(prop);
                if (sumValue == null) {
                    sumValue = 0;
                }
                Integer entryValue = (Integer) count.get(key);
                if (entryValue == null) {
                    entryValue = 0;
                }
                sum.put(prop, sumValue + entryValue);
            }
        }
        result.put(new GenericProperty(Long.toString(current)), sum);
    }
    return new Result(result, false);
}
Also used : Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult) IntProperty(org.structr.core.property.IntProperty) GraphObjectMap(org.structr.core.GraphObjectMap) GenericProperty(org.structr.core.property.GenericProperty) GraphObject(org.structr.core.GraphObject) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PropertyMap(org.structr.core.property.PropertyMap) TreeMap(java.util.TreeMap)

Example 49 with GraphObjectMap

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

the class EnumInfoFunction method apply.

@Override
public Object apply(ActionContext ctx, Object caller, Object[] sources) throws FrameworkException {
    try {
        if (arrayHasMinLengthAndMaxLengthAndAllElementsNotNull(sources, 2, 3)) {
            final ConfigurationProvider config = StructrApp.getConfiguration();
            final String typeName = sources[0].toString();
            final String enumPropertyName = sources[1].toString();
            final boolean rawList = (sources.length == 3) ? Boolean.parseBoolean(sources[2].toString()) : false;
            final Class type = SchemaHelper.getEntityClassForRawType(typeName);
            if (type != null) {
                final PropertyKey key = StructrApp.key(type, enumPropertyName);
                if (key != null) {
                    if (key instanceof EnumProperty) {
                        final String formatString = SchemaHelper.getPropertyInfo(ctx.getSecurityContext(), key).get("format").toString();
                        final List<String> valueList = Arrays.asList(formatString.replace(" ", "").split(","));
                        if (rawList) {
                            return valueList;
                        } else {
                            final ArrayList<GraphObjectMap> resultList = new ArrayList();
                            for (final String value : valueList) {
                                final GraphObjectMap valueMap = new GraphObjectMap();
                                resultList.add(valueMap);
                                valueMap.put(new StringProperty("value"), value);
                            }
                            return resultList;
                        }
                    } else {
                        logger.warn("Error: Not an Enum property \"{}.{}\"", typeName, enumPropertyName);
                        return "Not an Enum property " + typeName + "." + enumPropertyName;
                    }
                } else {
                    logger.warn("Error: Unknown property \"{}.{}\"", typeName, enumPropertyName);
                    return "Unknown property " + typeName + "." + enumPropertyName;
                }
            } else {
                logger.warn("Error: Unknown type \"{}\"", typeName);
                return "Unknown type " + typeName;
            }
        } else {
            logParameterError(caller, sources, ctx.isJavaScriptContext());
            return usage(ctx.isJavaScriptContext());
        }
    } catch (final IllegalArgumentException e) {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Also used : EnumProperty(org.structr.core.property.EnumProperty) ConfigurationProvider(org.structr.schema.ConfigurationProvider) GraphObjectMap(org.structr.core.GraphObjectMap) ArrayList(java.util.ArrayList) StringProperty(org.structr.core.property.StringProperty) PropertyKey(org.structr.core.property.PropertyKey)

Example 50 with GraphObjectMap

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

the class CreateFunction method apply.

@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
    if (sources != null && sources.length > 0) {
        final SecurityContext securityContext = ctx.getSecurityContext();
        final ConfigurationProvider config = StructrApp.getConfiguration();
        PropertyMap propertyMap;
        Class type = null;
        if (sources.length >= 1 && sources[0] != null) {
            type = config.getNodeEntityClass(sources[0].toString());
        }
        if (type == null) {
            throw new FrameworkException(422, "Unknown type '" + sources[0].toString() + "' in create() method!");
        }
        // extension for native javascript objects
        if (sources.length == 2 && sources[1] instanceof Map) {
            propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]);
        } else if (sources.length == 2 && sources[1] instanceof GraphObjectMap) {
            propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, ((GraphObjectMap) sources[1]).toMap());
        } else {
            propertyMap = new PropertyMap();
            final int parameter_count = sources.length;
            if (parameter_count % 2 == 0) {
                throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + (ctx.isJavaScriptContext() ? ERROR_MESSAGE_CREATE_JS : ERROR_MESSAGE_CREATE));
            }
            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);
                    }
                    propertyMap.put(key, value);
                }
            }
        }
        return StructrApp.getInstance(securityContext).create(type, propertyMap);
    } else {
        logParameterError(caller, sources, ctx.isJavaScriptContext());
        return usage(ctx.isJavaScriptContext());
    }
}
Also used : PropertyMap(org.structr.core.property.PropertyMap) FrameworkException(org.structr.common.error.FrameworkException) ConfigurationProvider(org.structr.schema.ConfigurationProvider) GraphObjectMap(org.structr.core.GraphObjectMap) SecurityContext(org.structr.common.SecurityContext) PropertyConverter(org.structr.core.converter.PropertyConverter) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap) PropertyKey(org.structr.core.property.PropertyKey)

Aggregations

GraphObjectMap (org.structr.core.GraphObjectMap)60 LinkedList (java.util.LinkedList)27 GraphObject (org.structr.core.GraphObject)24 Map (java.util.Map)18 FrameworkException (org.structr.common.error.FrameworkException)16 StringProperty (org.structr.core.property.StringProperty)15 GenericProperty (org.structr.core.property.GenericProperty)13 PropertyKey (org.structr.core.property.PropertyKey)12 List (java.util.List)11 Result (org.structr.core.Result)10 SecurityContext (org.structr.common.SecurityContext)8 IntProperty (org.structr.core.property.IntProperty)8 RestMethodResult (org.structr.rest.RestMethodResult)8 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)6 Test (org.junit.Test)6 ConfigurationProvider (org.structr.schema.ConfigurationProvider)6 HashMap (java.util.HashMap)5 LinkedHashSet (java.util.LinkedHashSet)5 Tx (org.structr.core.graph.Tx)5