Search in sources :

Example 1 with ResponseDelegate

use of org.folio.rest.jaxrs.resource.support.ResponseDelegate in project raml-module-builder by folio-org.

the class PgUtil method postSync.

/**
 * Post a list of T entities to the database. Fail all if any of them fails.
 * @param table database table to store into
 * @param entities  the records to store
 * @param maxEntities  fail with HTTP 413 if entities.size() > maxEntities to avoid out of memory;
 *     suggested value is from 100 ... 10000.
 * @param upsert  true to update records with the same id, false to fail all entities if one has an existing id
 * @param okapiHeaders  http headers provided by okapi
 * @param vertxContext  the current context
 * @param responseClass  the ResponseDelegate class created from the RAML file with these methods:
 *               respond201(), respond409WithTextPlain(Object), respond413WithTextPlain(Object), respond500WithTextPlain(Object).
 * @return future where to return the result created by responseClass
 */
public static <T> Future<Response> postSync(String table, List<T> entities, int maxEntities, boolean upsert, Map<String, String> okapiHeaders, Context vertxContext, Class<? extends ResponseDelegate> responseClass) {
    final Method respond500;
    try {
        respond500 = responseClass.getMethod(RESPOND_500_WITH_TEXT_PLAIN, Object.class);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return response(e.getMessage(), null, null);
    }
    try {
        Method respond201 = responseClass.getMethod(RESPOND_201);
        Method respond409 = getRespond409(responseClass);
        Method respond413 = responseClass.getMethod(RESPOND_413_WITH_TEXT_PLAIN, Object.class);
        if (entities != null && entities.size() > maxEntities) {
            String message = "Expected a maximum of " + maxEntities + " records to prevent out of memory but got " + entities.size();
            return response(message, respond413, respond500);
        }
        // RestVerticle populates a single record only, not an array of records
        Promise<Response> promise = Promise.promise();
        MetadataUtil.populateMetadata(entities, okapiHeaders);
        PostgresClient postgresClient = postgresClient(vertxContext, okapiHeaders);
        Handler<AsyncResult<RowSet<Row>>> replyHandler = result -> {
            if (result.failed()) {
                if (PgExceptionUtil.isVersionConflict(result.cause())) {
                    Method method = respond409 == null ? respond500 : respond409;
                    response(result.cause().getMessage(), method, respond500).onComplete(promise);
                } else {
                    response(table, /* id */
                    "", result.cause(), responseClass, respond500, respond500).onComplete(promise);
                }
            }
            response(respond201, respond500).onComplete(promise);
        };
        if (upsert) {
            postgresClient.upsertBatch(table, entities, replyHandler);
        } else {
            postgresClient.saveBatch(table, entities, replyHandler);
        }
        return promise.future();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return response(e.getMessage(), respond500, respond500);
    }
}
Also used : Response(javax.ws.rs.core.Response) HttpServerResponse(io.vertx.core.http.HttpServerResponse) ValidationHelper(org.folio.rest.tools.utils.ValidationHelper) RoutingContext(io.vertx.ext.web.RoutingContext) Context(io.vertx.core.Context) MetadataUtil(org.folio.rest.tools.utils.MetadataUtil) RowIterator(io.vertx.sqlclient.RowIterator) Matcher(java.util.regex.Matcher) ObjectMapperTool(org.folio.dbschema.ObjectMapperTool) Map(java.util.Map) Method(java.lang.reflect.Method) Errors(org.folio.rest.jaxrs.model.Errors) CQLSortNode(org.z3950.zing.cql.CQLSortNode) FacetManager(org.folio.rest.persist.facets.FacetManager) HttpHeaders(io.vertx.core.http.HttpHeaders) UUID(java.util.UUID) FieldException(org.folio.cql2pgjson.exception.FieldException) Future(io.vertx.core.Future) TenantTool(org.folio.rest.tools.utils.TenantTool) InvocationTargetException(java.lang.reflect.InvocationTargetException) OutStream(org.folio.rest.tools.utils.OutStream) CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CQLParser(org.z3950.zing.cql.CQLParser) Response(javax.ws.rs.core.Response) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Pattern(java.util.regex.Pattern) CQLNode(org.z3950.zing.cql.CQLNode) ModifierSet(org.z3950.zing.cql.ModifierSet) Json(io.vertx.core.json.Json) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) FacetField(org.folio.rest.persist.facets.FacetField) CQLDefaultNodeVisitor(org.z3950.zing.cql.CQLDefaultNodeVisitor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) UuidUtil(org.folio.util.UuidUtil) ResultInfo(org.folio.rest.jaxrs.model.ResultInfo) ArrayList(java.util.ArrayList) ResponseDelegate(org.folio.rest.jaxrs.resource.support.ResponseDelegate) QueryValidationException(org.folio.cql2pgjson.exception.QueryValidationException) CQLParseException(org.z3950.zing.cql.CQLParseException) RowSet(io.vertx.sqlclient.RowSet) AsyncResult(io.vertx.core.AsyncResult) CQLFeatureUnsupportedException(org.folio.cql2pgjson.exception.CQLFeatureUnsupportedException) Diagnostic(org.folio.rest.jaxrs.model.Diagnostic) Modifier(org.z3950.zing.cql.Modifier) Promise(io.vertx.core.Promise) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Row(io.vertx.sqlclient.Row) Handler(io.vertx.core.Handler) LogManager(org.apache.logging.log4j.LogManager) Method(java.lang.reflect.Method) Row(io.vertx.sqlclient.Row) AsyncResult(io.vertx.core.AsyncResult) FieldException(org.folio.cql2pgjson.exception.FieldException) InvocationTargetException(java.lang.reflect.InvocationTargetException) QueryValidationException(org.folio.cql2pgjson.exception.QueryValidationException) CQLParseException(org.z3950.zing.cql.CQLParseException) CQLFeatureUnsupportedException(org.folio.cql2pgjson.exception.CQLFeatureUnsupportedException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 AsyncResult (io.vertx.core.AsyncResult)1 Context (io.vertx.core.Context)1 Future (io.vertx.core.Future)1 Handler (io.vertx.core.Handler)1 Promise (io.vertx.core.Promise)1 HttpHeaders (io.vertx.core.http.HttpHeaders)1 HttpServerResponse (io.vertx.core.http.HttpServerResponse)1 Json (io.vertx.core.json.Json)1 RoutingContext (io.vertx.ext.web.RoutingContext)1 Row (io.vertx.sqlclient.Row)1 RowIterator (io.vertx.sqlclient.RowIterator)1 RowSet (io.vertx.sqlclient.RowSet)1 IOException (java.io.IOException)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1