Search in sources :

Example 6 with RestMethodResult

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

the class SchemaJsonResource method doPost.

@Override
public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException {
    if (propertySet != null && propertySet.containsKey("schema")) {
        final App app = StructrApp.getInstance(securityContext);
        String schemaJson = (String) propertySet.get("schema");
        try {
            StructrSchema.replaceDatabaseSchema(app, StructrSchema.createFromSource(schemaJson));
        } catch (URISyntaxException | InvalidSchemaException ex) {
            logger.error("Error while importing JsonSchema: " + ex.getMessage());
        }
        return new RestMethodResult(200, "Schema import started");
    }
    return new RestMethodResult(400, "Invalid request body. Specify schema json string as 'schema' in request body.");
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) InvalidSchemaException(org.structr.schema.json.InvalidSchemaException) URISyntaxException(java.net.URISyntaxException) RestMethodResult(org.structr.rest.RestMethodResult)

Example 7 with RestMethodResult

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

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

the class LogResource method doPost.

@Override
public RestMethodResult doPost(Map<String, Object> propertySet) throws FrameworkException {
    final HttpServletRequest request = securityContext.getRequest();
    if (request != null) {
        // initialize?!
        if ("true".equals(request.getParameter("initialize"))) {
            final String filesPath = Settings.FilesPath.getValue();
            try (final Context context = new Context(1000)) {
                collectFilesAndStore(context, new File(filesPath + SUBJECTS).toPath(), 0);
            } catch (FrameworkException fex) {
                logger.warn("", fex);
            }
            return new RestMethodResult(200);
        }
        final String subjectId = (String) propertySet.get(subjectProperty.jsonName());
        final String objectId = (String) propertySet.get(objectProperty.jsonName());
        final String action = (String) propertySet.get(actionProperty.jsonName());
        final String message = (String) propertySet.get(messageProperty.jsonName());
        if (subjectId != null && objectId != null && action != null) {
            final App app = StructrApp.getInstance(securityContext);
            LogEvent event = null;
            try (final Tx tx = app.tx()) {
                final PropertyMap properties = new PropertyMap();
                properties.put(LogEvent.timestampProperty, new Date());
                properties.put(LogEvent.actionProperty, action);
                properties.put(LogEvent.subjectProperty, subjectId);
                properties.put(LogEvent.objectProperty, objectId);
                properties.put(LogEvent.messageProperty, message);
                properties.put(LogEvent.visibleToPublicUsers, true);
                properties.put(LogEvent.visibleToAuthenticatedUsers, true);
                event = app.create(LogEvent.class, properties);
                tx.success();
            }
            final RestMethodResult result = new RestMethodResult(201);
            result.addContent(event);
            return result;
        } else {
            final ErrorBuffer errorBuffer = new ErrorBuffer();
            if (StringUtils.isEmpty(subjectId)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", subjectProperty));
            }
            if (StringUtils.isEmpty(objectId)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", objectProperty));
            }
            if (StringUtils.isEmpty(action)) {
                errorBuffer.add(new EmptyPropertyToken("LogFile", actionProperty));
            }
            throw new FrameworkException(422, "Log entry must consist of at least subjectId, objectId and action", errorBuffer);
        }
    }
    // no request object, this is fatal
    throw new FrameworkException(500, "No request object present, aborting.");
}
Also used : SecurityContext(org.structr.common.SecurityContext) App(org.structr.core.app.App) StructrApp(org.structr.core.app.StructrApp) EmptyPropertyToken(org.structr.common.error.EmptyPropertyToken) FrameworkException(org.structr.common.error.FrameworkException) Tx(org.structr.core.graph.Tx) LogEvent(org.structr.rest.logging.entity.LogEvent) Date(java.util.Date) HttpServletRequest(javax.servlet.http.HttpServletRequest) PropertyMap(org.structr.core.property.PropertyMap) ErrorBuffer(org.structr.common.error.ErrorBuffer) File(java.io.File) RestMethodResult(org.structr.rest.RestMethodResult)

Example 9 with RestMethodResult

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

