Search in sources :

Example 1 with IllegalPathException

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

the class RelationshipResource method doGet.

@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
    // fetch all results, paging is applied later
    final List<? extends GraphObject> results = wrappedResource.doGet(null, false, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults();
    final App app = StructrApp.getInstance();
    if (results != null && !results.isEmpty()) {
        try {
            final List<GraphObject> resultList = new LinkedList<>();
            for (GraphObject obj : results) {
                if (obj instanceof AbstractNode) {
                    final List<? extends RelationshipInterface> relationships = Direction.INCOMING.equals(direction) ? Iterables.toList(((AbstractNode) obj).getIncomingRelationships()) : Iterables.toList(((AbstractNode) obj).getOutgoingRelationships());
                    if (relationships != null) {
                        boolean filterInternalRelationshipTypes = false;
                        if (securityContext != null && securityContext.getRequest() != null) {
                            final String filterInternal = securityContext.getRequest().getParameter(REQUEST_PARAMETER_FILTER_INTERNAL_RELATIONSHIP_TYPES);
                            if (filterInternal != null) {
                                filterInternalRelationshipTypes = "true".equals(filterInternal);
                            }
                        }
                        // the result set using the request parameter "filterInternal=true"
                        if (filterInternalRelationshipTypes) {
                            for (final RelationshipInterface rel : relationships) {
                                if (!rel.isInternal()) {
                                    resultList.add(rel);
                                }
                            }
                        } else {
                            resultList.addAll(relationships);
                        }
                    }
                }
            }
            final int rawResultCount = resultList.size();
            return new Result(PagingHelper.subList(resultList, pageSize, page), rawResultCount, true, false);
        } catch (Throwable t) {
            logger.warn("Exception while fetching relationships", t);
        }
    } else {
        logger.info("No results from parent..");
    }
    throw new IllegalPathException(getResourceSignature() + " can only be applied to a non-empty resource");
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) IllegalPathException(org.structr.rest.exception.IllegalPathException) AbstractNode(org.structr.core.entity.AbstractNode) GraphObject(org.structr.core.GraphObject) LinkedList(java.util.LinkedList) Result(org.structr.core.Result) RelationshipInterface(org.structr.core.graph.RelationshipInterface)

Example 2 with IllegalPathException

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

the class Resource method doPut.

public RestMethodResult doPut(final Map<String, Object> propertySet) throws FrameworkException {
    final Result<GraphObject> result = doGet(null, false, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE);
    final List<GraphObject> results = result.getResults();
    if (results != null && !results.isEmpty()) {
        final Class type = results.get(0).getClass();
        // instruct deserialization strategies to set properties on related nodes
        securityContext.setAttribute("setNestedProperties", true);
        PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, type, propertySet);
        for (final GraphObject obj : results) {
            if (obj.isNode() && !obj.getSyncNode().isGranted(Permission.write, securityContext)) {
                throw new FrameworkException(403, "Modification not permitted.");
            }
            obj.setProperties(securityContext, properties);
        }
        return new RestMethodResult(HttpServletResponse.SC_OK);
    }
    throw new IllegalPathException(getResourceSignature() + " can only be applied to a non-empty resource");
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) PropertyMap(org.structr.core.property.PropertyMap) FrameworkException(org.structr.common.error.FrameworkException) GraphObject(org.structr.core.GraphObject) RestMethodResult(org.structr.rest.RestMethodResult)

Example 3 with IllegalPathException

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

the class SchemaMethodResource method doPost.

@Override
public RestMethodResult doPost(final Map<String, Object> propertySet) throws FrameworkException {
    final App app = StructrApp.getInstance(securityContext);
    RestMethodResult result = null;
    if (source != null) {
        try (final Tx tx = app.tx()) {
            result = SchemaMethodResource.invoke(securityContext, null, source, propertySet, methodResource.getUriPart());
            tx.success();
        }
    }
    if (result == null) {
        throw new IllegalPathException("Type and method name do not match the given path.");
    }
    return result;
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) IllegalPathException(org.structr.rest.exception.IllegalPathException) Tx(org.structr.core.graph.Tx) RestMethodResult(org.structr.rest.RestMethodResult)

Example 4 with IllegalPathException

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

