Search in sources :

Example 26 with PostgresClient

use of org.folio.rest.persist.PostgresClient in project mod-inventory-storage by folio-org.

the class ItemStorageAPI method postItemStorageItems.

@Validate
@Override
public void postItemStorageItems(@DefaultValue("en") @Pattern(regexp = "[a-zA-Z]{2}") String lang, Item 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));
        if (entity.getId() == null) {
            entity.setId(UUID.randomUUID().toString());
        }
        vertxContext.runOnContext(v -> {
            try {
                /**
                 *This should be replaced with a foreign key / cache since a lookup into the MT table
                 * every time an item is inserted is wasteful and slows down the insert process
                 */
                getMaterialType(vertxContext.owner(), tenantId, entity, replyHandler -> {
                    int res = replyHandler.result();
                    if (res == 0) {
                        String message = "Can not add " + entity.getMaterialTypeId() + ". Material type not found";
                        log.error(message);
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainBadRequest(message)));
                        return;
                    } else if (res == -1) {
                        asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError("")));
                        return;
                    } else {
                        Future<Location> temporaryLocationFuture;
                        if (entity.getTemporaryLocationId() != null) {
                            temporaryLocationFuture = getShelfLocation(vertxContext.owner(), tenantId, entity.getTemporaryLocationId());
                        } else {
                            temporaryLocationFuture = Future.succeededFuture();
                        }
                        temporaryLocationFuture.setHandler(compRes -> {
                            if (compRes.failed()) {
                                String message = "Attempting to specify non-existent location";
                                log.error(message);
                                asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainBadRequest(message)));
                            } else {
                                try {
                                    postgresClient.save("item", entity.getId(), entity, reply -> {
                                        try {
                                            if (reply.succeeded()) {
                                                OutStream stream = new OutStream();
                                                stream.setData(entity);
                                                asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withJsonCreated(reply.result(), stream)));
                                            } else {
                                                String message = PgExceptionUtil.badRequestMessage(reply.cause());
                                                if (message != null) {
                                                    asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainBadRequest(message)));
                                                } else {
                                                    asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(reply.cause().getMessage())));
                                                }
                                            }
                                        } catch (Exception e) {
                                            asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                                        }
                                    });
                                } catch (Exception e) {
                                    asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                                }
                            }
                        });
                    }
                });
            } catch (Exception e) {
                asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
            }
        });
    } catch (Exception e) {
        asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
    }
}
Also used : PathParam(javax.ws.rs.PathParam) Arrays(java.util.Arrays) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) io.vertx.core(io.vertx.core) Criteria(org.folio.rest.persist.Criteria.Criteria) LoggerFactory(io.vertx.core.logging.LoggerFactory) QueryParam(javax.ws.rs.QueryParam) Limit(org.folio.rest.persist.Criteria.Limit) PgExceptionUtil(org.folio.rest.persist.PgExceptionUtil) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Offset(org.folio.rest.persist.Criteria.Offset) Logger(io.vertx.core.logging.Logger) ItemStorageResource(org.folio.rest.jaxrs.resource.ItemStorageResource) UUID(java.util.UUID) NotNull(javax.validation.constraints.NotNull) Validate(org.folio.rest.annotations.Validate) TenantTool(org.folio.rest.tools.utils.TenantTool) PostgresClient(org.folio.rest.persist.PostgresClient) org.folio.rest.jaxrs.model(org.folio.rest.jaxrs.model) OutStream(org.folio.rest.tools.utils.OutStream) List(java.util.List) Criterion(org.folio.rest.persist.Criteria.Criterion) Response(javax.ws.rs.core.Response) Pattern(javax.validation.constraints.Pattern) CQL2PgJSON(org.z3950.zing.cql.cql2pgjson.CQL2PgJSON) PostgresClient(org.folio.rest.persist.PostgresClient) OutStream(org.folio.rest.tools.utils.OutStream) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 27 with PostgresClient

