Search in sources :

Example 11 with GenericProperty

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

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

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

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

the class AdvancedSchemaTest method test04SchemaPropertyOrderInBuiltInViews.

@Test
public void test04SchemaPropertyOrderInBuiltInViews() {
    try (final Tx tx = app.tx()) {
        createAdminUser();
        createResourceAccess("_schema", UiAuthenticator.AUTH_USER_GET);
        tx.success();
    } catch (Exception ex) {
        logger.error("", ex);
    }
    final GenericProperty jsonName = new GenericProperty("jsonName");
    SchemaNode test = null;
    String id = null;
    try (final Tx tx = app.tx()) {
        // create test type
        test = app.create(SchemaNode.class, "Test");
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
    }
    try (final Tx tx = app.tx()) {
        // create view with sort order
        final List<SchemaView> list = test.getProperty(SchemaNode.schemaViews);
        // create properties
        app.create(SchemaProperty.class, new NodeAttribute<>(SchemaProperty.schemaNode, test), new NodeAttribute<>(SchemaProperty.schemaViews, list), new NodeAttribute<>(SchemaProperty.propertyType, "String"), new NodeAttribute<>(SchemaProperty.name, "one"));
        app.create(SchemaProperty.class, new NodeAttribute<>(SchemaProperty.schemaNode, test), new NodeAttribute<>(SchemaProperty.schemaViews, list), new NodeAttribute<>(SchemaProperty.propertyType, "String"), new NodeAttribute<>(SchemaProperty.name, "two"));
        app.create(SchemaProperty.class, new NodeAttribute<>(SchemaProperty.schemaNode, test), new NodeAttribute<>(SchemaProperty.schemaViews, list), new NodeAttribute<>(SchemaProperty.propertyType, "String"), new NodeAttribute<>(SchemaProperty.name, "three"));
        app.create(SchemaProperty.class, new NodeAttribute<>(SchemaProperty.schemaNode, test), new NodeAttribute<>(SchemaProperty.schemaViews, list), new NodeAttribute<>(SchemaProperty.propertyType, "String"), new NodeAttribute<>(SchemaProperty.name, "four"));
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
    }
    final Class type = StructrApp.getConfiguration().getNodeEntityClass("Test");
    final List<PropertyKey> list = new LinkedList<>(StructrApp.getConfiguration().getPropertySet(type, "public"));
    Assert.assertEquals("Invalid number of properties in sorted view", 6, list.size());
    Assert.assertEquals("id", list.get(0).dbName());
    Assert.assertEquals("type", list.get(1).dbName());
    Assert.assertEquals("one", list.get(2).dbName());
    Assert.assertEquals("two", list.get(3).dbName());
    Assert.assertEquals("three", list.get(4).dbName());
    Assert.assertEquals("four", list.get(5).dbName());
    try (final Tx tx = app.tx()) {
        for (final SchemaView testView : test.getProperty(SchemaNode.schemaViews)) {
            // modify sort order
            testView.setProperty(SchemaView.sortOrder, "type, one, id, two, three, four, name");
        }
        // create test entity
        final NodeInterface node = app.create(StructrApp.getConfiguration().getNodeEntityClass("Test"));
        // save UUID for later
        id = node.getUuid();
        tx.success();
    } catch (FrameworkException fex) {
        fex.printStackTrace();
    }
    final List<PropertyKey> list2 = new LinkedList<>(StructrApp.getConfiguration().getPropertySet(type, "public"));
    Assert.assertEquals("Invalid number of properties in sorted view", 6, list2.size());
    Assert.assertEquals("id", list2.get(0).dbName());
    Assert.assertEquals("type", list2.get(1).dbName());
    Assert.assertEquals("one", list2.get(2).dbName());
    Assert.assertEquals("two", list2.get(3).dbName());
    Assert.assertEquals("three", list2.get(4).dbName());
    Assert.assertEquals("four", list2.get(5).dbName());
    // test schema resource
    RestAssured.given().contentType("application/json; charset=UTF-8").filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(201)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(400)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(404)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(422)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(500)).headers("X-User", ADMIN_USERNAME, "X-Password", ADMIN_PASSWORD).expect().statusCode(200).body("result", hasSize(6)).body("result[0].jsonName", equalTo("id")).body("result[1].jsonName", equalTo("type")).body("result[2].jsonName", equalTo("one")).body("result[3].jsonName", equalTo("two")).body("result[4].jsonName", equalTo("three")).body("result[5].jsonName", equalTo("four")).when().get("/_schema/Test/public");
    // test actual REST resource (not easy to extract and verify
    // JSON property order, that's why we're using replaceAll and
    // string comparison..
    final String[] actual = RestAssured.given().contentType("application/json; charset=UTF-8").filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(200)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(201)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(400)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(404)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(422)).filter(ResponseLoggingFilter.logResponseIfStatusCodeIs(500)).headers("X-User", ADMIN_USERNAME, "X-Password", ADMIN_PASSWORD).expect().statusCode(200).when().get("/Test").body().asString().replaceAll("[\\s]+", "").split("[\\W]+");
    // we can only test the actual ORDER of the JSON result object by splitting it on whitespace and validating the resulting array
    assertEquals("Invalid JSON result for sorted property view", "", actual[0]);
    assertEquals("Invalid JSON result for sorted property view", "query_time", actual[1]);
    assertEquals("Invalid JSON result for sorted property view", "0", actual[2]);
    assertEquals("Invalid JSON result for sorted property view", "result_count", actual[4]);
    assertEquals("Invalid JSON result for sorted property view", "1", actual[5]);
    assertEquals("Invalid JSON result for sorted property view", "result", actual[6]);
    assertEquals("Invalid JSON result for sorted property view", "id", actual[7]);
    assertEquals("Invalid JSON result for sorted property view", id, actual[8]);
    assertEquals("Invalid JSON result for sorted property view", "type", actual[9]);
    assertEquals("Invalid JSON result for sorted property view", "Test", actual[10]);
    assertEquals("Invalid JSON result for sorted property view", "one", actual[11]);
    assertEquals("Invalid JSON result for sorted property view", "null", actual[12]);
    assertEquals("Invalid JSON result for sorted property view", "two", actual[13]);
    assertEquals("Invalid JSON result for sorted property view", "null", actual[14]);
    assertEquals("Invalid JSON result for sorted property view", "three", actual[15]);
    assertEquals("Invalid JSON result for sorted property view", "null", actual[16]);
    assertEquals("Invalid JSON result for sorted property view", "four", actual[17]);
    assertEquals("Invalid JSON result for sorted property view", "null", actual[18]);
    assertEquals("Invalid JSON result for sorted property view", "serialization_time", actual[19]);
    // try built-in function
    try {
        final List<GraphObjectMap> list3 = (List) new TypeInfoFunction().apply(new ActionContext(securityContext), null, new Object[] { "Test", "public" });
        Assert.assertEquals("Invalid number of properties in sorted view", 6, list3.size());
        Assert.assertEquals("id", list3.get(0).get(jsonName));
        Assert.assertEquals("type", list3.get(1).get(jsonName));
        Assert.assertEquals("one", list3.get(2).get(jsonName));
        Assert.assertEquals("two", list3.get(3).get(jsonName));
        Assert.assertEquals("three", list3.get(4).get(jsonName));
        Assert.assertEquals("four", list3.get(5).get(jsonName));
    } catch (FrameworkException fex) {
        fex.printStackTrace();
    }
    // try scripting call
    try {
        final List<GraphObjectMap> list4 = (List) Scripting.evaluate(new ActionContext(securityContext), null, "${type_info('Test', 'public')}", "test");
        Assert.assertEquals("Invalid number of properties in sorted view", 6, list4.size());
        Assert.assertEquals("id", list4.get(0).get(jsonName));
        Assert.assertEquals("type", list4.get(1).get(jsonName));
        Assert.assertEquals("one", list4.get(2).get(jsonName));
        Assert.assertEquals("two", list4.get(3).get(jsonName));
        Assert.assertEquals("three", list4.get(4).get(jsonName));
        Assert.assertEquals("four", list4.get(5).get(jsonName));
    } catch (FrameworkException fex) {
        fex.printStackTrace();
    }
}
Also used : Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) ActionContext(org.structr.schema.action.ActionContext) FrameworkException(org.structr.common.error.FrameworkException) LinkedList(java.util.LinkedList) SchemaView(org.structr.core.entity.SchemaView) SchemaNode(org.structr.core.entity.SchemaNode) TypeInfoFunction(org.structr.core.function.TypeInfoFunction) GraphObjectMap(org.structr.core.GraphObjectMap) GenericProperty(org.structr.core.property.GenericProperty) LinkedList(java.util.LinkedList) List(java.util.List) PropertyKey(org.structr.core.property.PropertyKey) NodeInterface(org.structr.core.graph.NodeInterface) FrontendTest(org.structr.web.basic.FrontendTest) ResourceAccessTest(org.structr.web.basic.ResourceAccessTest) Test(org.junit.Test)