the class CsvServlet method doPost.

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    final String fieldSeparatorHeader = request.getHeader(DEFAULT_FIELD_SEPARATOR_HEADER_NAME);
    final char fieldSeparator = (fieldSeparatorHeader == null) ? DEFAULT_FIELD_SEPARATOR : fieldSeparatorHeader.charAt(0);
    final String quoteCharacterHeader = request.getHeader(DEFAULT_QUOTE_CHARACTER_HEADER_NAME);
    final char quoteCharacter = (quoteCharacterHeader == null) ? DEFAULT_QUOTE_CHARACTER : quoteCharacterHeader.charAt(0);
    final String doPeridicCommitHeader = request.getHeader(DEFAULT_PERIODIC_COMMIT_HEADER_NAME);
    final boolean doPeriodicCommit = (doPeridicCommitHeader == null) ? DEFAULT_PERIODIC_COMMIT : Boolean.parseBoolean(doPeridicCommitHeader);
    final String periodicCommitIntervalHeader = request.getHeader(DEFAULT_PERIODIC_COMMIT_INTERVAL_HEADER_NAME);
    final int periodicCommitInterval = (periodicCommitIntervalHeader == null) ? DEFAULT_PERIODIC_COMMIT_INTERVAL : Integer.parseInt(periodicCommitIntervalHeader);
    final String rangeHeader = request.getHeader(DEFAULT_RANGE_HEADER_NAME);
    final List<RestMethodResult> results = new LinkedList<>();
    final Authenticator authenticator;
    final Resource resource;
    try {
        // 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 Reader input = 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);
        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();
            }
            // do not send websocket notifications for created objects
            securityContext.setDoTransactionNotifications(false);
            securityContext.disableModificationOfAccessTime();
            securityContext.ignoreResultCount(true);
            securityContext.disableEnsureCardinality();
            final String username = securityContext.getUser(false).getName();
            final long startTime = System.currentTimeMillis();
            final Map<String, Object> data = new LinkedHashMap();
            data.put("type", "CSV_IMPORT_STATUS");
            data.put("subtype", "BEGIN");
            data.put("username", username);
            TransactionCommand.simpleBroadcastGenericMessage(data);
            // isolate doPost
            boolean retry = true;
            while (retry) {
                retry = false;
                final Iterable<JsonInput> csv = CsvHelper.cleanAndParseCSV(securityContext, input, resource.getEntityClass(), fieldSeparator, quoteCharacter, rangeHeader);
                if (resource.createPostTransaction()) {
                    if (doPeriodicCommit) {
                        final List<JsonInput> list = new ArrayList<>();
                        csv.iterator().forEachRemaining(list::add);
                        final List<List<JsonInput>> chunkedCsv = ListUtils.partition(list, periodicCommitInterval);
                        final int totalChunkNo = chunkedCsv.size();
                        int currentChunkNo = 0;
                        for (final List<JsonInput> currentChunk : chunkedCsv) {
                            try (final Tx tx = app.tx()) {
                                currentChunkNo++;
                                for (final JsonInput propertySet : currentChunk) {
                                    handleCsvPropertySet(results, resource, propertySet);
                                }
                                tx.success();
                                logger.info("CSV: Finished importing chunk " + currentChunkNo + " / " + totalChunkNo);
                                final Map<String, Object> chunkMsgData = new LinkedHashMap();
                                chunkMsgData.put("type", "CSV_IMPORT_STATUS");
                                chunkMsgData.put("subtype", "CHUNK");
                                chunkMsgData.put("currentChunkNo", currentChunkNo);
                                chunkMsgData.put("totalChunkNo", totalChunkNo);
                                chunkMsgData.put("username", username);
                                TransactionCommand.simpleBroadcastGenericMessage(chunkMsgData);
                            } catch (RetryException ddex) {
                                retry = true;
                            }
                        }
                    } else {
                        try (final Tx tx = app.tx()) {
                            for (final JsonInput propertySet : csv) {
                                handleCsvPropertySet(results, resource, propertySet);
                            }
                            tx.success();
                        } catch (RetryException ddex) {
                            retry = true;
                        }
                    }
                } else {
                    if (doPeriodicCommit) {
                        logger.warn("Resource auto-creates POST transaction - can not commit periodically!");
                    }
                    try {
                        for (final JsonInput propertySet : csv) {
                            handleCsvPropertySet(results, resource, propertySet);
                        }
                    } catch (RetryException ddex) {
                        retry = true;
                    }
                }
            }
            final long endTime = System.currentTimeMillis();
            DecimalFormat decimalFormat = new DecimalFormat("0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
            final String duration = decimalFormat.format(((endTime - startTime) / 1000.0)) + "s";
            logger.info("CSV: Finished importing CSV data (Time: {})", duration);
            final Map<String, Object> endMsgData = new LinkedHashMap();
            endMsgData.put("type", "CSV_IMPORT_STATUS");
            endMsgData.put("subtype", "END");
            endMsgData.put("duration", duration);
            endMsgData.put("username", username);
            TransactionCommand.simpleBroadcastGenericMessage(endMsgData);
            // 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) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) Reader(java.io.Reader) GraphObject(org.structr.core.GraphObject) JsonParseException(com.google.gson.JsonParseException) LinkedHashMap(java.util.LinkedHashMap) JsonInput(org.structr.core.JsonInput) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Authenticator(org.structr.core.auth.Authenticator) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Resource(org.structr.rest.resource.Resource) RetryException(org.structr.api.RetryException) LinkedList(java.util.LinkedList) JsonSyntaxException(com.google.gson.JsonSyntaxException) GraphObject(org.structr.core.GraphObject) RestMethodResult(org.structr.rest.RestMethodResult)

Example 10 with RestMethodResult

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

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