the class RestDataSource method getData.

// FIXME: this method is needed by the websocket search command because there is no reference node for the above method
public List<GraphObject> getData(final RenderContext renderContext, final String restQuery) throws FrameworkException {
    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    final SecurityContext securityContext = renderContext.getSecurityContext();
    ResourceProvider resourceProvider = renderContext.getResourceProvider();
    if (resourceProvider == null) {
        try {
            resourceProvider = UiResourceProvider.class.newInstance();
        } catch (Throwable t) {
            logger.error("Couldn't establish a resource provider", t);
            return Collections.EMPTY_LIST;
        }
    }
    // inject resources
    resourceMap.putAll(resourceProvider.getResources());
    Value<String> propertyView = new ThreadLocalPropertyView();
    propertyView.set(securityContext, PropertyView.Ui);
    HttpServletRequest request = securityContext.getRequest();
    if (request == null) {
        request = renderContext.getRequest();
    }
    // initialize variables
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(request) {

        @Override
        public Enumeration<String> getParameterNames() {
            return new IteratorEnumeration(getParameterMap().keySet().iterator());
        }

        @Override
        public String getParameter(final String key) {
            String[] p = getParameterMap().get(key);
            return p != null ? p[0] : null;
        }

        @Override
        public String[] getParameterValues(final String key) {
            return getParameterMap().get(key);
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            String[] parts = StringUtils.split(getQueryString(), "&");
            Map<String, String[]> parameterMap = new HashMap();
            for (String p : parts) {
                String[] kv = StringUtils.split(p, "=");
                if (kv.length > 1) {
                    parameterMap.put(kv[0], new String[] { kv[1] });
                }
            }
            return parameterMap;
        }

        @Override
        public String getQueryString() {
            return StringUtils.substringAfter(restQuery, "?");
        }

        @Override
        public String getPathInfo() {
            return StringUtils.substringBefore(restQuery, "?");
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(restQuery);
        }
    };
    // store original request
    final HttpServletRequest origRequest = securityContext.getRequest();
    // update request in security context
    securityContext.setRequest(wrappedRequest);
    // HttpServletResponse response = renderContext.getResponse();
    Resource resource = null;
    try {
        resource = ResourceHelper.applyViewTransformation(wrappedRequest, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, wrappedRequest, resourceMap, propertyView), propertyView);
    } catch (IllegalPathException | NotFoundException e) {
        logger.warn("Illegal path for REST query: {}", restQuery);
    }
    // reset request to old context
    securityContext.setRequest(origRequest);
    if (resource == null) {
        return Collections.EMPTY_LIST;
    }
    // experimental: disable result count, prevents instantiation
    // of large collections just for counting all the objects..
    securityContext.ignoreResultCount(true);
    // TODO: decide if we need to rest the REST request here
    // securityContext.checkResourceAccess(request, resource.getResourceSignature(), resource.getGrant(request, response), PropertyView.Ui);
    // add sorting & paging
    String pageSizeParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_SIZE);
    String pageParameter = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_PAGE_NUMBER);
    String sortOrder = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_ORDER);
    String sortKeyName = wrappedRequest.getParameter(JsonRestServlet.REQUEST_PARAMETER_SORT_KEY);
    boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase()));
    int pageSize = parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE);
    int page = parseInt(pageParameter, NodeFactory.DEFAULT_PAGE);
    PropertyKey sortKey = null;
    // set sort key
    if (sortKeyName != null) {
        Class<? extends GraphObject> type = resource.getEntityClass();
        if (type == null) {
            // fallback to default implementation
            // if no type can be determined
            type = AbstractNode.class;
        }
        sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false);
    }
    // do action
    Result result = Result.EMPTY_RESULT;
    try {
        result = resource.doGet(sortKey, sortDescending, pageSize, page);
    } catch (NotFoundException nfe) {
        logger.warn("No result from internal REST query: {}", restQuery);
    }
    result.setIsCollection(resource.isCollectionResource());
    result.setIsPrimitiveArray(resource.isPrimitiveArray());
    // Integer rawResultCount = (Integer) Services.getAttribute(NodeFactory.RAW_RESULT_COUNT + Thread.currentThread().getId());
    PagingHelper.addPagingParameter(result, pageSize, page);
    List<GraphObject> res = result.getResults();
    renderContext.setResult(result);
    return res != null ? res : Collections.EMPTY_LIST;
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) NotFoundException(org.structr.rest.exception.NotFoundException) GraphObject(org.structr.core.GraphObject) LinkedHashMap(java.util.LinkedHashMap) Result(org.structr.core.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) ResourceProvider(org.structr.rest.ResourceProvider) UiResourceProvider(org.structr.web.common.UiResourceProvider) Pattern(java.util.regex.Pattern) IteratorEnumeration(org.apache.commons.collections.iterators.IteratorEnumeration) Resource(org.structr.rest.resource.Resource) UiResourceProvider(org.structr.web.common.UiResourceProvider) SecurityContext(org.structr.common.SecurityContext) PropertyKey(org.structr.core.property.PropertyKey)

