Search in sources :

Example 11 with OutStream

use of org.folio.rest.tools.utils.OutStream in project raml-module-builder by folio-org.

the class TenantAPI method deleteTenant.

@Validate
@Override
public void deleteTenant(Map<String, String> headers, Handler<AsyncResult<Response>> handlers, Context context) throws Exception {
    context.runOnContext(v -> {
        try {
            String tenantId = TenantTool.calculateTenantId(headers.get(ClientGenerator.OKAPI_HEADER_TENANT));
            log.info("sending... deleteTenant for " + tenantId);
            tenantExists(context, tenantId, h -> {
                boolean exists = false;
                if (h.succeeded()) {
                    exists = h.result();
                    if (!exists) {
                        handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError("Tenant does not exist: " + tenantId)));
                        log.error("Can not delete. Tenant does not exist: " + tenantId);
                        return;
                    } else {
                        log.info("Deleting tenant " + tenantId);
                    }
                } else {
                    handlers.handle(io.vertx.core.Future.failedFuture(h.cause().getMessage()));
                    log.error(h.cause().getMessage(), h.cause());
                    return;
                }
                String sqlFile = null;
                try {
                    /*              InputStream is = TenantAPI.class.getClassLoader().getResourceAsStream(DELETE_JSON);
              if(is == null){
                log.info("No delete json to use for deleting tenant " + tenantId);
                handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withNoContent()));
                return;
              }
              sqlFile = IOUtils.toString(is);*/
                    SchemaMaker sMaker = new SchemaMaker(tenantId, PostgresClient.getModuleName(), TenantOperation.DELETE, null, PomReader.INSTANCE.getRmbVersion());
                    sqlFile = sMaker.generateDDL();
                } catch (Exception e1) {
                    handlers.handle(io.vertx.core.Future.failedFuture(e1.getMessage()));
                    log.error(e1.getMessage(), e1);
                    return;
                }
                log.info("Attempting to run delete script for: " + tenantId);
                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 {
                        String res = "";
                        if (reply.succeeded()) {
                            res = new JsonArray(reply.result()).encodePrettily();
                            if (reply.result().size() > 0) {
                                log.error("Unable to run the following commands during tenant delete: ");
                                reply.result().forEach(System.out::println);
                                handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainBadRequest(res)));
                            } else {
                                OutStream os = new OutStream();
                                os.setData(res);
                                handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withNoContent()));
                            }
                        } else {
                            log.error(reply.cause().getMessage(), reply.cause());
                            handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError(reply.cause().getMessage())));
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError(e.getMessage())));
                    }
                });
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            handlers.handle(io.vertx.core.Future.succeededFuture(DeleteTenantResponse.withPlainInternalServerError(e.getMessage())));
        }
    });
}
Also used : JsonArray(io.vertx.core.json.JsonArray) OutStream(org.folio.rest.tools.utils.OutStream) SchemaMaker(org.folio.rest.persist.ddlgen.SchemaMaker) Validate(org.folio.rest.annotations.Validate)

Example 12 with OutStream

use of org.folio.rest.tools.utils.OutStream in project mod-inventory-storage by folio-org.

the class LocationUnitAPI method postLocationUnitsCampuses.

@Override
public void postLocationUnitsCampuses(String lang, Loccamp entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
    String tenantId = getTenant(okapiHeaders);
    String id = entity.getId();
    if (id == null) {
        id = UUID.randomUUID().toString();
        entity.setId(id);
    }
    PostgresClient.getInstance(vertxContext.owner(), tenantId).save(CAMPUS_TABLE, id, entity, reply -> {
        if (reply.failed()) {
            String message = logAndSaveError(reply.cause());
            if (isDuplicate(message)) {
                asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.PostLocationUnitsCampusesResponse.withJsonUnprocessableEntity(ValidationHelper.createValidationErrorMessage("loccamp", entity.getId(), "Campus already exists"))));
            } else {
                asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.PostLocationUnitsCampusesResponse.withPlainInternalServerError(message)));
            }
        } else {
            Object responseObject = reply.result();
            entity.setId((String) responseObject);
            OutStream stream = new OutStream();
            stream.setData(entity);
            asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.PostLocationUnitsCampusesResponse.withJsonCreated(URL_PREFIX + responseObject, stream)));
        }
    });
}
Also used : OutStream(org.folio.rest.tools.utils.OutStream)