use of org.folio.rest.persist.PostgresClient in project mod-inventory-storage by folio-org.

the class MaterialTypeAPI method deleteMaterialTypes.

@Override
public void deleteMaterialTypes(String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    String tenantId = TenantTool.tenantId(okapiHeaders);
    try {
        vertxContext.runOnContext(v -> {
            PostgresClient postgresClient = PostgresClient.getInstance(vertxContext.owner(), TenantTool.calculateTenantId(tenantId));
            postgresClient.mutate(String.format("DELETE FROM %s_%s.%s", tenantId, "mod_inventory_storage", MATERIAL_TYPE_TABLE), reply -> {
                if (reply.succeeded()) {
                    asyncResultHandler.handle(Future.succeededFuture(MaterialTypesResource.DeleteMaterialTypesResponse.noContent().build()));
                } else {
                    asyncResultHandler.handle(Future.succeededFuture(MaterialTypesResource.DeleteMaterialTypesResponse.withPlainInternalServerError(reply.cause().getMessage())));
                }
            });
        });
    } catch (Exception e) {
        asyncResultHandler.handle(Future.succeededFuture(MaterialTypesResource.DeleteMaterialTypesResponse.withPlainInternalServerError(e.getMessage())));
    }
}
Also used : PostgresClient(org.folio.rest.persist.PostgresClient) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException)

Example 28 with PostgresClient

use of org.folio.rest.persist.PostgresClient in project mod-inventory-storage by folio-org.

the class ClassificationTypeAPI method deleteClassificationTypesByClassificationTypeId.

@Validate
@Override
public void deleteClassificationTypesByClassificationTypeId(String instanceTypeId, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    vertxContext.runOnContext(v -> {
        try {
            String tenantId = TenantTool.tenantId(okapiHeaders);
            PostgresClient postgres = PostgresClient.getInstance(vertxContext.owner(), tenantId);
            postgres.delete(CLASSIFICATION_TYPE_TABLE, instanceTypeId, reply -> {
                try {
                    if (reply.failed()) {
                        String msg = PgExceptionUtil.badRequestMessage(reply.cause());
                        if (msg == null) {
                            internalServerErrorDuringDelete(reply.cause(), lang, asyncResultHandler);
                            return;
                        }
                        log.info(msg);
                        asyncResultHandler.handle(Future.succeededFuture(DeleteClassificationTypesByClassificationTypeIdResponse.withPlainBadRequest(msg)));
                        return;
                    }
                    int updated = reply.result().getUpdated();
                    if (updated != 1) {
                        String msg = messages.getMessage(lang, MessageConsts.DeletedCountError, 1, updated);
                        log.error(msg);
                        asyncResultHandler.handle(Future.succeededFuture(DeleteClassificationTypesByClassificationTypeIdResponse.withPlainNotFound(msg)));
                        return;
                    }
                    asyncResultHandler.handle(Future.succeededFuture(DeleteClassificationTypesByClassificationTypeIdResponse.withNoContent()));
                } catch (Exception e) {
                    internalServerErrorDuringDelete(e, lang, asyncResultHandler);
                }
            });
        } catch (Exception e) {
            internalServerErrorDuringDelete(e, lang, asyncResultHandler);
        }
    });
}
Also used : PostgresClient(org.folio.rest.persist.PostgresClient) CQLParseException(org.z3950.zing.cql.CQLParseException) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 29 with PostgresClient

use of org.folio.rest.persist.PostgresClient in project mod-inventory-storage by folio-org.

the class ContributorTypeAPI method deleteContributorTypesByContributorTypeId.

