Search in sources :

Example 51 with Validate

use of org.folio.rest.annotations.Validate 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 52 with Validate

use of org.folio.rest.annotations.Validate in project mod-inventory-storage by folio-org.

the class ContributorTypeAPI method getContributorTypes.

@Validate
@Override
public void getContributorTypes(String query, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    /**
     * http://host:port/contributor-types
     */
    vertxContext.runOnContext(v -> {
        try {
            String tenantId = TenantTool.tenantId(okapiHeaders);
            CQLWrapper cql = getCQL(query, limit, offset);
            PostgresClient.getInstance(vertxContext.owner(), tenantId).get(CONTRIBUTOR_TYPE_TABLE, ContributorType.class, new String[] { "*" }, cql, true, true, reply -> {
                try {
                    if (reply.succeeded()) {
                        ContributorTypes contributorTypes = new ContributorTypes();
                        @SuppressWarnings("unchecked") List<ContributorType> contributorType = (List<ContributorType>) reply.result().getResults();
                        contributorTypes.setContributorTypes(contributorType);
                        contributorTypes.setTotalRecords(reply.result().getResultInfo().getTotalRecords());
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetContributorTypesResponse.withJsonOK(contributorTypes)));
                    } else {
                        log.error(reply.cause().getMessage(), reply.cause());
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetContributorTypesResponse.withPlainBadRequest(reply.cause().getMessage())));
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetContributorTypesResponse.withPlainInternalServerError(messages.getMessage(lang, MessageConsts.InternalServerError))));
                }
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            String message = messages.getMessage(lang, MessageConsts.InternalServerError);
            if (e.getCause() instanceof CQLParseException) {
                message = " CQL parse error " + e.getLocalizedMessage();
            }
            asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetContributorTypesResponse.withPlainInternalServerError(message)));
        }
    });
}
Also used : ContributorType(org.folio.rest.jaxrs.model.ContributorType) List(java.util.List) ContributorTypes(org.folio.rest.jaxrs.model.ContributorTypes) CQLParseException(org.z3950.zing.cql.CQLParseException) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) CQLParseException(org.z3950.zing.cql.CQLParseException) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 53 with Validate

use of org.folio.rest.annotations.Validate in project mod-inventory-storage by folio-org.

the class ContributorTypeAPI method getContributorTypesByContributorTypeId.

@Validate
@Override
public void getContributorTypesByContributorTypeId(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);
            Criterion c = new Criterion(new Criteria().addField(idFieldName).setJSONB(false).setOperation("=").setValue("'" + contributorTypeId + "'"));
            PostgresClient.getInstance(vertxContext.owner(), tenantId).get(CONTRIBUTOR_TYPE_TABLE, ContributorType.class, c, true, reply -> {
                try {
                    if (reply.failed()) {
                        String msg = PgExceptionUtil.badRequestMessage(reply.cause());
                        if (msg == null) {
                            internalServerErrorDuringGetById(reply.cause(), lang, asyncResultHandler);
                            return;
                        }
                        log.info(msg);
                        asyncResultHandler.handle(Future.succeededFuture(GetContributorTypesByContributorTypeIdResponse.withPlainNotFound(msg)));
                        return;
                    }
                    @SuppressWarnings("unchecked") List<ContributorType> contributorType = (List<ContributorType>) reply.result().getResults();
                    if (contributorType.isEmpty()) {
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetContributorTypesByContributorTypeIdResponse.withPlainNotFound(contributorTypeId)));
                    } else {
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetContributorTypesByContributorTypeIdResponse.withJsonOK(contributorType.get(0))));
                    }
                } catch (Exception e) {
                    internalServerErrorDuringGetById(e, lang, asyncResultHandler);
                }
            });
        } catch (Exception e) {
            internalServerErrorDuringGetById(e, lang, asyncResultHandler);
        }
    });
}
Also used : ContributorType(org.folio.rest.jaxrs.model.ContributorType) Criterion(org.folio.rest.persist.Criteria.Criterion) List(java.util.List) Criteria(org.folio.rest.persist.Criteria.Criteria) CQLParseException(org.z3950.zing.cql.CQLParseException) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 54 with Validate

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