Example 13 with OutStream

use of org.folio.rest.tools.utils.OutStream in project mod-inventory-storage by folio-org.

the class PlatformAPI method postPlatforms.

@Validate
@Override
public void postPlatforms(String lang, Platform entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    vertxContext.runOnContext(v -> {
        try {
            String id = entity.getId();
            if (id == null) {
                id = UUID.randomUUID().toString();
                entity.setId(id);
            }
            String tenantId = TenantTool.tenantId(okapiHeaders);
            PostgresClient.getInstance(vertxContext.owner(), tenantId).save(PLATFORM_TABLE, id, entity, reply -> {
                try {
                    if (reply.succeeded()) {
                        Object ret = reply.result();
                        entity.setId((String) ret);
                        OutStream stream = new OutStream();
                        stream.setData(entity);
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PlatformsResource.PostPlatformsResponse.withJsonCreated(LOCATION_PREFIX + ret, stream)));
                    } else {
                        String msg = PgExceptionUtil.badRequestMessage(reply.cause());
                        if (msg == null) {
                            internalServerErrorDuringPost(reply.cause(), lang, asyncResultHandler);
                            return;
                        }
                        log.info(msg);
                        asyncResultHandler.handle(Future.succeededFuture(PlatformsResource.PostPlatformsResponse.withPlainBadRequest(msg)));
                    }
                } catch (Exception e) {
                    internalServerErrorDuringPost(e, lang, asyncResultHandler);
                }
            });
        } catch (Exception e) {
            internalServerErrorDuringPost(e, lang, asyncResultHandler);
        }
    });
}
Also used : OutStream(org.folio.rest.tools.utils.OutStream) CQLParseException(org.z3950.zing.cql.CQLParseException) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 14 with OutStream

use of org.folio.rest.tools.utils.OutStream in project mod-inventory-storage by folio-org.

the class HoldingsStorageAPI method putHoldingsStorageHoldingsByHoldingsRecordId.

@Override
public void putHoldingsStorageHoldingsByHoldingsRecordId(@NotNull String holdingsRecordId, @DefaultValue("en") @Pattern(regexp = "[a-zA-Z]{2}") String lang, HoldingsRecord entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    String tenantId = okapiHeaders.get(TENANT_HEADER);
    try {
        PostgresClient postgresClient = PostgresClient.getInstance(vertxContext.owner(), TenantTool.calculateTenantId(tenantId));
        vertxContext.runOnContext(v -> {
            try {
                String[] fieldList = { "*" };
                CQL2PgJSON cql2pgJson = new CQL2PgJSON(HOLDINGS_RECORD_TABLE + ".jsonb");
                CQLWrapper cql = new CQLWrapper(cql2pgJson, String.format("id==%s", holdingsRecordId)).setLimit(new Limit(1)).setOffset(new Offset(0));
                log.info(String.format("SQL generated from CQL: %s", cql.toString()));
                postgresClient.get(HOLDINGS_RECORD_TABLE, HoldingsRecord.class, fieldList, cql, true, false, reply -> {
                    if (reply.succeeded()) {
                        List<HoldingsRecord> itemList = (List<HoldingsRecord>) reply.result().getResults();
                        if (itemList.size() == 1) {
                            try {
                                postgresClient.update(HOLDINGS_RECORD_TABLE, entity, entity.getId(), update -> {
                                    try {
                                        if (update.succeeded()) {
                                            OutStream stream = new OutStream();
                                            stream.setData(entity);
                                            asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withNoContent()));
                                        } else {
                                            asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(update.cause().getMessage())));
                                        }
                                    } catch (Exception e) {
                                        asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(e.getMessage())));
                                    }
                                });
                            } catch (Exception e) {
                                asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(e.getMessage())));
                            }
                        } else {
                            try {
                                postgresClient.save(HOLDINGS_RECORD_TABLE, entity.getId(), entity, save -> {
                                    try {
                                        if (save.succeeded()) {
                                            OutStream stream = new OutStream();
                                            stream.setData(entity);
                                            asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withNoContent()));
                                        } else {
                                            asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(save.cause().getMessage())));
                                        }
                                    } catch (Exception e) {
                                        asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(e.getMessage())));
                                    }
                                });
                            } catch (Exception e) {
                                asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(e.getMessage())));
                            }
                        }
                    } else {
                        asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(reply.cause().getMessage())));
                    }
                });
            } catch (Exception e) {
                asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(e.getMessage())));
            }
        });
    } catch (Exception e) {
        asyncResultHandler.handle(Future.succeededFuture(PutHoldingsStorageHoldingsByHoldingsRecordIdResponse.withPlainInternalServerError(e.getMessage())));
    }
}
Also used : CQL2PgJSON(org.z3950.zing.cql.cql2pgjson.CQL2PgJSON) HoldingsRecord(org.folio.rest.jaxrs.model.HoldingsRecord) PostgresClient(org.folio.rest.persist.PostgresClient) List(java.util.List) OutStream(org.folio.rest.tools.utils.OutStream) Limit(org.folio.rest.persist.Criteria.Limit) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) Offset(org.folio.rest.persist.Criteria.Offset)

