Search in sources :

Example 16 with RestMethodResult

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

the class JsonRestServlet method doPut.

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="PUT">
@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    final SecurityContext securityContext;
    final Authenticator authenticator;
    final Resource resource;
    RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
    try {
        assertInitialized();
        // first thing to do!
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // get reader before initalizing security context
        final String input = IOUtils.toString(request.getReader());
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }
        final App app = StructrApp.getInstance(securityContext);
        final IJsonInput jsonInput = cleanAndParseJsonString(app, input);
        if (securityContext != null) {
            // isolate resource authentication
            try (final Tx tx = app.tx()) {
                // evaluate constraint chain
                resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
                authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
                tx.success();
            }
            // isolate doPut
            boolean retry = true;
            while (retry) {
                try (final Tx tx = app.tx()) {
                    result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0)));
                    tx.success();
                    retry = false;
                } catch (RetryException ddex) {
                    retry = true;
                }
            }
            // isolate write output
            try (final Tx tx = app.tx()) {
                result.commitResponse(gson.get(), response);
                tx.success();
            }
        } else {
            // isolate write output
            try (final Tx tx = app.tx()) {
                result = new RestMethodResult(HttpServletResponse.SC_FORBIDDEN);
                result.commitResponse(gson.get(), response);
                tx.success();
            }
        }
    } catch (FrameworkException frameworkException) {
        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        gson.get().toJson(frameworkException, response.getWriter());
        response.getWriter().println();
    } catch (JsonSyntaxException jsex) {
        logger.warn("PUT: Invalid JSON syntax", jsex.getMessage());
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {
        logger.warn("PUT: Unable to parse JSON string", jpex.getMessage());
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jpex.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in PUT", t);
        logger.warn("", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + t.getMessage()));
    } finally {
        try {
            // response.getWriter().flush();
            response.getWriter().close();
        } catch (Throwable t) {
            logger.warn("Unable to flush and close response: {}", t.getMessage());
        }
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Resource(org.structr.rest.resource.Resource) StaticRelationshipResource(org.structr.rest.resource.StaticRelationshipResource) RetryException(org.structr.api.RetryException) JsonParseException(com.google.gson.JsonParseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) SecurityContext(org.structr.common.SecurityContext) IJsonInput(org.structr.core.IJsonInput) Authenticator(org.structr.core.auth.Authenticator) RestMethodResult(org.structr.rest.RestMethodResult)

Example 17 with RestMethodResult

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

the class JsonRestServlet method doOptions.

// <editor-fold defaultstate="collapsed" desc="OPTIONS">
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final SecurityContext securityContext;
    final Authenticator authenticator;
    final Resource resource;
    RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST);
    try {
        assertInitialized();
        // first thing to do!
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }
        final App app = StructrApp.getInstance(securityContext);
        // isolate resource authentication
        try (final Tx tx = app.tx()) {
            resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
            authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
            tx.success();
        }
        // isolate doOptions
        boolean retry = true;
        while (retry) {
            try (final Tx tx = app.tx()) {
                result = resource.doOptions();
                tx.success();
                retry = false;
            } catch (RetryException ddex) {
                retry = true;
            }
        }
        // isolate write output
        try (final Tx tx = app.tx()) {
            result.commitResponse(gson.get(), response);
            tx.success();
        }
    } catch (FrameworkException frameworkException) {
        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        gson.get().toJson(frameworkException, response.getWriter());
        response.getWriter().println();
    } catch (JsonSyntaxException jsex) {
        logger.warn("JsonSyntaxException in OPTIONS", jsex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {
        logger.warn("JsonParseException in OPTIONS", jpex);
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jpex.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in OPTIONS", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + t.getMessage()));
    } finally {
        try {
            // response.getWriter().flush();
            response.getWriter().close();
        } catch (Throwable t) {
            logger.warn("Unable to flush and close response: {}", t.getMessage());
        }
    }
}
Also used : App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) JsonSyntaxException(com.google.gson.JsonSyntaxException) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) SecurityContext(org.structr.common.SecurityContext) Resource(org.structr.rest.resource.Resource) StaticRelationshipResource(org.structr.rest.resource.StaticRelationshipResource) RetryException(org.structr.api.RetryException) JsonParseException(com.google.gson.JsonParseException) Authenticator(org.structr.core.auth.Authenticator) RestMethodResult(org.structr.rest.RestMethodResult)

Example 18 with RestMethodResult

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

the class SchemaMethodResource method wrapInResult.

public static RestMethodResult wrapInResult(final Object obj) {
    RestMethodResult result = null;
    if (obj instanceof RestMethodResult) {
        result = (RestMethodResult) obj;
    } else {
        result = new RestMethodResult(200);
        // unwrap nested object(s)
        SchemaMethodResource.unwrapTo(obj, result);
    }
    return result;
}
Also used : RestMethodResult(org.structr.rest.RestMethodResult)

Example 19 with RestMethodResult

use of org.structr.rest.RestMethodResult 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 20 with RestMethodResult

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

the class StaticRelationshipResource method doPut.

@Override
public RestMethodResult doPut(final Map<String, Object> propertySet) throws FrameworkException {
    final List<? extends GraphObject> results = typedIdResource.doGet(null, false, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults();
    final App app = StructrApp.getInstance(securityContext);
    if (results != null) {
        // fetch static relationship definition
        if (propertyKey != null && propertyKey instanceof RelationProperty) {
            final GraphObject sourceEntity = typedIdResource.getEntity();
            if (sourceEntity != null) {
                if (propertyKey.isReadOnly()) {
                    logger.info("Read-only property on {}: {}", new Object[] { sourceEntity.getClass(), typeResource.getRawType() });
                    return new RestMethodResult(HttpServletResponse.SC_FORBIDDEN);
                }
                final List<GraphObject> nodes = new LinkedList<>();
                // Now add new relationships for any new id: This should be the rest of the property set
                for (final Object obj : propertySet.values()) {
                    nodes.add(app.getNodeById(obj.toString()));
                }
                // set property on source node
                sourceEntity.setProperty(propertyKey, nodes);
            }
        }
    }
    return new RestMethodResult(HttpServletResponse.SC_OK);
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) RelationProperty(org.structr.core.property.RelationProperty) GraphObject(org.structr.core.GraphObject) GraphObject(org.structr.core.GraphObject) RestMethodResult(org.structr.rest.RestMethodResult) LinkedList(java.util.LinkedList)

Aggregations

RestMethodResult (org.structr.rest.RestMethodResult)27 App (org.structr.core.app.App)13 StructrApp (org.structr.core.app.StructrApp)13 Tx (org.structr.core.graph.Tx)10 FrameworkException (org.structr.common.error.FrameworkException)9 GraphObject (org.structr.core.GraphObject)7 SecurityContext (org.structr.common.SecurityContext)6 Authenticator (org.structr.core.auth.Authenticator)6 Resource (org.structr.rest.resource.Resource)6 JsonParseException (com.google.gson.JsonParseException)5 JsonSyntaxException (com.google.gson.JsonSyntaxException)5 RetryException (org.structr.api.RetryException)5 IllegalPathException (org.structr.rest.exception.IllegalPathException)5 PropertyMap (org.structr.core.property.PropertyMap)4 NotFoundException (org.structr.rest.exception.NotFoundException)4 StaticRelationshipResource (org.structr.rest.resource.StaticRelationshipResource)4 HashMap (java.util.HashMap)3 LinkedList (java.util.LinkedList)3 Principal (org.structr.core.entity.Principal)3 LinkedHashMap (java.util.LinkedHashMap)2