Search in sources :

Example 1 with IJsonInput

use of org.structr.core.IJsonInput in project structr by structr.

the class JsonRestServlet method doPost.

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="POST">
@Override
protected void doPost(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final List<RestMethodResult> results = new LinkedList<>();
    final SecurityContext securityContext;
    final Authenticator authenticator;
    final Resource resource;
    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()) {
                resource = ResourceHelper.applyViewTransformation(request, securityContext, ResourceHelper.optimizeNestedResourceChain(securityContext, request, resourceMap, propertyView), propertyView);
                authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext));
                tx.success();
            }
            // isolate doPost
            boolean retry = true;
            while (retry) {
                if (resource.createPostTransaction()) {
                    try (final Tx tx = app.tx()) {
                        for (JsonInput propertySet : jsonInput.getJsonInputs()) {
                            results.add(resource.doPost(convertPropertySetToMap(propertySet)));
                        }
                        tx.success();
                        retry = false;
                    } catch (RetryException ddex) {
                        retry = true;
                    }
                } else {
                    try {
                        for (JsonInput propertySet : jsonInput.getJsonInputs()) {
                            results.add(resource.doPost(convertPropertySetToMap(propertySet)));
                        }
                        retry = false;
                    } catch (RetryException ddex) {
                        retry = true;
                    }
                }
            }
            // set default value for property view
            propertyView.set(securityContext, config.getDefaultPropertyView());
            // isolate write output
            try (final Tx tx = app.tx()) {
                if (!results.isEmpty()) {
                    final RestMethodResult result = results.get(0);
                    final int resultCount = results.size();
                    if (result != null) {
                        if (resultCount > 1) {
                            for (final RestMethodResult r : results) {
                                final GraphObject objectCreated = r.getContent().get(0);
                                if (!result.getContent().contains(objectCreated)) {
                                    result.addContent(objectCreated);
                                }
                            }
                            // remove Location header if more than one object was
                            // written because it may only contain a single URL
                            result.addHeader("Location", null);
                        }
                        result.commitResponse(gson.get(), response);
                    }
                }
                tx.success();
            }
        } else {
            // isolate write output
            try (final Tx tx = app.tx()) {
                new RestMethodResult(HttpServletResponse.SC_FORBIDDEN).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("POST: Invalid JSON syntax", jsex.getMessage());
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + jsex.getMessage()));
    } catch (JsonParseException jpex) {
        logger.warn("Unable to parse JSON string", jpex.getMessage());
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonParseException in POST: " + jpex.getMessage()));
    } catch (UnsupportedOperationException uoe) {
        logger.warn("POST not supported");
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in POST", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + 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) GraphObject(org.structr.core.GraphObject) JsonParseException(com.google.gson.JsonParseException) LinkedList(java.util.LinkedList) JsonInput(org.structr.core.JsonInput) IJsonInput(org.structr.core.IJsonInput) JsonSyntaxException(com.google.gson.JsonSyntaxException) SecurityContext(org.structr.common.SecurityContext) IJsonInput(org.structr.core.IJsonInput) RestMethodResult(org.structr.rest.RestMethodResult) Authenticator(org.structr.core.auth.Authenticator)

Example 2 with IJsonInput

use of org.structr.core.IJsonInput 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 3 with IJsonInput

use of org.structr.core.IJsonInput in project structr by structr.

the class JsonRestServlet method cleanAndParseJsonString.

// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="private methods">
private IJsonInput cleanAndParseJsonString(final App app, final String input) throws FrameworkException {
    IJsonInput jsonInput = null;
    // isolate input parsing (will include read and write operations)
    try (final Tx tx = app.tx()) {
        jsonInput = gson.get().fromJson(input, IJsonInput.class);
        tx.success();
    } catch (JsonSyntaxException jsx) {
        logger.warn("", jsx);
        throw new FrameworkException(400, jsx.getMessage());
    }
    if (jsonInput == null) {
        if (StringUtils.isBlank(input)) {
            try (final Tx tx = app.tx()) {
                jsonInput = gson.get().fromJson("{}", IJsonInput.class);
                tx.success();
            }
        } else {
            // throw new JsonParseException("Invalid or empty JSON string, must at least contain {} to be valid!");
            jsonInput = new JsonSingleInput();
        }
    }
    return jsonInput;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) JsonSingleInput(org.structr.core.JsonSingleInput) IJsonInput(org.structr.core.IJsonInput)

Example 4 with IJsonInput

use of org.structr.core.IJsonInput in project structr by structr.

the class JsonInputGSONAdapter method deserialize.

@Override
public IJsonInput deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
    IJsonInput jsonInput = null;
    JsonInput wrapper = null;
    if (json.isJsonObject()) {
        jsonInput = new JsonSingleInput();
        wrapper = deserialize(json, context);
        jsonInput.add(wrapper);
    } else if (json.isJsonArray()) {
        jsonInput = new JsonSingleInput();
        JsonArray array = json.getAsJsonArray();
        for (final JsonElement elem : array) {
            wrapper = deserialize(elem, context);
            jsonInput.add(wrapper);
        }
    } else {
        // not one of the expected types => error
        throw new JsonSyntaxException("Invalid JSON, expecting object or array");
    }
    return jsonInput;
}
Also used : JsonArray(com.google.gson.JsonArray) JsonInput(org.structr.core.JsonInput) IJsonInput(org.structr.core.IJsonInput) JsonSyntaxException(com.google.gson.JsonSyntaxException) JsonSingleInput(org.structr.core.JsonSingleInput) JsonElement(com.google.gson.JsonElement) IJsonInput(org.structr.core.IJsonInput)

Aggregations

JsonSyntaxException (com.google.gson.JsonSyntaxException)4 IJsonInput (org.structr.core.IJsonInput)4 FrameworkException (org.structr.common.error.FrameworkException)3 Tx (org.structr.core.graph.Tx)3 JsonParseException (com.google.gson.JsonParseException)2 RetryException (org.structr.api.RetryException)2 SecurityContext (org.structr.common.SecurityContext)2 JsonInput (org.structr.core.JsonInput)2 JsonSingleInput (org.structr.core.JsonSingleInput)2 App (org.structr.core.app.App)2 StructrApp (org.structr.core.app.StructrApp)2 Authenticator (org.structr.core.auth.Authenticator)2 RestMethodResult (org.structr.rest.RestMethodResult)2 Resource (org.structr.rest.resource.Resource)2 StaticRelationshipResource (org.structr.rest.resource.StaticRelationshipResource)2 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 LinkedList (java.util.LinkedList)1 GraphObject (org.structr.core.GraphObject)1