Search in sources :

Example 11 with Relation

use of org.structr.core.entity.Relation 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 Relation

use of org.structr.core.entity.Relation in project structr by structr.

the class TypeResource method doPost.

@Override
public RestMethodResult doPost(final Map<String, Object> propertySet) throws FrameworkException {
    // virtual type?
    if (virtualType != null) {
        virtualType.transformInput(securityContext, entityClass, propertySet);
    }
    if (isNode) {
        final RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_CREATED);
        final NodeInterface newNode = createNode(propertySet);
        if (newNode != null) {
            result.addHeader("Location", buildLocationHeader(newNode));
            result.addContent(newNode);
        }
        result.serializeAsPrimitiveArray(true);
        // finally: return 201 Created
        return result;
    } else {
        final App app = StructrApp.getInstance(securityContext);
        final Relation template = getRelationshipTemplate();
        final ErrorBuffer errorBuffer = new ErrorBuffer();
        if (template != null) {
            final NodeInterface sourceNode = identifyStartNode(template, propertySet);
            final NodeInterface targetNode = identifyEndNode(template, propertySet);
            final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, entityClass, propertySet);
            RelationshipInterface newRelationship = null;
            if (sourceNode == null) {
                errorBuffer.add(new EmptyPropertyToken(entityClass.getSimpleName(), template.getSourceIdProperty()));
            }
            if (targetNode == null) {
                errorBuffer.add(new EmptyPropertyToken(entityClass.getSimpleName(), template.getTargetIdProperty()));
            }
            if (errorBuffer.hasError()) {
                throw new FrameworkException(422, "Source node ID and target node ID of relationsips must be set", errorBuffer);
            }
            template.ensureCardinality(securityContext, sourceNode, targetNode);
            newRelationship = app.create(sourceNode, targetNode, entityClass, properties);
            RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_CREATED);
            if (newRelationship != null) {
                result.addHeader("Location", buildLocationHeader(newRelationship));
                result.addContent(newRelationship);
            }
            result.serializeAsPrimitiveArray(true);
            // finally: return 201 Created
            return result;
        }
        // shouldn't happen
        throw new NotFoundException("Type" + rawType + " does not exist");
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) EmptyPropertyToken(org.structr.common.error.EmptyPropertyToken) Relation(org.structr.core.entity.Relation) ErrorBuffer(org.structr.common.error.ErrorBuffer) PropertyMap(org.structr.core.property.PropertyMap) FrameworkException(org.structr.common.error.FrameworkException) RelationshipInterface(org.structr.core.graph.RelationshipInterface) NotFoundException(org.structr.rest.exception.NotFoundException) RestMethodResult(org.structr.rest.RestMethodResult) NodeInterface(org.structr.core.graph.NodeInterface)

Example 13 with Relation

use of org.structr.core.entity.Relation in project structr by structr.

the class ImageHelper method findAndReconnectOriginalImage.

