Search in sources :

Example 6 with IllegalPathException

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

the class SchemaMethodResource method findMethodSource.

public static String findMethodSource(final Class type, final String methodName) throws IllegalPathException {
    try {
        final App app = StructrApp.getInstance();
        final String typeName = type.getSimpleName();
        Class currentType = type;
        // first step: schema node or one of its parents
        SchemaNode schemaNode = app.nodeQuery(SchemaNode.class).andName(typeName).getFirst();
        while (schemaNode != null) {
            for (final SchemaMethod method : schemaNode.getProperty(SchemaNode.schemaMethods)) {
                if (methodName.equals(method.getName()) && !method.isJava()) {
                    return method.getProperty(SchemaMethod.source);
                }
            }
            currentType = currentType.getSuperclass();
            if (currentType != null) {
                // skip non-dynamic types
                if (currentType.getSimpleName().equals(typeName) || !currentType.getName().startsWith("org.structr.dynamic.")) {
                    currentType = currentType.getSuperclass();
                }
                if (currentType != null && currentType.getName().startsWith("org.structr.dynamic.")) {
                    schemaNode = app.nodeQuery(SchemaNode.class).andName(currentType.getSimpleName()).getFirst();
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    } catch (FrameworkException fex) {
    }
    throw new IllegalPathException("Type and method name do not match the given path.");
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) SchemaNode(org.structr.core.entity.SchemaNode) IllegalPathException(org.structr.rest.exception.IllegalPathException) SchemaMethod(org.structr.core.entity.SchemaMethod) FrameworkException(org.structr.common.error.FrameworkException)

Example 7 with IllegalPathException

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

the class StaticRelationshipResource method doPost.

@Override
public RestMethodResult doPost(final Map<String, Object> propertySet) throws FrameworkException {
    final GraphObject sourceNode = typedIdResource.getEntity();
    RestMethodResult result = null;
    if (sourceNode != null && propertyKey != null && propertyKey instanceof RelationProperty) {
        final RelationProperty relationProperty = (RelationProperty) propertyKey;
        final Class sourceNodeType = sourceNode.getClass();
        NodeInterface newNode = null;
        if (propertyKey.isReadOnly()) {
            logger.info("Read-only property on {}: {}", new Object[] { sourceNodeType, typeResource.getRawType() });
            return null;
        }
        // fetch notion
        final Notion notion = relationProperty.getNotion();
        final PropertyKey primaryPropertyKey = notion.getPrimaryPropertyKey();
        // apply notion if the property set contains the ID property as the only element
        if (primaryPropertyKey != null && propertySet.containsKey(primaryPropertyKey.jsonName()) && propertySet.size() == 1) {
        // FIXME: what happens here?
        } else {
            // the notion can not deserialize objects with a single key, or the POSTed propertySet did not contain a key to deserialize,
            // so we create a new node from the POSTed properties and link the source node to it. (this is the "old" implementation)
            newNode = typeResource.createNode(propertySet);
            if (newNode != null) {
                relationProperty.addSingleElement(securityContext, sourceNode, newNode);
            }
        }
        if (newNode != null) {
            result = new RestMethodResult(HttpServletResponse.SC_CREATED);
            result.addHeader("Location", buildLocationHeader(newNode));
            return result;
        }
    } else {
        final Class entityType = typedIdResource.getTypeResource().getEntityClass();
        final String methodName = typeResource.getRawType();
        try {
            final String source = SchemaMethodResource.findMethodSource(entityType, methodName);
            result = SchemaMethodResource.invoke(securityContext, typedIdResource.getEntity(), source, propertySet, methodName);
        } catch (IllegalPathException ex) {
            // try direct invocation of the schema method on the node type
            try {
                result = SchemaMethodResource.wrapInResult(typedIdResource.getEntity().invokeMethod(methodName, propertySet, true));
            } catch (Throwable t) {
                logger.warn("Unable to execute {}.{}: {}", entityType.getSimpleName(), methodName, t.getMessage());
            }
        }
    }
    if (result == null) {
        throw new IllegalPathException("Illegal path");
    } else {
        return result;
    }
}
Also used : IllegalPathException(org.structr.rest.exception.IllegalPathException) RelationProperty(org.structr.core.property.RelationProperty) Notion(org.structr.core.notion.Notion) GraphObject(org.structr.core.GraphObject) RestMethodResult(org.structr.rest.RestMethodResult) NodeInterface(org.structr.core.graph.NodeInterface) PropertyKey(org.structr.core.property.PropertyKey)

Example 8 with IllegalPathException

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

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

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