use of org.folio.rest.persist.Criteria.Criterion in project raml-module-builder by folio-org.
the class JobAPI method getJobsJobconfs.
@Validate
@Override
public void getJobsJobconfs(String query, String orderBy, Order order, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
try {
Criterion criterion = Criterion.json2Criterion(query);
criterion.setLimit(new Limit(limit)).setOffset(new Offset(offset));
org.folio.rest.persist.Criteria.Order or = getOrder(order, orderBy);
if (or != null) {
criterion.setOrder(or);
}
System.out.println("sending... getJobsJobconfs");
vertxContext.runOnContext(v -> {
try {
PostgresClient.getInstance(vertxContext.owner()).get(RTFConsts.JOB_CONF_COLLECTION, JobConf.class, criterion, true, reply -> {
JobsConfs ps = new JobsConfs();
@SuppressWarnings("unchecked") List<JobConf> jobConfs = (List<JobConf>) reply.result().getResults();
ps.setJobConfs(jobConfs);
ps.setTotalRecords(jobConfs.size());
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetJobsJobconfsResponse.withJsonOK(ps)));
});
} catch (Exception e) {
log.error(e);
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetJobsJobconfsResponse.withPlainInternalServerError(messages.getMessage(lang, MessageConsts.InternalServerError))));
}
});
} catch (Exception e) {
log.error(e);
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetJobsJobconfsResponse.withPlainInternalServerError(messages.getMessage(lang, MessageConsts.InternalServerError))));
}
}
use of org.folio.rest.persist.Criteria.Criterion in project raml-module-builder by folio-org.
the class JobAPI method getJobsJobconfsByJobconfsIdJobs.
@Validate
@Override
public void getJobsJobconfsByJobconfsIdJobs(String jobconfsId, String query, String orderBy, Order order, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
System.out.println("sending... getJobsJobconfsByJobconfsIdJobs");
try {
Criterion criterion = Criterion.json2Criterion(query);
criterion.setLimit(new Limit(limit)).setOffset(new Offset(offset));
org.folio.rest.persist.Criteria.Order or = getOrder(order, orderBy);
if (or != null) {
criterion.setOrder(or);
}
vertxContext.runOnContext(v -> {
try {
PostgresClient.getInstance(vertxContext.owner()).get(RTFConsts.JOBS_COLLECTION, Job.class, criterion, true, reply -> {
try {
@SuppressWarnings("unchecked") List<Job> jobs = (List<Job>) reply.result().getResults();
Jobs jobList = new Jobs();
jobList.setJobs(jobs);
jobList.setTotalRecords(jobs.size());
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetJobsJobconfsByJobconfsIdJobsResponse.withJsonOK(jobList)));
} catch (Exception e) {
log.error(e.getMessage(), e);
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetJobsJobconfsByJobconfsIdJobsResponse.withPlainInternalServerError(messages.getMessage(lang, MessageConsts.InternalServerError))));
}
});
} catch (Exception e) {
log.error(e.getMessage(), e);
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetJobsJobconfsByJobconfsIdJobsResponse.withPlainInternalServerError(messages.getMessage(lang, MessageConsts.InternalServerError))));
}
});
} catch (Exception e) {
log.error(e.getMessage(), e);
asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetJobsJobconfsByJobconfsIdJobsResponse.withPlainInternalServerError(messages.getMessage(lang, MessageConsts.InternalServerError))));
}
}
use of org.folio.rest.persist.Criteria.Criterion in project raml-module-builder by folio-org.
the class PostgresClient method join.
/**
* run simple join queries between two tables
*
* for example, to generate the following query:
* SELECT c1.* , c2.* FROM univeristy.config_data c1
* INNER JOIN univeristy.config_data c2 ON ((c1.jsonb->>'code') = (c2.jsonb->'scope'->>'library_id'))
* WHERE (c2.jsonb->>'default')::boolean IS TRUE AND (c2.jsonb->>'default')::boolean IS TRUE
*
* Create a criteria representing a join column for each of the tables
* Create two JoinBy objects containing the:
* 1. The table to join from and to,
* 2. An alias for the tables,
* 3. The Fields to return
* 4. The column to join on (using the criteria object)
*
* @param JoinBy jb1= new JoinBy("config_data","c1",
* new Criteria().addField("'code'"), new String[]{"count(c1._id)"});
*
* @param JoinBy jb2= new JoinBy("config_data","c2",
* new Criteria().addField("'scope'").addField("'library_id'"), new String[]{"avg(length(c2.description))"});
*
* Passing "*" to the fields to return may be used as well (or a list of aliased column names)
*
* JoinBy jb1= new JoinBy("config_data","c1",
* new Criteria().addField("'code'"), new String[]{"*"});
*
* @param operation what operation to use when comparing the two columns. For example:
* setting this to equals would yeild something like:
*
* ((c1.jsonb->>'code') = (c2.jsonb->'scope'->>'library_id'))
*
* @param joinType - for example: INNER JOIN, LEFT JOIN,
* some prepared COnsts can be found: JoinBy.RIGHT_JOIN
*
* @param cr criterion to use to further filter results per table. can be used to also sort results
* new Criterion().setOrder(new Order("c2._id", ORDER.DESC))
* But can be used to create a more complex where clause if needed
*
* For example:
* GroupedCriterias gc = new GroupedCriterias();
* gc.addCriteria(new Criteria().setAlias("c2").addField("'default'")
* .setOperation(Criteria.OP_IS_TRUE));
* gc.addCriteria(new Criteria().setAlias("c2").addField("'enabled'")
* .setOperation(Criteria.OP_IS_TRUE) , "OR");
* gc.setGroupOp("AND");
*
* NOTE that to use sorting with a combination of functions - group by is needed - not currently implemented
*
* Criterion cr =
* new Criterion().addGroupOfCriterias(gc).addGroupOfCriterias(gc1).setOrder(new Order("c1._id", ORDER.DESC));
*/
public void join(JoinBy from, JoinBy to, String operation, String joinType, String cr, Class<?> returnedClass, boolean setId, Handler<AsyncResult<?>> replyHandler) {
long start = System.nanoTime();
client.getConnection(res -> {
if (res.succeeded()) {
SQLConnection connection = res.result();
try {
String select = "SELECT ";
StringBuffer joinon = new StringBuffer();
StringBuffer tables = new StringBuffer();
StringBuffer selectFields = new StringBuffer();
String filter = "";
if (cr != null) {
filter = cr;
}
String selectFromTable = from.getSelectFields();
String selectToTable = to.getSelectFields();
boolean addComma = false;
if (selectFromTable != null && selectFromTable.length() > 0) {
selectFields.append(from.getSelectFields());
addComma = true;
}
if (selectToTable != null && selectToTable.length() > 0) {
if (addComma) {
selectFields.append(",");
}
selectFields.append(to.getSelectFields());
}
tables.append(convertToPsqlStandard(tenantId) + "." + from.getTableName() + " " + from.getAlias() + " ");
joinon.append(joinType + " " + convertToPsqlStandard(tenantId) + "." + to.getTableName() + " " + to.getAlias() + " ");
String[] q = new String[] { select + selectFields.toString() + " FROM " + tables.toString() + joinon.toString() + new Criterion().addCriterion(from.getJoinColumn(), operation, to.getJoinColumn(), " AND ") + filter };
// TODO optimize query building
Map<String, String> replaceMapping = new HashMap<>();
replaceMapping.put("tenantId", convertToPsqlStandard(tenantId));
replaceMapping.put("query", org.apache.commons.lang.StringEscapeUtils.escapeSql(parseQuery(q[0]).getCountFuncQuery()));
StrSubstitutor sub = new StrSubstitutor(replaceMapping);
q[0] = select + sub.replace(countClauseTemplate) + q[0].replaceFirst(select, " ");
log.debug("query = " + q[0]);
connection.query(q[0], query -> {
connection.close();
if (query.failed()) {
log.error(query.cause().getMessage(), query.cause());
replyHandler.handle(Future.failedFuture(query.cause()));
} else {
if (returnedClass != null) {
replyHandler.handle(Future.succeededFuture(processResult(query.result(), returnedClass, true, setId)));
} else {
replyHandler.handle(Future.succeededFuture(query.result()));
}
}
long end = System.nanoTime();
StatsTracker.addStatElement(STATS_KEY + ".join", (end - start));
if (log.isDebugEnabled()) {
log.debug("timer: get " + q[0] + " (ns) " + (end - start));
}
});
} catch (Exception e) {
if (connection != null) {
connection.close();
}
log.error(e.getMessage(), e);
replyHandler.handle(Future.failedFuture(e));
}
} else {
log.error(res.cause().getMessage(), res.cause());
replyHandler.handle(Future.failedFuture(res.cause()));
}
});
}
use of org.folio.rest.persist.Criteria.Criterion in project mod-inventory-storage by folio-org.
the class LocationUnitAPI method deleteLocationUnitsInstitutionsById.
@Override
public void deleteLocationUnitsInstitutionsById(String id, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
Criterion criterion;
String tenantId = getTenant(okapiHeaders);
try {
Criteria criteria = new Criteria(INST_SCHEMA_PATH);
criteria.addField(ID_FIELD_NAME);
criteria.setOperation("=");
criteria.setValue(id);
criterion = new Criterion(criteria);
} catch (Exception e) {
String message = logAndSaveError(e);
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsInstitutionsByIdResponse.withPlainInternalServerError(message)));
return;
}
instInUse(id, tenantId, vertxContext).setHandler(res -> {
if (res.failed()) {
String message = logAndSaveError(res.cause());
LocationUnitsResource.DeleteLocationUnitsInstitutionsByIdResponse.withPlainInternalServerError(message);
} else {
if (res.result()) {
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsInstitutionsByIdResponse.withPlainBadRequest("Cannot delete institution, as it is in use")));
} else {
try {
PostgresClient.getInstance(vertxContext.owner(), tenantId).delete(INSTITUTION_TABLE, criterion, deleteReply -> {
if (deleteReply.failed()) {
logAndSaveError(deleteReply.cause());
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsInstitutionsByIdResponse.withPlainNotFound("Institution not found")));
} else {
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsInstitutionsByIdResponse.withNoContent()));
}
});
} catch (Exception e) {
String message = logAndSaveError(e);
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsInstitutionsByIdResponse.withPlainInternalServerError(message)));
}
}
}
});
}
use of org.folio.rest.persist.Criteria.Criterion in project mod-inventory-storage by folio-org.
the class LocationUnitAPI method deleteLocationUnitsCampusesById.
@Override
public void deleteLocationUnitsCampusesById(String id, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
String tenantId = getTenant(okapiHeaders);
Criterion criterion;
try {
Criteria criteria = new Criteria(CAMP_SCHEMA_PATH);
criteria.addField(ID_FIELD_NAME);
criteria.setOperation("=");
criteria.setValue(id);
criterion = new Criterion(criteria);
} catch (Exception e) {
String message = logAndSaveError(e);
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsCampusesByIdResponse.withPlainInternalServerError(message)));
return;
}
campInUse(id, tenantId, vertxContext).setHandler(res -> {
if (res.failed()) {
String message = logAndSaveError(res.cause());
LocationUnitsResource.DeleteLocationUnitsCampusesByIdResponse.withPlainInternalServerError(message);
} else {
if (res.result()) {
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsCampusesByIdResponse.withPlainBadRequest("Cannot delete campus, as it is in use")));
} else {
PostgresClient.getInstance(vertxContext.owner(), tenantId).delete(CAMPUS_TABLE, criterion, deleteReply -> {
if (deleteReply.failed()) {
logAndSaveError(deleteReply.cause());
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsCampusesByIdResponse.withPlainNotFound("Campus not found")));
} else {
asyncResultHandler.handle(Future.succeededFuture(LocationUnitsResource.DeleteLocationUnitsCampusesByIdResponse.withNoContent()));
}
});
}
}
});
}
Aggregations