Search in sources :

Example 36 with OutStream

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

the class AdminAPI method getAdminTotalDbSize.

@Validate
@Override
public void getAdminTotalDbSize(String dbname, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    PostgresClient.getInstance(vertxContext.owner()).select("select pg_size_pretty(pg_database_size('" + dbname + "')) as db_size", reply -> {
        if (reply.succeeded()) {
            OutStream stream = new OutStream();
            stream.setData(reply.result().getRows());
            asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminTotalDbSizeResponse.withJsonOK(stream)));
        } else {
            log.error(reply.cause().getMessage(), reply.cause());
            asyncResultHandler.handle(io.vertx.core.Future.failedFuture(reply.cause().getMessage()));
        }
    });
}
Also used : OutStream(org.folio.rest.tools.utils.OutStream) Validate(org.folio.rest.annotations.Validate)

Example 37 with OutStream

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

the class AdminAPI method getAdminPostgresTableSize.

@Validate
@Override
public void getAdminPostgresTableSize(String dbname, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    PostgresClient.getInstance(vertxContext.owner()).select("SELECT relname as \"Table\", pg_size_pretty(pg_relation_size(relid)) As \" Table Size\"," + " pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as \"Index Size\"" + " FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;", reply -> {
        if (reply.succeeded()) {
            OutStream stream = new OutStream();
            stream.setData(reply.result().getRows());
            asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminPostgresTableAccessStatsResponse.withJsonOK(stream)));
        } else {
            log.error(reply.cause().getMessage(), reply.cause());
            asyncResultHandler.handle(io.vertx.core.Future.failedFuture(reply.cause().getMessage()));
        }
    });
}
Also used : OutStream(org.folio.rest.tools.utils.OutStream) Validate(org.folio.rest.annotations.Validate)

Example 38 with OutStream

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

the class BooksDemoAPI method postRmbtestsTest.

@Override
public void postRmbtestsTest(Reader entity, RoutingContext routingContext, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    OutStream os = new OutStream();
    try {
        os.setData(routingContext.getBodyAsJson());
        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PostRmbtestsTestResponse.withJsonOK(os)));
    } catch (Exception e) {
        log.error(e);
        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(null));
    }
}
Also used : OutStream(org.folio.rest.tools.utils.OutStream)

Example 39 with OutStream

use of org.folio.rest.tools.utils.OutStream 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)

Example 40 with OutStream

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

the class RestVerticle method sendResponse.

/**
 * Send the result as response.
 *
 * @param rc
 *          - where to send the result
 * @param v
 *          - the result to send
 * @param start
 *          - request's start time, using JVM's high-resolution time source, in nanoseconds
 */
private void sendResponse(RoutingContext rc, AsyncResult<Response> v, long start, String tenantId) {
    Response result = ((Response) ((AsyncResult<?>) v).result());
    if (result == null) {
        // catch all
        endRequestWithError(rc, 500, true, "Server error", new boolean[] { true });
        return;
    }
    Object entity = null;
    try {
        HttpServerResponse response = rc.response();
        int statusCode = result.getStatus();
        // a chunked Transfer header is not allowed
        if (statusCode != 204) {
            response.setChunked(true);
        }
        response.setStatusCode(statusCode);
        for (Entry<String, List<String>> entry : result.getStringHeaders().entrySet()) {
            String jointValue = Joiner.on("; ").join(entry.getValue());
            response.headers().add(entry.getKey(), jointValue);
        }
        // response.headers().add(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate");
        // forward all headers except content-type that was passed in by the client
        // since this may cause problems when for example application/octet-stream is
        // sent as part of an upload. passing this back will confuse clients as they
        // will think they are getting back a stream of data which may not be the case
        rc.request().headers().remove("Content-type");
        // should not be forwarded in cases of no content
        if (statusCode == 204) {
            rc.request().headers().remove("transfer-encoding");
        }
        mergeIntoResponseHeadersDistinct(response.headers(), rc.request().headers());
        entity = result.getEntity();
        /* entity is of type OutStream - and will be written as a string */
        if (entity instanceof OutStream) {
            response.write(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(((OutStream) entity).getData()));
        } else /* entity is of type BinaryOutStream - and will be written as a buffer */
        if (entity instanceof BinaryOutStream) {
            response.write(Buffer.buffer(((BinaryOutStream) entity).getData()));
        } else /* data is a string so just push it out, no conversion needed */
        if (entity instanceof String) {
            response.write(Buffer.buffer((String) entity));
        } else /* catch all - anything else will be assumed to be a pojo which needs converting to json */
        if (entity != null) {
            response.write(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(entity));
        }
    } catch (Exception e) {
        log.error(e);
    } finally {
        rc.response().end();
    }
    long end = System.nanoTime();
    StringBuilder sb = new StringBuilder();
    if (log.isDebugEnabled()) {
        try {
            sb.append(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(entity));
        } catch (Exception e) {
            String name = "null";
            if (entity != null) {
                name = entity.getClass().getName();
            }
            log.error("writeValueAsString(" + name + ")", e);
        }
    }
    LogUtil.formatStatsLogMessage(rc.request().remoteAddress().toString(), rc.request().method().toString(), rc.request().version().toString(), rc.response().getStatusCode(), (((end - start) / 1000000)), rc.response().bytesWritten(), rc.request().path(), rc.request().query(), rc.response().getStatusMessage(), tenantId, sb.toString());
}
Also used : BinaryOutStream(org.folio.rest.tools.utils.BinaryOutStream) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpServerResponse(io.vertx.core.http.HttpServerResponse) JsonObject(io.vertx.core.json.JsonObject) List(java.util.List) ArrayList(java.util.ArrayList) BinaryOutStream(org.folio.rest.tools.utils.BinaryOutStream) OutStream(org.folio.rest.tools.utils.OutStream) AsyncResult(io.vertx.core.AsyncResult)

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