Search in sources :

Example 66 with Validate

use of org.folio.rest.annotations.Validate in project raml-module-builder by folio-org.

the class TenantAPI method postTenant.

@Validate
@Override
public void postTenant(TenantAttributes entity, Map<String, String> headers, Handler<AsyncResult<Response>> handlers, Context context) throws Exception {
    /**
     * http://host:port/tenant
     * Validation by rmb means the entity is either properly populated on is null
     * depending on whether this is an upgrade or a create tenant
     */
    context.runOnContext(v -> {
        String tenantId = TenantTool.calculateTenantId(headers.get(ClientGenerator.OKAPI_HEADER_TENANT));
        log.info("sending... postTenant for " + tenantId);
        try {
            boolean[] isUpdateMode = new boolean[] { false };
            // body is optional so that the TenantAttributes
            if (entity != null) {
                log.debug("upgrade from " + entity.getModuleFrom() + " to " + entity.getModuleTo());
                try {
                    if (entity.getModuleFrom() != null) {
                        isUpdateMode[0] = true;
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withPlainBadRequest(e.getMessage())));
                    return;
                }
            }
            tenantExists(context, tenantId, h -> {
                try {
                    boolean tenantExists = false;
                    if (h.succeeded()) {
                        tenantExists = h.result();
                        if (tenantExists && !isUpdateMode[0]) {
                            // tenant exists and a create tenant request was made, then this should do nothing
                            // if tenant exists then only update tenant request is acceptable
                            handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withNoContent()));
                            log.warn("Tenant already exists: " + tenantId);
                            return;
                        } else if (!tenantExists && isUpdateMode[0]) {
                            // update requested for a non-existant tenant
                            log.error("Can not update non-existant tenant " + tenantId);
                            handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withPlainBadRequest("Update tenant requested for tenant " + tenantId + ", but tenant does not exist")));
                            return;
                        } else {
                            log.info("adding/updating tenant " + tenantId);
                        }
                    } else {
                        handlers.handle(io.vertx.core.Future.failedFuture(h.cause().getMessage()));
                        log.error(h.cause().getMessage(), h.cause());
                        return;
                    }
                    InputStream tableInput = TenantAPI.class.getClassLoader().getResourceAsStream(TABLE_JSON);
                    if (tableInput == null) {
                        handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withNoContent()));
                        log.info("Could not find templates/db_scripts/schema.json , " + " RMB will not run any scripts for " + tenantId);
                        return;
                    }
                    TenantOperation op = TenantOperation.CREATE;
                    String previousVersion = null;
                    String newVersion = null;
                    if (isUpdateMode[0]) {
                        op = TenantOperation.UPDATE;
                        previousVersion = entity.getModuleFrom();
                        newVersion = entity.getModuleTo();
                    }
                    SchemaMaker sMaker = new SchemaMaker(tenantId, PostgresClient.getModuleName(), op, previousVersion, newVersion);
                    String tableInputStr = null;
                    if (tableInput != null) {
                        tableInputStr = IOUtils.toString(tableInput, "UTF8");
                        Schema schema = ObjectMapperTool.getMapper().readValue(tableInputStr, Schema.class);
                        sMaker.setSchema(schema);
                    }
                    String sqlFile = sMaker.generateDDL();
                    log.debug("GENERATED SCHEMA " + sqlFile);
                    /* connect as user in postgres-conf.json file (super user) - so that all commands will be available */
                    PostgresClient.getInstance(context.owner()).runSQLFile(sqlFile, true, reply -> {
                        try {
                            StringBuffer res = new StringBuffer();
                            if (reply.succeeded()) {
                                boolean failuresExist = false;
                                if (reply.result().size() > 0) {
                                    failuresExist = true;
                                }
                                res.append(new JsonArray(reply.result()).encodePrettily());
                                OutStream os = new OutStream();
                                if (failuresExist) {
                                    handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withPlainBadRequest(res.toString())));
                                } else {
                                    os.setData(res);
                                    handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withJsonCreated(os)));
                                }
                            } else {
                                log.error(reply.cause().getMessage(), reply.cause());
                                handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withPlainInternalServerError(reply.cause().getMessage())));
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                            handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withPlainInternalServerError(e.getMessage())));
                        }
                    });
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withPlainInternalServerError(e.getMessage())));
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            handlers.handle(io.vertx.core.Future.succeededFuture(PostTenantResponse.withPlainInternalServerError(e.getMessage())));
        }
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) InputStream(java.io.InputStream) Schema(org.folio.rest.persist.ddlgen.Schema) TenantOperation(org.folio.rest.persist.ddlgen.TenantOperation) OutStream(org.folio.rest.tools.utils.OutStream) SchemaMaker(org.folio.rest.persist.ddlgen.SchemaMaker) Validate(org.folio.rest.annotations.Validate)

Aggregations

Validate (org.folio.rest.annotations.Validate)66 FieldException (org.z3950.zing.cql.cql2pgjson.FieldException)42 CQLParseException (org.z3950.zing.cql.CQLParseException)32 List (java.util.List)27 OutStream (org.folio.rest.tools.utils.OutStream)27 Criteria (org.folio.rest.persist.Criteria.Criteria)16 Criterion (org.folio.rest.persist.Criteria.Criterion)16 PostgresClient (org.folio.rest.persist.PostgresClient)16 CQLWrapper (org.folio.rest.persist.cql.CQLWrapper)13 JsonObject (io.vertx.core.json.JsonObject)4 Map (java.util.Map)4 Response (javax.ws.rs.core.Response)4 TenantTool (org.folio.rest.tools.utils.TenantTool)4 InputStream (java.io.InputStream)3 BodyPart (javax.mail.BodyPart)3 io.vertx.core (io.vertx.core)2 AsyncResult (io.vertx.core.AsyncResult)2 Context (io.vertx.core.Context)2 Handler (io.vertx.core.Handler)2 Logger (io.vertx.core.logging.Logger)2