@Validate
@Override
public void deleteContributorTypesByContributorTypeId(String contributorTypeId, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    vertxContext.runOnContext(v -> {
        try {
            String tenantId = TenantTool.tenantId(okapiHeaders);
            PostgresClient postgres = PostgresClient.getInstance(vertxContext.owner(), tenantId);
            postgres.delete(CONTRIBUTOR_TYPE_TABLE, contributorTypeId, reply -> {
                try {
                    if (reply.failed()) {
                        String msg = PgExceptionUtil.badRequestMessage(reply.cause());
                        if (msg == null) {
                            internalServerErrorDuringDelete(reply.cause(), lang, asyncResultHandler);
                            return;
                        }
                        log.info(msg);
                        asyncResultHandler.handle(Future.succeededFuture(DeleteContributorTypesByContributorTypeIdResponse.withPlainBadRequest(msg)));
                        return;
                    }
                    int updated = reply.result().getUpdated();
                    if (updated != 1) {
                        String msg = messages.getMessage(lang, MessageConsts.DeletedCountError, 1, updated);
                        log.error(msg);
                        asyncResultHandler.handle(Future.succeededFuture(DeleteContributorTypesByContributorTypeIdResponse.withPlainNotFound(msg)));
                        return;
                    }
                    asyncResultHandler.handle(Future.succeededFuture(DeleteContributorTypesByContributorTypeIdResponse.withNoContent()));
                } catch (Exception e) {
                    internalServerErrorDuringDelete(e, lang, asyncResultHandler);
                }
            });
        } catch (Exception e) {
            internalServerErrorDuringDelete(e, lang, asyncResultHandler);
        }
    });
}
Also used : PostgresClient(org.folio.rest.persist.PostgresClient) CQLParseException(org.z3950.zing.cql.CQLParseException) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 30 with PostgresClient

use of org.folio.rest.persist.PostgresClient in project mod-inventory-storage by folio-org.

the class StorageTestSuite method getRecordsWithUnmatchedIds.

private static ResultSet getRecordsWithUnmatchedIds(String tenantId, String tableName) throws InterruptedException, ExecutionException, TimeoutException {
    PostgresClient dbClient = PostgresClient.getInstance(getVertx(), tenantId);
    CompletableFuture<ResultSet> selectCompleted = new CompletableFuture<>();
    String sql = String.format("SELECT null FROM %s_%s.%s" + " WHERE CAST(_id AS VARCHAR(50)) != jsonb->>'id'", tenantId, "mod_inventory_storage", tableName);
    dbClient.select(sql, result -> {
        if (result.succeeded()) {
            selectCompleted.complete(result.result());
        } else {
            selectCompleted.completeExceptionally(result.cause());
        }
    });
    return selectCompleted.get(5, TimeUnit.SECONDS);
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) ResultSet(io.vertx.ext.sql.ResultSet) PostgresClient(org.folio.rest.persist.PostgresClient)

Aggregations

PostgresClient (org.folio.rest.persist.PostgresClient)30 FieldException (org.z3950.zing.cql.cql2pgjson.FieldException)22 Validate (org.folio.rest.annotations.Validate)14 List (java.util.List)10 CQLWrapper (org.folio.rest.persist.cql.CQLWrapper)10 CQLParseException (org.z3950.zing.cql.CQLParseException)8 OutStream (org.folio.rest.tools.utils.OutStream)6 Criteria (org.folio.rest.persist.Criteria.Criteria)5 Criterion (org.folio.rest.persist.Criteria.Criterion)5 Limit (org.folio.rest.persist.Criteria.Limit)5 Offset (org.folio.rest.persist.Criteria.Offset)5 CQL2PgJSON (org.z3950.zing.cql.cql2pgjson.CQL2PgJSON)5 HoldingsRecord (org.folio.rest.jaxrs.model.HoldingsRecord)3 Instance (org.folio.rest.jaxrs.model.Instance)3 io.vertx.core (io.vertx.core)2 Logger (io.vertx.core.logging.Logger)2 LoggerFactory (io.vertx.core.logging.LoggerFactory)2 Arrays (java.util.Arrays)2 Map (java.util.Map)2 UUID (java.util.UUID)2