Search in sources :

Example 1 with ResourceProvider

use of org.structr.rest.ResourceProvider 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 2 with ResourceProvider

use of org.structr.rest.ResourceProvider in project structr by structr.

the class JsonRestServlet method init.

@Override
public void init() {
    // inject resources
    final ResourceProvider provider = config.getResourceProvider();
    if (provider != null) {
        resourceMap.putAll(provider.getResources());
    } else {
        logger.error("Unable to initialize JsonRestServlet, no resource provider found. Please check structr.conf for a valid resource provider class");
    }
    // initialize variables
    this.propertyView = new ThreadLocalPropertyView();
    this.indentJson = Settings.JsonIndentation.getValue();
    this.gson = new ThreadLocalGson(propertyView, config.getOutputNestingDepth());
}
Also used : ResourceProvider(org.structr.rest.ResourceProvider)

Example 3 with ResourceProvider

use of org.structr.rest.ResourceProvider in project structr by structr.

the class WrappedRestCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) throws FrameworkException {
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String method = (String) nodeData.get("method");
    if (method == null || !(method.equals("POST") || method.equals("PUT"))) {
        logger.warn("Method not supported: {}", method);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Method not supported: " + method).build(), true);
        return;
    }
    ResourceProvider resourceProvider;
    try {
        resourceProvider = UiResourceProvider.class.newInstance();
    } catch (Throwable t) {
        logger.error("Couldn't establish a resource provider", t);
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Couldn't establish a resource provider").build(), true);
        return;
    }
    final Map<Pattern, Class<? extends Resource>> resourceMap = new LinkedHashMap<>();
    resourceMap.putAll(resourceProvider.getResources());
    final StructrWebSocket socket = this.getWebSocket();
    final String url = (String) nodeData.get("url");
    // mimic HTTP request
    final HttpServletRequest wrappedRequest = new HttpServletRequestWrapper(socket.getRequest()) {

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

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

        @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(url, "?");
        }

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

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(url);
        }
    };
    Resource resource;
    final StaticValue fakePropertyView = new StaticValue(PropertyView.Public);
    try {
        resource = ResourceHelper.applyViewTransformation(wrappedRequest, socket.getSecurityContext(), ResourceHelper.optimizeNestedResourceChain(socket.getSecurityContext(), wrappedRequest, resourceMap, fakePropertyView), fakePropertyView);
    } catch (IllegalPathException | NotFoundException e) {
        logger.warn("Illegal path for REST query");
        getWebSocket().send(MessageBuilder.wrappedRest().code(422).message("Illegal path for REST query").build(), true);
        return;
    }
    final String data = (String) nodeData.get("data");
    final Gson gson = new GsonBuilder().create();
    final Map<String, Object> jsonData = gson.fromJson(data, Map.class);
    RestMethodResult result = null;
    switch(method) {
        case "PUT":
            // we want to update data
            result = resource.doPut(jsonData);
            break;
        case "POST":
            // we either want to create data or call a method on an object
            result = resource.doPost(jsonData);
            break;
    }
    // right now we do not send messages
    if (result != null) {
    // getWebSocket().send(MessageBuilder.wrappedRest().code(result.getResponseCode()).message(result.jsonMessage()).build(), true);
    }
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StructrWebSocket(org.structr.websocket.StructrWebSocket) NotFoundException(org.structr.rest.exception.NotFoundException) Gson(com.google.gson.Gson) LinkedHashMap(java.util.LinkedHashMap) 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) GsonBuilder(com.google.gson.GsonBuilder) Resource(org.structr.rest.resource.Resource) StaticValue(org.structr.core.StaticValue) UiResourceProvider(org.structr.web.common.UiResourceProvider) RestMethodResult(org.structr.rest.RestMethodResult)

Aggregations

ResourceProvider (org.structr.rest.ResourceProvider)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 IllegalPathException (org.structr.rest.exception.IllegalPathException)2 NotFoundException (org.structr.rest.exception.NotFoundException)2 Resource (org.structr.rest.resource.Resource)2 UiResourceProvider (org.structr.web.common.UiResourceProvider)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 SecurityContext (org.structr.common.SecurityContext)1 GraphObject (org.structr.core.GraphObject)1 Result (org.structr.core.Result)1 StaticValue (org.structr.core.StaticValue)1 PropertyKey (org.structr.core.property.PropertyKey)1 RestMethodResult (org.structr.rest.RestMethodResult)1 StructrWebSocket (org.structr.websocket.StructrWebSocket)1