Example 15 with GenericProperty

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

the class SchemaHelper method getSchemaTypeInfo.

// ----- public static methods -----
public static List<GraphObjectMap> getSchemaTypeInfo(final SecurityContext securityContext, final String rawType, final Class type, final String propertyView) throws FrameworkException {
    List<GraphObjectMap> resultList = new LinkedList<>();
    if (type != null) {
        if (propertyView != null) {
            for (final Map.Entry<String, Object> entry : getPropertiesForView(securityContext, type, propertyView).entrySet()) {
                final GraphObjectMap property = new GraphObjectMap();
                for (final Map.Entry<String, Object> prop : ((Map<String, Object>) entry.getValue()).entrySet()) {
                    property.setProperty(new GenericProperty(prop.getKey()), prop.getValue());
                }
                resultList.add(property);
            }
        } else {
            final GraphObjectMap schema = new GraphObjectMap();
            resultList.add(schema);
            String url = "/".concat(rawType);
            schema.setProperty(new StringProperty("url"), url);
            schema.setProperty(new StringProperty("type"), type.getSimpleName());
            schema.setProperty(new StringProperty("className"), type.getName());
            schema.setProperty(new StringProperty("extendsClass"), type.getSuperclass().getName());
            schema.setProperty(new BooleanProperty("isRel"), AbstractRelationship.class.isAssignableFrom(type));
            schema.setProperty(new LongProperty("flags"), SecurityContext.getResourceFlags(rawType));
            Set<String> propertyViews = new LinkedHashSet<>(StructrApp.getConfiguration().getPropertyViewsForType(type));
            // list property sets for all views
            Map<String, Map<String, Object>> views = new TreeMap();
            schema.setProperty(new GenericProperty("views"), views);
            for (final String view : propertyViews) {
                if (!View.INTERNAL_GRAPH_VIEW.equals(view)) {
                    views.put(view, getPropertiesForView(securityContext, type, view));
                }
            }
        }
    }
    return resultList;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BooleanProperty(org.structr.core.property.BooleanProperty) AbstractRelationship(org.structr.core.entity.AbstractRelationship) StringProperty(org.structr.core.property.StringProperty) TreeMap(java.util.TreeMap) LinkedList(java.util.LinkedList) GraphObjectMap(org.structr.core.GraphObjectMap) LongProperty(org.structr.core.property.LongProperty) GenericProperty(org.structr.core.property.GenericProperty) GraphObject(org.structr.core.GraphObject) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Aggregations

GenericProperty (org.structr.core.property.GenericProperty)16 GraphObjectMap (org.structr.core.GraphObjectMap)12 LinkedList (java.util.LinkedList)9 GraphObject (org.structr.core.GraphObject)8 PropertyKey (org.structr.core.property.PropertyKey)7 List (java.util.List)5 Map (java.util.Map)5 HashMap (java.util.HashMap)4 FrameworkException (org.structr.common.error.FrameworkException)4 Result (org.structr.core.Result)4 NodeInterface (org.structr.core.graph.NodeInterface)4 Tx (org.structr.core.graph.Tx)4 RestMethodResult (org.structr.rest.RestMethodResult)4 LinkedHashMap (java.util.LinkedHashMap)3 LinkedHashSet (java.util.LinkedHashSet)3 TreeMap (java.util.TreeMap)3 Test (org.junit.Test)3 SchemaNode (org.structr.core.entity.SchemaNode)3 SchemaView (org.structr.core.entity.SchemaView)3 TypeInfoFunction (org.structr.core.function.TypeInfoFunction)3