Example 5 with IllegalPathException

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

the class ResourceHelper method optimizeNestedResourceChain.

/**
 * Optimize the resource chain by trying to combine two resources to a new one
 *
 * @param securityContext
 * @param request
 * @param resourceMap
 * @param propertyView
 * @return finalResource
 * @throws FrameworkException
 */
public static Resource optimizeNestedResourceChain(final SecurityContext securityContext, final HttpServletRequest request, final Map<Pattern, Class<? extends Resource>> resourceMap, final Value<String> propertyView) throws FrameworkException {
    final List<Resource> resourceChain = ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView);
    ViewFilterResource view = null;
    int num = resourceChain.size();
    boolean found = false;
    do {
        for (Iterator<Resource> it = resourceChain.iterator(); it.hasNext(); ) {
            Resource constr = it.next();
            if (constr instanceof ViewFilterResource) {
                view = (ViewFilterResource) constr;
                it.remove();
            }
        }
        found = false;
        try {
            for (int i = 0; i < num; i++) {
                Resource firstElement = resourceChain.get(i);
                Resource secondElement = resourceChain.get(i + 1);
                Resource combinedConstraint = firstElement.tryCombineWith(secondElement);
                if (combinedConstraint != null) {
                    // remove source constraints
                    resourceChain.remove(firstElement);
                    resourceChain.remove(secondElement);
                    // add combined constraint
                    resourceChain.add(i, combinedConstraint);
                    // signal success
                    found = true;
                }
            }
        } catch (Throwable t) {
        // ignore exceptions thrown here
        }
    } while (found);
    if (resourceChain.size() == 1) {
        Resource finalResource = resourceChain.get(0);
        if (view != null) {
            finalResource = finalResource.tryCombineWith(view);
        }
        if (finalResource == null) {
            // fall back to original resource
            finalResource = resourceChain.get(0);
        }
        return finalResource;
    } else {
        logger.warn("Resource chain evaluation for path {} resulted in {} entries, returning status code 400.", new Object[] { request.getPathInfo(), resourceChain.size() });
    }
    throw new IllegalPathException("Cannot resolve URL path");
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) TransformationResource(org.structr.rest.resource.TransformationResource) ViewFilterResource(org.structr.rest.resource.ViewFilterResource) Resource(org.structr.rest.resource.Resource) ViewFilterResource(org.structr.rest.resource.ViewFilterResource)

Aggregations

IllegalPathException (org.structr.rest.exception.IllegalPathException)9 RestMethodResult (org.structr.rest.RestMethodResult)5 GraphObject (org.structr.core.GraphObject)4 App (org.structr.core.app.App)4 StructrApp (org.structr.core.app.StructrApp)4 NotFoundException (org.structr.rest.exception.NotFoundException)3 Resource (org.structr.rest.resource.Resource)3 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 Pattern (java.util.regex.Pattern)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)2 IteratorEnumeration (org.apache.commons.collections.iterators.IteratorEnumeration)2 FrameworkException (org.structr.common.error.FrameworkException)2 Result (org.structr.core.Result)2 Tx (org.structr.core.graph.Tx)2 PropertyKey (org.structr.core.property.PropertyKey)2 ResourceProvider (org.structr.rest.ResourceProvider)2 UiResourceProvider (org.structr.web.common.UiResourceProvider)2 Gson (com.google.gson.Gson)1