Example 15 with OutStream

use of org.folio.rest.tools.utils.OutStream in project mod-inventory-storage by folio-org.

the class IdentifierTypeAPI method postIdentifierTypes.

@Validate
@Override
public void postIdentifierTypes(String lang, IdentifierType entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    vertxContext.runOnContext(v -> {
        try {
            String id = entity.getId();
            if (id == null) {
                id = UUID.randomUUID().toString();
                entity.setId(id);
            }
            String tenantId = TenantTool.tenantId(okapiHeaders);
            PostgresClient.getInstance(vertxContext.owner(), tenantId).save(IDENTIFIER_TYPE_TABLE, id, entity, reply -> {
                try {
                    if (reply.succeeded()) {
                        Object ret = reply.result();
                        entity.setId((String) ret);
                        OutStream stream = new OutStream();
                        stream.setData(entity);
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PostIdentifierTypesResponse.withJsonCreated(LOCATION_PREFIX + ret, stream)));
                    } else {
                        String msg = PgExceptionUtil.badRequestMessage(reply.cause());
                        if (msg == null) {
                            internalServerErrorDuringPost(reply.cause(), lang, asyncResultHandler);
                            return;
                        }
                        log.info(msg);
                        asyncResultHandler.handle(Future.succeededFuture(PostIdentifierTypesResponse.withPlainBadRequest(msg)));
                    }
                } catch (Exception e) {
                    internalServerErrorDuringPost(e, lang, asyncResultHandler);
                }
            });
        } catch (Exception e) {
            internalServerErrorDuringPost(e, lang, asyncResultHandler);
        }
    });
}
Also used : OutStream(org.folio.rest.tools.utils.OutStream) CQLParseException(org.z3950.zing.cql.CQLParseException) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Aggregations

OutStream (org.folio.rest.tools.utils.OutStream)40 Validate (org.folio.rest.annotations.Validate)26 FieldException (org.z3950.zing.cql.cql2pgjson.FieldException)13 CQLParseException (org.z3950.zing.cql.CQLParseException)8 PostgresClient (org.folio.rest.persist.PostgresClient)7 List (java.util.List)5 JsonObject (io.vertx.core.json.JsonObject)4 Response (javax.ws.rs.core.Response)4 CQLWrapper (org.folio.rest.persist.cql.CQLWrapper)4 Map (java.util.Map)3 Limit (org.folio.rest.persist.Criteria.Limit)3 Offset (org.folio.rest.persist.Criteria.Offset)3 TenantTool (org.folio.rest.tools.utils.TenantTool)3 CQL2PgJSON (org.z3950.zing.cql.cql2pgjson.CQL2PgJSON)3 io.vertx.core (io.vertx.core)2 AsyncResult (io.vertx.core.AsyncResult)2 JsonArray (io.vertx.core.json.JsonArray)2 Logger (io.vertx.core.logging.Logger)2 LoggerFactory (io.vertx.core.logging.LoggerFactory)2 InputStream (java.io.InputStream)2