the class AdminAPI method getAdminPostgresLoad.

@Validate
@Override
public void getAdminPostgresLoad(String dbname, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    PostgresClient.getInstance(vertxContext.owner()).select("SELECT pg_stat_reset()", reply -> {
        if (reply.succeeded()) {
            /* wait 10 seconds for stats to gather and then query stats table for info */
            vertxContext.owner().setTimer(10000, new Handler<Long>() {

                @Override
                public void handle(Long timerID) {
                    PostgresClient.getInstance(vertxContext.owner(), "public").select("SELECT numbackends as CONNECTIONS, xact_commit as TX_COMM, xact_rollback as " + "TX_RLBCK, blks_read + blks_hit as READ_TOTAL, " + "blks_hit * 100 / (blks_read + blks_hit) " + "as BUFFER_HIT_PERCENT FROM pg_stat_database WHERE datname = '" + dbname + "'", reply2 -> {
                        if (reply2.succeeded()) {
                            OutStream stream = new OutStream();
                            stream.setData(reply2.result().getRows());
                            asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminPostgresLoadResponse.withJsonOK(stream)));
                        } else {
                            log.error(reply2.cause().getMessage(), reply2.cause());
                            asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminPostgresLoadResponse.withPlainInternalServerError(reply2.cause().getMessage())));
                        }
                    });
                }
            });
        } else {
            log.error(reply.cause().getMessage(), reply.cause());
            asyncResultHandler.handle(io.vertx.core.Future.failedFuture(reply.cause().getMessage()));
        }
    });
}
Also used : RestVerticle(org.folio.rest.RestVerticle) LRUCache(org.folio.rest.tools.utils.LRUCache) AES(org.folio.rest.security.AES) Date(java.util.Date) StatsTracker(org.folio.rest.tools.monitor.StatsTracker) Context(io.vertx.core.Context) BodyPart(javax.mail.BodyPart) PomReader(org.folio.rest.tools.PomReader) MemoryMXBean(java.lang.management.MemoryMXBean) Logger(org.apache.log4j.Logger) ThreadInfo(java.lang.management.ThreadInfo) MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) LogUtil(org.folio.rest.tools.utils.LogUtil) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) ManagementFactory(java.lang.management.ManagementFactory) AsyncResult(io.vertx.core.AsyncResult) MemoryUsage(java.lang.management.MemoryUsage) MimeMultipart(javax.mail.internet.MimeMultipart) DecimalFormat(java.text.DecimalFormat) ThreadMXBean(java.lang.management.ThreadMXBean) Validate(org.folio.rest.annotations.Validate) TenantTool(org.folio.rest.tools.utils.TenantTool) PostgresClient(org.folio.rest.persist.PostgresClient) IOUtils(org.apache.commons.io.IOUtils) OutStream(org.folio.rest.tools.utils.OutStream) Response(javax.ws.rs.core.Response) AdminResource(org.folio.rest.jaxrs.resource.AdminResource) ClientGenerator(org.folio.rest.tools.ClientGenerator) LogManager(org.apache.log4j.LogManager) Handler(io.vertx.core.Handler) InputStream(java.io.InputStream) OutStream(org.folio.rest.tools.utils.OutStream) Validate(org.folio.rest.annotations.Validate)

Example 55 with Validate

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

the class AdminAPI method getAdminMemory.

