Search in sources :

Example 6 with NotFoundException

use of org.structr.rest.exception.NotFoundException 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 7 with NotFoundException

use of org.structr.rest.exception.NotFoundException in project structr by structr.

the class MaintenanceResource method doPost.

@Override
public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException {
    if ((securityContext != null) && isSuperUser()) {
        if (this.taskOrCommand != null) {
            try {
                final App app = StructrApp.getInstance(securityContext);
                if (Task.class.isAssignableFrom(taskOrCommand)) {
                    Task task = (Task) taskOrCommand.newInstance();
                    app.processTasks(task);
                } else if (MaintenanceCommand.class.isAssignableFrom(taskOrCommand)) {
                    MaintenanceCommand cmd = (MaintenanceCommand) StructrApp.getInstance(securityContext).command(taskOrCommand);
                    // flush caches if required
                    if (cmd.requiresFlushingOfCaches()) {
                        app.command(FlushCachesCommand.class).execute(Collections.EMPTY_MAP);
                    }
                    // create enclosing transaction if required
                    if (cmd.requiresEnclosingTransaction()) {
                        try (final Tx tx = app.tx()) {
                            cmd.execute(propertySet);
                            tx.success();
                        }
                    } else {
                        cmd.execute(propertySet);
                    }
                    final RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_OK);
                    cmd.getCustomHeaders().forEach((final String headerName, final String headerValue) -> {
                        result.addHeader(headerName, headerValue);
                    });
                    cmd.getCustomHeaders().clear();
                    return result;
                } else {
                    return new RestMethodResult(HttpServletResponse.SC_NOT_FOUND);
                }
                // return 200 OK
                return new RestMethodResult(HttpServletResponse.SC_OK);
            } catch (InstantiationException iex) {
                throw new SystemException(iex.getMessage());
            } catch (IllegalAccessException iaex) {
                throw new SystemException(iaex.getMessage());
            }
        } else {
            if (taskOrCommandName != null) {
                throw new NotFoundException("No such task or command: " + this.taskOrCommandName);
            } else {
                throw new IllegalPathException("Maintenance resource needs parameter");
            }
        }
    } else {
        throw new NotAllowedException("Use of the maintenance endpoint is restricted to admin users");
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Task(org.structr.agent.Task) IllegalPathException(org.structr.rest.exception.IllegalPathException) Tx(org.structr.core.graph.Tx) SystemException(org.structr.rest.exception.SystemException) NotAllowedException(org.structr.rest.exception.NotAllowedException) NotFoundException(org.structr.rest.exception.NotFoundException) MaintenanceCommand(org.structr.core.graph.MaintenanceCommand) RestMethodResult(org.structr.rest.RestMethodResult)

Example 8 with NotFoundException

use of org.structr.rest.exception.NotFoundException 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 9 with NotFoundException

use of org.structr.rest.exception.NotFoundException in project structr by structr.

the class TypeResource method doGet.

@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
    boolean includeDeletedAndHidden = true;
    boolean publicOnly = false;
    PropertyKey actualSortKey = sortKey;
    boolean actualSortOrder = sortDescending;
    if (rawType != null) {
        if (entityClass == null) {
            throw new NotFoundException("Type " + rawType + " does not exist");
        }
        collectSearchAttributes(query);
        // default sort key & order
        if (actualSortKey == null) {
            try {
                GraphObject templateEntity = ((GraphObject) entityClass.newInstance());
                PropertyKey sortKeyProperty = templateEntity.getDefaultSortKey();
                actualSortOrder = GraphObjectComparator.DESCENDING.equals(templateEntity.getDefaultSortOrder());
                if (sortKeyProperty != null) {
                    actualSortKey = sortKeyProperty;
                } else {
                    actualSortKey = AbstractNode.name;
                }
            } catch (Throwable t) {
                // fallback to name
                actualSortKey = AbstractNode.name;
            }
        }
        if (virtualType != null) {
            final Result untransformedResult = query.includeDeletedAndHidden(includeDeletedAndHidden).publicOnly(publicOnly).sort(actualSortKey).order(actualSortOrder).getResult();
            final Result result = virtualType.transformOutput(securityContext, entityClass, untransformedResult);
            return PagingHelper.subResult(result, pageSize, page);
        } else {
            return query.includeDeletedAndHidden(includeDeletedAndHidden).publicOnly(publicOnly).sort(actualSortKey).order(actualSortOrder).pageSize(pageSize).page(page).getResult();
        }
    } else {
        logger.warn("type was null");
    }
    List emptyList = Collections.emptyList();
    return new Result(emptyList, null, isCollectionResource(), isPrimitiveArray());
}
Also used : NotFoundException(org.structr.rest.exception.NotFoundException) List(java.util.List) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey) Result(org.structr.core.Result) RestMethodResult(org.structr.rest.RestMethodResult)

Example 10 with NotFoundException

use of org.structr.rest.exception.NotFoundException in project structr by structr.

the class UuidResource method getEntity.

public GraphObject getEntity() throws FrameworkException {
    final App app = StructrApp.getInstance(securityContext);
    GraphObject entity = app.nodeQuery().uuid(uuid).getFirst();
    if (entity == null) {
        entity = app.relationshipQuery().uuid(uuid).getFirst();
    }
    if (entity == null) {
        throw new NotFoundException("Entity with ID " + uuid + " not found");
    }
    return entity;
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) NotFoundException(org.structr.rest.exception.NotFoundException) GraphObject(org.structr.core.GraphObject)

Aggregations

NotFoundException (org.structr.rest.exception.NotFoundException)12 GraphObject (org.structr.core.GraphObject)7 RestMethodResult (org.structr.rest.RestMethodResult)7 Result (org.structr.core.Result)4 App (org.structr.core.app.App)4 StructrApp (org.structr.core.app.StructrApp)4 Pattern (java.util.regex.Pattern)3 PropertyKey (org.structr.core.property.PropertyKey)3 IllegalPathException (org.structr.rest.exception.IllegalPathException)3 NotAllowedException (org.structr.rest.exception.NotAllowedException)3 Resource (org.structr.rest.resource.Resource)3 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)2 IteratorEnumeration (org.apache.commons.collections.iterators.IteratorEnumeration)2 Relation (org.structr.core.entity.Relation)2 CypherQueryCommand (org.structr.core.graph.CypherQueryCommand)2 NodeInterface (org.structr.core.graph.NodeInterface)2 ResourceProvider (org.structr.rest.ResourceProvider)2