public static void findAndReconnectOriginalImage(final Image thumbnail) {
    final Class<Relation> thumbnailRel = StructrApp.getConfiguration().getRelationshipEntityClass("ImageTHUMBNAILImage");
    final PropertyKey<String> pathKey = StructrApp.key(Image.class, "path");
    final String originalImageName = thumbnail.getOriginalImageName();
    try {
        final App app = StructrApp.getInstance();
        final Image originalImage = (Image) app.nodeQuery(Image.class).and(pathKey, PathHelper.getFolderPath(thumbnail.getProperty(pathKey)) + PathHelper.PATH_SEP + originalImageName).getFirst();
        if (originalImage != null) {
            final PropertyMap relProperties = new PropertyMap();
            relProperties.put(StructrApp.key(Image.class, "width"), thumbnail.getWidth());
            relProperties.put(StructrApp.key(Image.class, "height"), thumbnail.getHeight());
            relProperties.put(StructrApp.key(Image.class, "checksum"), originalImage.getChecksum());
            app.create(originalImage, thumbnail, thumbnailRel, relProperties);
        }
    } catch (FrameworkException ex) {
        logger.debug("Error reconnecting thumbnail " + thumbnail.getName() + " to original image " + originalImageName, ex);
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Relation(org.structr.core.entity.Relation) PropertyMap(org.structr.core.property.PropertyMap) FrameworkException(org.structr.common.error.FrameworkException) BufferedImage(java.awt.image.BufferedImage) Image(org.structr.web.entity.Image)

Example 14 with Relation

use of org.structr.core.entity.Relation in project structr by structr.

the class ImageHelper method findAndReconnectThumbnails.

public static void findAndReconnectThumbnails(final Image originalImage) {
    final Class<Relation> thumbnailRel = StructrApp.getConfiguration().getRelationshipEntityClass("ImageTHUMBNAILImage");
    final PropertyKey<Image> tnSmallKey = StructrApp.key(Image.class, "tnSmall");
    final PropertyKey<Image> tnMidKey = StructrApp.key(Image.class, "tnMid");
    final PropertyKey<String> pathKey = StructrApp.key(Image.class, "path");
    final App app = StructrApp.getInstance();
    final Integer origWidth = originalImage.getWidth();
    final Integer origHeight = originalImage.getHeight();
    if (origWidth == null || origHeight == null) {
        if (!Arrays.asList("image/svg+xml", "image/x-icon", "image/x-photoshop").contains(originalImage.getContentType())) {
            logger.info("Could not determine width and heigth for {}", originalImage.getName());
        }
        return;
    }
    for (ThumbnailProperty tnProp : new ThumbnailProperty[] { (ThumbnailProperty) tnSmallKey, (ThumbnailProperty) tnMidKey }) {
        int maxWidth = tnProp.getWidth();
        int maxHeight = tnProp.getHeight();
        boolean crop = tnProp.getCrop();
        final float scale = getScaleRatio(origWidth, origHeight, maxWidth, maxHeight, crop);
        final String tnName = ImageHelper.getThumbnailName(originalImage.getName(), getThumbnailWidth(origWidth, scale), getThumbnailHeight(origHeight, scale));
        try {
            final Image thumbnail = (Image) app.nodeQuery(Image.class).and(pathKey, PathHelper.getFolderPath(originalImage.getProperty(pathKey)) + PathHelper.PATH_SEP + tnName).getFirst();
            if (thumbnail != null) {
                app.create(originalImage, thumbnail, thumbnailRel);
            }
        } catch (FrameworkException ex) {
            logger.debug("Error reconnecting thumbnail " + tnName + " to original image " + originalImage.getName(), ex);
        }
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) ThumbnailProperty(org.structr.web.property.ThumbnailProperty) FrameworkException(org.structr.common.error.FrameworkException) BufferedImage(java.awt.image.BufferedImage) Image(org.structr.web.entity.Image) Relation(org.structr.core.entity.Relation)

Example 15 with Relation

use of org.structr.core.entity.Relation in project structr by structr.

the class SchemaHelper method getPropertyInfo.

public static Map<String, Object> getPropertyInfo(final SecurityContext securityContext, final PropertyKey property) {
    final Map<String, Object> map = new LinkedHashMap();
    map.put("dbName", property.dbName());
    map.put("jsonName", property.jsonName());
    map.put("className", property.getClass().getName());
    final Class declaringClass = property.getDeclaringClass();
    if (declaringClass != null) {
        map.put("declaringClass", declaringClass.getSimpleName());
    }
    map.put("defaultValue", property.defaultValue());
    if (property instanceof StringProperty) {
        map.put("contentType", ((StringProperty) property).contentType());
    }
    map.put("format", property.format());
    map.put("readOnly", property.isReadOnly());
    map.put("system", property.isSystemInternal());
    map.put("indexed", property.isIndexed());
    map.put("indexedWhenEmpty", property.isIndexedWhenEmpty());
    map.put("compound", property.isCompound());
    map.put("unique", property.isUnique());
    map.put("notNull", property.isNotNull());
    map.put("dynamic", property.isDynamic());
    map.put("hint", property.hint());
    map.put("category", property.category());
    final Class<? extends GraphObject> relatedType = property.relatedType();
    if (relatedType != null) {
        map.put("relatedType", relatedType.getName());
        map.put("type", relatedType.getSimpleName());
        map.put("uiType", relatedType.getSimpleName() + (property.isCollection() ? "[]" : ""));
    } else {
        map.put("type", property.typeName());
        map.put("uiType", property.typeName() + (property.isCollection() ? "[]" : ""));
    }
    map.put("isCollection", property.isCollection());
    final PropertyConverter databaseConverter = property.databaseConverter(securityContext, null);
    final PropertyConverter inputConverter = property.inputConverter(securityContext);
    if (databaseConverter != null) {
        map.put("databaseConverter", databaseConverter.getClass().getName());
    }
    if (inputConverter != null) {
        map.put("inputConverter", inputConverter.getClass().getName());
    }
    // if (declaringClass != null && ("org.structr.dynamic".equals(declaringClass.getPackage().getName()))) {
    if (declaringClass != null && property instanceof RelationProperty) {
        Relation relation = ((RelationProperty) property).getRelation();
        if (relation != null) {
            map.put("relationshipType", relation.name());
        }
    }
    return map;
}
Also used : Relation(org.structr.core.entity.Relation) RelationProperty(org.structr.core.property.RelationProperty) PropertyConverter(org.structr.core.converter.PropertyConverter) StringProperty(org.structr.core.property.StringProperty) GraphObject(org.structr.core.GraphObject) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

Relation (org.structr.core.entity.Relation)17 FrameworkException (org.structr.common.error.FrameworkException)7 App (org.structr.core.app.App)6 StructrApp (org.structr.core.app.StructrApp)6 PropertyMap (org.structr.core.property.PropertyMap)5 PropertyKey (org.structr.core.property.PropertyKey)4 LinkedList (java.util.LinkedList)3 GraphObject (org.structr.core.GraphObject)3 GraphObjectMap (org.structr.core.GraphObjectMap)3 RestMethodResult (org.structr.rest.RestMethodResult)3 Image (org.structr.web.entity.Image)3 BufferedImage (java.awt.image.BufferedImage)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2 SecurityContext (org.structr.common.SecurityContext)2 Result (org.structr.core.Result)2 AbstractNode (org.structr.core.entity.AbstractNode)2 NodeInterface (org.structr.core.graph.NodeInterface)2 Tx (org.structr.core.graph.Tx)2