@Validate
@Override
public void getAdminMemory(boolean history, java.util.Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    final StringBuilder dump = new StringBuilder();
    vertxContext.owner().executeBlocking(code -> {
        try {
            dump.append("<br><table>");
            for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
                MemoryUsage mem = pool.getCollectionUsage();
                MemoryUsage curMem = pool.getUsage();
                MemoryUsage peakMem = pool.getPeakUsage();
                long usageAfterGC = -1;
                long currentUsage = -1;
                double usageAfterGCPercent = -1;
                double currentUsagePercent = -1;
                long peakUsage = -1;
                if (mem != null) {
                    usageAfterGC = mem.getUsed() / 1024 / 1024;
                    // Mimic jstat behavior
                    usageAfterGCPercent = (double) mem.getUsed() / (double) mem.getCommitted() * 100;
                }
                if (curMem != null) {
                    currentUsage = curMem.getUsed() / 1024 / 1024;
                    if (curMem.getMax() > 0) {
                        currentUsagePercent = (double) curMem.getUsed() / (double) curMem.getCommitted() * // Mimic jstat behavior
                        100;
                    }
                }
                if (peakMem != null) {
                    peakUsage = peakMem.getUsed() / 1024 / 1024;
                }
                dump.append("<tr><td>name: ").append(pool.getName()).append("   </td>").append("<td>memory usage after latest gc: <b>").append(usageAfterGC).append("</b>MB.   </td>").append("<td>type: ").append(pool.getType()).append("   </td>").append("<td>estimate of memory usage: <b>").append(currentUsage).append("</b>MB.   </td>").append("<td>peak usage: ").append(peakUsage).append("MB.   </td>").append("<td> % used memory after GC: <b>").append(DECFORMAT.format(usageAfterGCPercent)).append("</b>  </td>").append("<td> % used memory current: <b>").append(DECFORMAT.format(currentUsagePercent)).append("</b>   </td></tr>");
            }
            dump.append("</table><br><br>");
            final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
            final MemoryUsage memInfo = memoryMXBean.getHeapMemoryUsage();
            long memCommittedToJVMByOS = memInfo.getCommitted();
            long memUsedByJVM = memInfo.getUsed();
            dump.append("<b>Total: </b> Memory used/available(MB): ").append((memUsedByJVM / 1024 / 1024)).append("/").append(memCommittedToJVMByOS / 1024 / 1024).append("<br>");
            if (history) {
                StringBuilder historyMem = new StringBuilder();
                jvmMemoryHistory.put(new Date(), dump.toString());
                BiConsumer<Date, String> biConsumer = (key, value) -> historyMem.append(key.toInstant().toString() + "<br>" + value);
                jvmMemoryHistory.forEach(biConsumer);
                code.complete(historyMem);
            } else {
                jvmMemoryHistory.clear();
                code.complete(dump);
            }
        } catch (Exception e) {
            log.error(e);
            asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminMemoryResponse.withPlainInternalServerError("ERROR" + e.getMessage())));
        }
    }, result -> {
        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminMemoryResponse.withHtmlOK(result.result().toString())));
    });
}
Also used : RestVerticle(org.folio.rest.RestVerticle) LRUCache(org.folio.rest.tools.utils.LRUCache) AES(org.folio.rest.security.AES) Date(java.util.Date) StatsTracker(org.folio.rest.tools.monitor.StatsTracker) Context(io.vertx.core.Context) BodyPart(javax.mail.BodyPart) PomReader(org.folio.rest.tools.PomReader) MemoryMXBean(java.lang.management.MemoryMXBean) Logger(org.apache.log4j.Logger) ThreadInfo(java.lang.management.ThreadInfo) MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) LogUtil(org.folio.rest.tools.utils.LogUtil) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) ManagementFactory(java.lang.management.ManagementFactory) AsyncResult(io.vertx.core.AsyncResult) MemoryUsage(java.lang.management.MemoryUsage) MimeMultipart(javax.mail.internet.MimeMultipart) DecimalFormat(java.text.DecimalFormat) ThreadMXBean(java.lang.management.ThreadMXBean) Validate(org.folio.rest.annotations.Validate) TenantTool(org.folio.rest.tools.utils.TenantTool) PostgresClient(org.folio.rest.persist.PostgresClient) IOUtils(org.apache.commons.io.IOUtils) OutStream(org.folio.rest.tools.utils.OutStream) Response(javax.ws.rs.core.Response) AdminResource(org.folio.rest.jaxrs.resource.AdminResource) ClientGenerator(org.folio.rest.tools.ClientGenerator) LogManager(org.apache.log4j.LogManager) Handler(io.vertx.core.Handler) InputStream(java.io.InputStream) MemoryMXBean(java.lang.management.MemoryMXBean) MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) MemoryUsage(java.lang.management.MemoryUsage) Date(java.util.Date) 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