List of usage examples for org.hibernate.criterion Restrictions lt
public static SimpleExpression lt(String propertyName, Object value)
From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java
License:Open Source License
/** * Generic OBCriteria.//w ww . j a va 2 s . c o m * * @param clazz * Class (entity). * @param values * Value. Property, value and operator. * @return One record that satisfies the conditions. */ public static <T extends BaseOBObject> T getOneInstance(Class<T> clazz, Value... values) { OBCriteria<T> obc = OBDal.getInstance().createCriteria(clazz); obc.setFilterOnReadableClients(false); obc.setFilterOnReadableOrganization(false); obc.add(Restrictions.ne(Client.PROPERTY_ID, "0")); for (Value value : values) { if (value.getValue() == null && "==".equals(value.getOperator())) { obc.add(Restrictions.isNull(value.getField())); } else if (value.getValue() == null && "!=".equals(value.getOperator())) { obc.add(Restrictions.isNotNull(value.getField())); } else if ("==".equals(value.getOperator())) { obc.add(Restrictions.eq(value.getField(), value.getValue())); } else if ("!=".equals(value.getOperator())) { obc.add(Restrictions.ne(value.getField(), value.getValue())); } else if ("<".equals(value.getOperator())) { obc.add(Restrictions.lt(value.getField(), value.getValue())); } else if (">".equals(value.getOperator())) { obc.add(Restrictions.gt(value.getField(), value.getValue())); } else if ("<=".equals(value.getOperator())) { obc.add(Restrictions.le(value.getField(), value.getValue())); } else if (">=".equals(value.getOperator())) { obc.add(Restrictions.ge(value.getField(), value.getValue())); } else { obc.add(Restrictions.eq(value.getField(), value.getValue())); } } final List<T> listt = obc.list(); if (listt != null && listt.size() > 0) { return listt.get(0); } else { return null; } }
From source file:org.openbravo.erpCommon.ad_actionButton.CreateWorkEffort.java
License:Open Source License
@Override public void execute(ProcessBundle bundle) throws Exception { final String strWorkRequirement = (String) bundle.getParams().get("MA_Workrequirement_ID"); final String strdate = (String) bundle.getParams().get("date"); String strStartTime = (String) bundle.getParams().get("starttime"); String strEndTime = (String) bundle.getParams().get("endtime"); final ConnectionProvider conn = bundle.getConnection(); final VariablesSecureApp vars = bundle.getContext().toVars(); try {/*from w ww .j a v a2 s .c om*/ // ConvertVariables String dateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("dateFormat.java"); SimpleDateFormat dateformater = new SimpleDateFormat(dateFormat); SimpleDateFormat dateTimeformater = new SimpleDateFormat("yyyy-MM-dd"); Date date = dateformater.parse(strdate); String dateformatTime = dateTimeformater.format(date); if (strStartTime == null || strStartTime.equals("")) { strStartTime = "00:00:00"; } if (strEndTime == null || strEndTime.equals("")) { strEndTime = "00:00:00"; } Timestamp starttime = Timestamp.valueOf(dateformatTime + " " + strStartTime + ".0"); Timestamp endtime = Timestamp.valueOf(dateformatTime + " " + strEndTime + ".0"); // Search Phases To Be Created WorkRequirement workReq = OBDal.getInstance().get(WorkRequirement.class, strWorkRequirement); OBCriteria<WorkRequirementOperation> workReqOpCriteria = OBDal.getInstance() .createCriteria(WorkRequirementOperation.class); workReqOpCriteria.add(Restrictions.eq(WorkRequirementOperation.PROPERTY_WORKREQUIREMENT, workReq)); workReqOpCriteria.add(Restrictions.le(WorkRequirementOperation.PROPERTY_STARTINGDATE, date)); workReqOpCriteria.add(Restrictions.eq(WorkRequirementOperation.PROPERTY_CLOSED, false)); workReqOpCriteria.addOrderBy(WorkRequirementOperation.PROPERTY_SEQUENCENUMBER, true); List<WorkRequirementOperation> workReqOpList = workReqOpCriteria.list(); int counter = 0; for (WorkRequirementOperation wrOp : workReqOpList) { // Check if exits one not processed; OBCriteria<ProductionPlan> productionPlanCriteria = OBDal.getInstance() .createCriteria(ProductionPlan.class); productionPlanCriteria.add(Restrictions.eq(ProductionPlan.PROPERTY_WRPHASE, wrOp)); productionPlanCriteria.createAlias(ProductionPlan.PROPERTY_PRODUCTION, "pro"); productionPlanCriteria .add(Restrictions.eq("pro." + ProductionTransaction.PROPERTY_MOVEMENTDATE, date)); productionPlanCriteria .add(Restrictions.eq("pro." + ProductionTransaction.PROPERTY_PROCESSED, false)); List<ProductionPlan> pplanList = productionPlanCriteria.list(); if (pplanList.isEmpty()) { counter++; // Create ProductionTransaction ProductionTransaction productionTransaction = OBProvider.getInstance() .get(ProductionTransaction.class); productionTransaction.setClient(wrOp.getClient()); productionTransaction.setOrganization(wrOp.getOrganization()); productionTransaction.setMovementDate(date); productionTransaction.setStartingTime(starttime); productionTransaction.setEndingTime(endtime); String documentNo = Utility.getDocumentNo(conn, wrOp.getClient().getId(), "M_Production", true); productionTransaction.setDocumentNo(documentNo); OBDal.getInstance().save(productionTransaction); OBDal.getInstance().flush(); // Crete ProductionPlan ProductionPlan productionPlan = OBProvider.getInstance().get(ProductionPlan.class); productionPlan.setProduction(productionTransaction); productionPlan.setOrganization(productionTransaction.getOrganization()); productionPlan.setClient(productionTransaction.getClient()); // Only one line per ProductionTransaction productionPlan.setLineNo(10L); productionPlan.setWRPhase(wrOp); productionPlan.setProductionplandate(date); productionPlan.setRunTime(0L); productionPlan.setClosephase(false); BigDecimal requeriedQty = wrOp.getQuantity().subtract(wrOp.getCompletedQuantity()); if (wrOp.isCreateStandards()) { productionPlan.setProductionQuantity(requeriedQty); BigDecimal estimatedTime = BigDecimal.ZERO; if (wrOp.getEstimatedTime() != null && wrOp.getQuantity() != null && wrOp.getQuantity().compareTo(BigDecimal.ZERO) != 0) { estimatedTime = wrOp.getEstimatedTime().multiply(requeriedQty) .divide(wrOp.getQuantity(), BigDecimal.ROUND_HALF_UP); } productionPlan.setEstimatedTime(new BigDecimal(estimatedTime.longValue())); } else { productionPlan.setProductionQuantity(BigDecimal.ZERO); productionPlan.setEstimatedTime(BigDecimal.ZERO); } productionPlan.setRejectedQuantity(BigDecimal.ZERO); productionPlan.setCostCenterUse(BigDecimal.ZERO); productionPlan.setStartingTime(starttime); productionPlan.setEndingTime(endtime); productionPlan.setRequiredQuantity(requeriedQty.longValue()); productionPlan.setProcessUnit(wrOp.getWorkRequirement().getProcessUnit()); if (wrOp.getWorkRequirement().getConversionRate() != null && wrOp.getWorkRequirement().getConversionRate().compareTo(BigDecimal.ZERO) != 0) { productionPlan.setConversionRate(wrOp.getWorkRequirement().getConversionRate()); } // Get CostCenterVersion OBCriteria<CostcenterVersion> costcenterVersionCriteria = OBDal.getInstance() .createCriteria(CostcenterVersion.class); costcenterVersionCriteria.add(Restrictions.eq(CostcenterVersion.PROPERTY_COSTCENTER, wrOp.getActivity().getCostCenter())); costcenterVersionCriteria.add(Restrictions.lt(CostcenterVersion.PROPERTY_VALIDFROMDATE, date)); costcenterVersionCriteria.addOrderBy(CostcenterVersion.PROPERTY_VALIDFROMDATE, false); List<CostcenterVersion> costcenterVersionList = costcenterVersionCriteria.list(); if (!costcenterVersionList.isEmpty()) { productionPlan.setCostCenterVersion(costcenterVersionList.get(0)); } productionPlan.setOutsourced((wrOp.isOutsourced() == null) ? false : wrOp.isOutsourced()); OBDal.getInstance().save(productionPlan); OBDal.getInstance().flush(); if (wrOp.isCreateStandards()) { String strProcessId = "FF80818132A4F6AD0132A573DD7A0021"; HashMap<String, Object> params = new HashMap<String, Object>(); params.put("M_ProductionPlan_ID", productionPlan.getId()); ProcessBundle pb = new ProcessBundle(strProcessId, vars).init(conn); pb.setParams(params); new org.openbravo.erpCommon.ad_actionButton.CreateStandards().execute(pb); OBError pbResult = (OBError) pb.getResult(); if (!pbResult.getType().equals("Success")) { throw new OBException(pbResult.getMessage()); } } } } final OBError msg = new OBError(); msg.setType("Success"); msg.setTitle(Utility.messageBD(conn, "Success", bundle.getContext().getLanguage())); msg.setMessage(counter + " " + Utility.messageBD(conn, "WorkEffortCreated", bundle.getContext().getLanguage()) + strdate); bundle.setResult(msg); } catch (final Exception e) { OBDal.getInstance().rollbackAndClose(); log4j.error("Error creating work effort", e); final OBError msg = new OBError(); msg.setType("Error"); if (e instanceof org.hibernate.exception.GenericJDBCException) { msg.setMessage(((org.hibernate.exception.GenericJDBCException) e).getSQLException() .getNextException().getMessage()); } else if (e instanceof org.hibernate.exception.ConstraintViolationException) { msg.setMessage(((org.hibernate.exception.ConstraintViolationException) e).getSQLException() .getNextException().getMessage()); } else { msg.setMessage(e.getMessage()); } msg.setTitle(Utility.messageBD(conn, "Error", bundle.getContext().getLanguage())); bundle.setResult(msg); } }
From source file:org.openbravo.erpCommon.obps.ActivationKey.java
License:Open Source License
/** * Looks for all active sessions that have not had activity during last * {@link ActivationKey#PING_TIMEOUT_SECS} seconds and deactivates them. Activity is tracked by * the requests the browser sends to look for alerts (see * {@link org.openbravo.erpCommon.utility.VerticalMenu}). * <p/>//w w w . j a va 2s. c om * PING_TIMEOUT_SECS is hardcoded to 120s, pings are hardcoded in front-end to 50s. */ private boolean deactivateTimeOutSessions(String currentSessionId) { // Last valid ping time is current time substract timeout seconds Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, (-1) * PING_TIMEOUT_SECS); Date lastValidPingTime = new Date(cal.getTimeInMillis()); OBCriteria<Session> obCriteria = OBDal.getInstance().createCriteria(Session.class); // sesion_active='Y' and (lastPing is null or lastPing<lastValidPing) obCriteria.add(Restrictions.and(Restrictions.eq(Session.PROPERTY_SESSIONACTIVE, true), Restrictions.or(Restrictions.isNull(Session.PROPERTY_LASTPING), Restrictions.lt(Session.PROPERTY_LASTPING, lastValidPingTime)))); obCriteria.add(Restrictions.in(Session.PROPERTY_LOGINSTATUS, ACTIVE_SESSION_TYPES)); obCriteria.add(Restrictions.ne(Session.PROPERTY_ID, currentSessionId)); boolean sessionDeactivated = false; for (Session expiredSession : obCriteria.list()) { expiredSession.setSessionActive(false); sessionDeactivated = true; log4j.info("Deactivated session: " + expiredSession.getId() + " beacuse of ping time out. Last ping: " + expiredSession.getLastPing() + ". Last valid ping time: " + lastValidPingTime); } if (sessionDeactivated) { OBDal.getInstance().flush(); } else { log4j.debug("No ping timeout sessions"); } return sessionDeactivated; }
From source file:org.openbravo.erpCommon.ReportsUtility.java
License:Open Source License
public static BigDecimal getBeginningBalance(String orgId, String acctSchemaId, String bpartnerId, String dateFrom, boolean isCustomer) { if (dateFrom == null || "".equals(dateFrom)) { return BigDecimal.ZERO; }//from w ww. j a va2 s.c o m OBCriteria<AccountingFact> obc = OBDal.getInstance().createCriteria(AccountingFact.class); obc.add(Restrictions.eq(AccountingFact.PROPERTY_ACCOUNTINGSCHEMA, OBDal.getInstance().get(AcctSchema.class, acctSchemaId))); obc.add(Restrictions.eq(AccountingFact.PROPERTY_BUSINESSPARTNER, OBDal.getInstance().get(BusinessPartner.class, bpartnerId))); obc.add(Restrictions.in(AccountingFact.PROPERTY_ORGANIZATION, getOrgList(orgId))); try { obc.add(Restrictions.lt(AccountingFact.PROPERTY_ACCOUNTINGDATE, OBDateUtils.getDate(dateFrom))); } catch (ParseException pe) { // do nothing } if (isCustomer) { obc.add(Restrictions.in(AccountingFact.PROPERTY_ACCOUNT, getValidAccountsList(acctSchemaId, bpartnerId))); } else { obc.add(Restrictions.in(AccountingFact.PROPERTY_ACCOUNT, getValidAccountsListVendor(acctSchemaId, bpartnerId))); } obc.setFilterOnReadableOrganization(false); ProjectionList projections = Projections.projectionList(); projections.add(Projections.sum(AccountingFact.PROPERTY_DEBIT)); projections.add(Projections.sum(AccountingFact.PROPERTY_CREDIT)); obc.setProjection(projections); @SuppressWarnings("rawtypes") List o = obc.list(); if (o != null && o.size() > 0) { Object[] resultSet = (Object[]) o.get(0); BigDecimal debit = (resultSet[0] != null) ? (BigDecimal) resultSet[0] : BigDecimal.ZERO; BigDecimal credit = (resultSet[1] != null) ? (BigDecimal) resultSet[1] : BigDecimal.ZERO; return debit.subtract(credit); } return BigDecimal.ZERO; }
From source file:org.openfaces.component.filter.HibernateCriterionBuilder.java
License:LGPL
private static Criterion convertToHibernateCriteria(final ExpressionFilterCriterion expressionFilterCriterion) { final String property = expressionFilterCriterion.getExpressionStr(); final Object parameter = expressionFilterCriterion.getArg1(); FilterCondition condition = expressionFilterCriterion.getCondition(); Criterion result = condition.process(new FilterConditionProcessor<Criterion>() { @Override/*from w w w.j ava 2 s. com*/ public Criterion processEmpty() { return Restrictions.isNull(property); } @Override public Criterion processEquals() { if (parameter == null) { return Restrictions.isNull(property); } if (parameter instanceof Date) { TimeZone timeZone = (TimeZone) expressionFilterCriterion.getParameters().get("timeZone"); Date dayStart = ParametersInterpreter.dayStart((Date) parameter, timeZone); Date dayEnd = ParametersInterpreter.dayEnd((Date) parameter, timeZone); return Restrictions.and(Restrictions.ge(property, dayStart), Restrictions.le(property, dayEnd)); } else if (parameter instanceof String) { boolean caseSensitive = expressionFilterCriterion.isCaseSensitive(); if (!caseSensitive) { return Restrictions.like(property, parameter.toString().toLowerCase()).ignoreCase(); } else { return Restrictions.like(property, parameter); } } else { return Restrictions.eq(property, parameter); } } @Override public Criterion processContains() { boolean caseSensitive = expressionFilterCriterion.isCaseSensitive(); if (!caseSensitive) { return Restrictions.like(property, "%" + parameter.toString().toLowerCase() + "%").ignoreCase(); } else { return Restrictions.like(property, "%" + parameter + "%"); } } @Override public Criterion processBegins() { boolean caseSensitive = expressionFilterCriterion.isCaseSensitive(); if (!caseSensitive) { return Restrictions.like(property, parameter.toString().toLowerCase() + "%").ignoreCase(); } else { return Restrictions.like(property, parameter + "%"); } } @Override public Criterion processEnds() { boolean caseSensitive = expressionFilterCriterion.isCaseSensitive(); if (!caseSensitive) { return Restrictions.like(property, "%" + parameter.toString().toLowerCase()).ignoreCase(); } else { return Restrictions.like(property, "%" + parameter); } } @Override public Criterion processLess() { Object correctedParameter = parameter; if (parameter instanceof Date) { TimeZone timeZone = (TimeZone) expressionFilterCriterion.getParameters().get("timeZone"); correctedParameter = ParametersInterpreter.dayStart((Date) parameter, timeZone); } return Restrictions.lt(property, correctedParameter); } @Override public Criterion processGreater() { Object correctedParameter = parameter; if (parameter instanceof Date) { TimeZone timeZone = (TimeZone) expressionFilterCriterion.getParameters().get("timeZone"); correctedParameter = ParametersInterpreter.dayEnd((Date) parameter, timeZone); } return Restrictions.gt(property, correctedParameter); } @Override public Criterion processLessOrEqual() { Object correctedParameter = parameter; if (parameter instanceof Date) { TimeZone timeZone = (TimeZone) expressionFilterCriterion.getParameters().get("timeZone"); correctedParameter = ParametersInterpreter.dayEnd((Date) parameter, timeZone); } return Restrictions.le(property, correctedParameter); } @Override public Criterion processGreaterOrEqual() { Object correctedParameter = parameter; if (parameter instanceof Date) { TimeZone timeZone = (TimeZone) expressionFilterCriterion.getParameters().get("timeZone"); correctedParameter = ParametersInterpreter.dayStart((Date) parameter, timeZone); } return Restrictions.ge(property, correctedParameter); } @Override public Criterion processBetween() { Object parameter2 = expressionFilterCriterion.getArg2(); if (parameter instanceof Date && parameter2 instanceof Date) { TimeZone timeZone = (TimeZone) expressionFilterCriterion.getParameters().get("timeZone"); Date periodStart = ParametersInterpreter.dayStart((Date) parameter, timeZone); Date periodEnd = ParametersInterpreter.dayEnd((Date) parameter2, timeZone); return Restrictions.and(Restrictions.ge(property, periodStart), Restrictions.le(property, periodEnd)); } else { return Restrictions.between(property, parameter, parameter2); } } }); if (parameter != null) { result = Restrictions.and(Restrictions.isNotNull(property), result); } return (expressionFilterCriterion.isInverse()) ? Restrictions.not(result) : result; }
From source file:org.openhealthtools.openatna.audit.persistence.dao.hibernate.HibernateQueryBuilder.java
License:Apache License
private Criterion createConditional(CriteriaNode root, CriteriaNode node, Query.ConditionalStatement value, String name) {//from ww w . jav a 2s . c o m Criteria c = node.getCriteria(); Query.Conditional con = value.getConditional(); Object val = value.getValue(); Criterion cron = null; switch (con) { case MAX_NUM: idCriteria.setMaxResults((Integer) val); break; case START_OFFSET: idCriteria.setFirstResult((Integer) val); break; case AFTER: cron = Restrictions.ge(name, val); break; case BEFORE: cron = Restrictions.le(name, val); break; case CASE_INSENSITIVE_LIKE: cron = Restrictions.ilike(name, val); break; case EQUALS: cron = Restrictions.eq(name, val); break; case GREATER_THAN: cron = Restrictions.gt(name, val); break; case GREATER_THAN_OR_EQUAL: cron = Restrictions.ge(name, val); break; case LESS_THAN: cron = Restrictions.lt(name, val); break; case LESS_THAN_OR_EQUAL: cron = Restrictions.le(name, val); break; case LIKE: cron = Restrictions.like(name, val); break; case NOT_EQUAL: cron = Restrictions.ne(name, val); break; case OR: processJoint(root, value, false); break; case AND: processJoint(root, value, true); break; case NULLITY: Boolean b = (Boolean) val; cron = b ? Restrictions.isNull(name) : Restrictions.isNotNull(name); break; case ASC: messageCriteria.addOrder(Order.asc((String) val)); break; case DESC: messageCriteria.addOrder(Order.desc((String) val)); break; default: break; } if (cron != null && c != null) { c.add(cron); } return cron; }
From source file:org.openmrs.api.db.hibernate.HibernateConceptDAO.java
License:Mozilla Public License
/** * @see org.openmrs.api.db.ConceptDAO#getPrevConcept(org.openmrs.Concept) *//* www . ja v a2 s . c o m*/ @SuppressWarnings("unchecked") public Concept getPrevConcept(Concept c) { Integer i = c.getConceptId(); List<Concept> concepts = sessionFactory.getCurrentSession().createCriteria(Concept.class) .add(Restrictions.lt("conceptId", i)).addOrder(Order.desc("conceptId")).setFetchSize(1).list(); if (concepts.size() < 1) { return null; } return concepts.get(0); }
From source file:org.openmrs.hl7.db.hibernate.HibernateHL7DAO.java
License:Mozilla Public License
/** * @see org.openmrs.hl7.db.HL7DAO#getHL7InArchivesToMigrate() *//*from w w w.ja v a 2s. com*/ @Override @SuppressWarnings("unchecked") public List<HL7InArchive> getHL7InArchivesToMigrate() { Integer daysToKeep = Hl7InArchivesMigrateThread.getDaysKept(); Criteria crit = getHL7SearchCriteria(HL7InArchive.class, HL7Constants.HL7_STATUS_PROCESSED, null); crit.setMaxResults(HL7Constants.MIGRATION_MAX_BATCH_SIZE); if (daysToKeep != null) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1 * daysToKeep); crit.add(Restrictions.lt("dateCreated", cal.getTime())); } return crit.list(); }
From source file:org.openmrs.logic.db.hibernate.HibernateLogicEncounterDAO.java
License:Open Source License
/** * Convenience method to get the list of hibernate queries for this expression * //from ww w . j av a2s . c om * @param logicExpression * @param indexDate * @param criteria Criteria object so that certain expressions can add aliases, etc * @return Criterion to be added to the Criteria */ public Criterion getCriterion(LogicExpression logicExpression, Date indexDate, Criteria criteria) { Operator operator = logicExpression.getOperator(); Object rightOperand = logicExpression.getRightOperand(); Object leftOperand = null; if (logicExpression instanceof LogicExpressionBinary) { leftOperand = ((LogicExpressionBinary) logicExpression).getLeftOperand(); } List<Criterion> criterion = new ArrayList<Criterion>(); //if the leftOperand is a String and does not match any components, //see if it is a concept name and restrict accordingly //a null operator implies a concept restriction if (leftOperand instanceof LogicExpression) { // no restrictions if there is no operator // TODO restrict on provider != null for encounterProvider token? } String token = logicExpression.getRootToken(); if (operator == null) { // no restrictions if there is no operator // TODO restrict on provider != null for encounterProvider token? } else if (operator == Operator.BEFORE || operator == Operator.LT) { if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) { criterion.add(Restrictions.lt("encounterDatetime", rightOperand)); } else { throw new LogicException("'before' is not a valid operator on " + token + " and " + rightOperand); } } else if (operator == Operator.AFTER || operator == Operator.GT) { if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) { criterion.add(Restrictions.gt("encounterDatetime", rightOperand)); } else { throw new LogicException("'after' is not a valid operator on " + token + " and " + rightOperand); } } else if (operator == Operator.AND || operator == Operator.OR) { if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) { Criterion leftCriteria = null; Criterion rightCriteria = null; if (leftOperand instanceof LogicExpression) { leftCriteria = this.getCriterion((LogicExpression) leftOperand, indexDate, criteria); } if (rightOperand instanceof LogicExpression) { rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria); } if (leftCriteria != null && rightCriteria != null) { if (operator == Operator.AND) { criterion.add(Restrictions.and(leftCriteria, rightCriteria)); } if (operator == Operator.OR) { criterion.add(Restrictions.or(leftCriteria, rightCriteria)); } } } else { throw new LogicException("'and/or' are not valid operators on " + token + " and " + rightOperand); } } else if (operator == Operator.NOT) { Criterion rightCriteria = null; if (rightOperand instanceof LogicExpression) { rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria); } if (rightCriteria != null) { criterion.add(Restrictions.not(rightCriteria)); } } else if (operator == Operator.CONTAINS) { if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) { criteria.createAlias("encounterType", "encounterType"); criterion.add(Expression.eq("encounterType.name", ((OperandText) rightOperand).asString())); } else if (LOCATION_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) { criteria.createAlias("location", "location"); criterion.add(Restrictions.eq("location.name", ((OperandText) rightOperand).asString())); } else if (PROVIDER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandNumeric) { criteria.createAlias("provider", "provider"); criterion.add(Restrictions.eq("provider.personId", ((OperandNumeric) rightOperand).asInteger())); } else { throw new LogicException("'contains' is not a valid operator on " + token + " and " + rightOperand); } } else if (operator == Operator.IN) { if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandCollection) { criteria.createAlias("encounterType", "encounterType"); criterion.add( Expression.in("encounterType.name", ((OperandCollection) rightOperand).asCollection())); } else if (LOCATION_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandCollection) { criteria.createAlias("location", "location"); criterion.add(Restrictions.in("location.name", ((OperandCollection) rightOperand).asCollection())); } else if (PROVIDER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandCollection) { criteria.createAlias("provider", "provider"); criterion.add( Restrictions.in("provider.systemId", ((OperandCollection) rightOperand).asCollection())); } else { throw new LogicException("'in' is not a valid operator on " + token + " and " + rightOperand); } } else if (operator == Operator.EQUALS) { if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandDate) { criterion.add(Restrictions.eq("encounterDatetime", rightOperand)); } else if (ENCOUNTER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) { criteria.createAlias("encounterType", "encounterType"); criterion.add(Restrictions.eq("encounterType.name", ((OperandText) rightOperand).asString())); } else if (LOCATION_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) { criteria.createAlias("location", "location"); criterion.add(Restrictions.eq("location.name", ((OperandText) rightOperand).asString())); } else if (PROVIDER_KEY.equalsIgnoreCase(token) && rightOperand instanceof OperandText) { criteria.createAlias("provider", "provider"); criterion.add(Restrictions.eq("provider.systemId", ((OperandText) rightOperand).asString())); } else { throw new LogicException("'equals' is not a valid operator on " + token + " and " + rightOperand); } } else if (operator == Operator.LTE) { if (rightOperand instanceof OperandDate) criterion.add(Restrictions.le("encounterDatetime", rightOperand)); else throw new LogicException( "'less than or equals' is not a valid operator on " + token + " and " + rightOperand); } else if (operator == Operator.GTE) { if (rightOperand instanceof OperandDate) criterion.add(Restrictions.ge("encounterDatetime", rightOperand)); else throw new LogicException( "'greater than or equals' is not a valid operator on " + token + " and " + rightOperand); } else if (operator == Operator.LT) { if (rightOperand instanceof OperandDate) criterion.add(Restrictions.lt("encounterDatetime", rightOperand)); else throw new LogicException( "'less than' is not a valid operator on " + token + " and " + rightOperand); } else if (operator == Operator.GT) { if (rightOperand instanceof OperandDate) criterion.add(Restrictions.gt("encounterDatetime", rightOperand)); else throw new LogicException( "'greater than' is not a valid operator on " + token + " and " + rightOperand); } else if (operator == Operator.EXISTS) { // EXISTS can be handled on the higher level (above // LogicService, even) by coercing the Result into a Boolean for // each patient } else if (operator == Operator.ASOF && rightOperand instanceof Date) { indexDate = (Date) rightOperand; criterion.add(Restrictions.le("encounterDatetime", indexDate)); } else if (operator == Operator.WITHIN) { if (rightOperand instanceof Duration) { Duration duration = (Duration) rightOperand; Calendar within = Calendar.getInstance(); within.setTime(indexDate); if (duration.getUnits() == Duration.Units.YEARS) { within.add(Calendar.YEAR, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.MONTHS) { within.add(Calendar.MONTH, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.WEEKS) { within.add(Calendar.WEEK_OF_YEAR, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.DAYS) { within.add(Calendar.DAY_OF_YEAR, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.HOURS) { within.add(Calendar.HOUR_OF_DAY, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.MINUTES) { within.add(Calendar.MINUTE, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.SECONDS) { within.add(Calendar.SECOND, duration.getDuration().intValue()); } if (indexDate.compareTo(within.getTime()) > 0) { criterion.add(Restrictions.between("encounterDatetime", within.getTime(), indexDate)); } else { criterion.add(Restrictions.between("encounterDatetime", indexDate, within.getTime())); } } else { throw new LogicException("'within' is not a valid operator on " + token + " and " + rightOperand); } } Criterion c = null; for (Criterion crit : criterion) { if (c == null) { c = crit; } else { c = Restrictions.and(c, crit); } } return c; }
From source file:org.openmrs.logic.db.hibernate.HibernateLogicObsDAO.java
License:Open Source License
public Criterion getCriterion(LogicExpression logicExpression, Date indexDate, Criteria criteria) { Operator operator = logicExpression.getOperator(); Operand rightOperand = logicExpression.getRightOperand(); Operand leftOperand = null;// ww w .j a v a2 s. c o m if (logicExpression instanceof LogicExpressionBinary) { leftOperand = ((LogicExpressionBinary) logicExpression).getLeftOperand(); } List<Criterion> criterion = new ArrayList<Criterion>(); //the root token can be a concept name for the obs datasource String rootToken = logicExpression.getRootToken(); Concept concept = getConceptForToken(rootToken); if (concept != null) { criterion.add(Restrictions.eq("concept", concept)); } else { if (rootToken != null && (rootToken.equalsIgnoreCase(COMPONENT_ENCOUNTER_ID) || rootToken.equalsIgnoreCase(COMPONENT_OBS_DATETIME))) { //this is a component not a concept so it is fine } else { throw new LogicException("Concept: " + rootToken + " does not exist"); } } if (operator == Operator.BEFORE) { criterion.add(Restrictions.lt("obsDatetime", rightOperand)); } else if (operator == Operator.AFTER) { criterion.add(Restrictions.gt("obsDatetime", rightOperand)); } else if (operator == Operator.AND || operator == Operator.OR) { Criterion leftCriteria = null; Criterion rightCriteria = null; if (leftOperand instanceof LogicExpression) { leftCriteria = this.getCriterion((LogicExpression) leftOperand, indexDate, criteria); } if (rightOperand instanceof LogicExpression) { rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria); } if (leftCriteria != null && rightCriteria != null) { if (operator == Operator.AND) { criterion.add(Restrictions.and(leftCriteria, rightCriteria)); } if (operator == Operator.OR) { criterion.add(Restrictions.or(leftCriteria, rightCriteria)); } } } else if (operator == Operator.NOT) { Criterion rightCriteria = null; if (rightOperand instanceof LogicExpression) { rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria); } if (rightCriteria != null) { criterion.add(Restrictions.not(rightCriteria)); } } else if (operator == Operator.CONTAINS) { // used with PROBLEM ADDED concept, to retrieve the "ANSWERED // BY" concept, stashed inside the concept's valueCoded member // variable. for example: // new LogicCriteria("PROBLEM ADDED").contains("HIV INFECTED"); if (rightOperand instanceof OperandNumeric) { concept = Context.getConceptService().getConcept(((OperandNumeric) rightOperand).asInteger()); criterion.add(Restrictions.eq("valueCoded", concept)); } else if (rightOperand instanceof OperandText) { concept = Context.getConceptService().getConcept((String) ((OperandText) rightOperand).asString()); criterion.add(Restrictions.eq("valueCoded", concept)); } else if (rightOperand instanceof OperandConcept) { criterion.add(Restrictions.eq("valueCoded", ((OperandConcept) rightOperand).asConcept())); } else log.error("Invalid operand value for CONTAINS operation"); } else if (operator == Operator.IN) { log.error("Invalid operand value for IN operation"); } else if (operator == Operator.EQUALS) { if (rightOperand instanceof OperandNumeric) { if (rootToken.equalsIgnoreCase(COMPONENT_ENCOUNTER_ID)) { EncounterService encounterService = Context.getEncounterService(); Encounter encounter = encounterService .getEncounter(((OperandNumeric) rightOperand).asInteger()); criterion.add(Restrictions.eq("encounter", encounter)); } else criterion.add(Restrictions.eq("valueNumeric", ((OperandNumeric) rightOperand).asDouble())); } else if (rightOperand instanceof OperandText) criterion.add(Restrictions.eq("valueText", ((OperandText) rightOperand).asString())); else if (rightOperand instanceof OperandDate) if (leftOperand instanceof OperandText && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) { criterion.add(Restrictions.eq(COMPONENT_OBS_DATETIME, rightOperand)); } else { criterion.add(Restrictions.eq("valueDatetime", rightOperand)); } else if (rightOperand instanceof OperandConcept) criterion.add(Restrictions.eq("valueCoded", ((OperandConcept) rightOperand).asConcept())); else log.error("Invalid operand value for EQUALS operation"); } else if (operator == Operator.LTE) { if (rightOperand instanceof OperandNumeric) criterion.add(Restrictions.le("valueNumeric", ((OperandNumeric) rightOperand).asDouble())); else if (rightOperand instanceof OperandDate) if (leftOperand instanceof OperandText && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) { criterion.add(Restrictions.le(COMPONENT_OBS_DATETIME, rightOperand)); } else { criterion.add(Restrictions.le("valueDatetime", rightOperand)); } else log.error("Invalid operand value for LESS THAN EQUAL operation"); } else if (operator == Operator.GTE) { if (rightOperand instanceof OperandNumeric) criterion.add(Restrictions.ge("valueNumeric", ((OperandNumeric) rightOperand).asDouble())); else if (rightOperand instanceof OperandDate) if (leftOperand instanceof OperandText && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) { criterion.add(Restrictions.ge(COMPONENT_OBS_DATETIME, rightOperand)); } else { criterion.add(Restrictions.ge("valueDatetime", rightOperand)); } else log.error("Invalid operand value for GREATER THAN EQUAL operation"); } else if (operator == Operator.LT) { if (rightOperand instanceof OperandNumeric) criterion.add(Restrictions.lt("valueNumeric", ((OperandNumeric) rightOperand).asDouble())); else if (rightOperand instanceof OperandDate) if (leftOperand instanceof OperandText && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) { criterion.add(Restrictions.lt(COMPONENT_OBS_DATETIME, rightOperand)); } else { criterion.add(Restrictions.lt("valueDatetime", rightOperand)); } else log.error("Invalid operand value for LESS THAN operation"); } else if (operator == Operator.GT) { if (rightOperand instanceof OperandNumeric) criterion.add(Restrictions.gt("valueNumeric", ((OperandNumeric) rightOperand).asDouble())); else if (rightOperand instanceof OperandDate) if (leftOperand instanceof OperandText && ((OperandText) leftOperand).asString().equals(COMPONENT_OBS_DATETIME)) { criterion.add(Restrictions.gt(COMPONENT_OBS_DATETIME, rightOperand)); } else { criterion.add(Restrictions.gt("valueDatetime", rightOperand)); } else log.error("Invalid operand value for GREATER THAN operation"); } else if (operator == Operator.EXISTS) { // EXISTS can be handled on the higher level (above // LogicService, even) by coercing the Result into a Boolean for // each patient } else if (operator == Operator.ASOF && rightOperand instanceof OperandDate) { indexDate = (Date) rightOperand; criterion.add(Restrictions.le("obsDatetime", indexDate)); } else if (operator == Operator.WITHIN && rightOperand instanceof Duration) { Duration duration = (Duration) rightOperand; Calendar within = Calendar.getInstance(); within.setTime(indexDate); if (duration.getUnits() == Duration.Units.YEARS) { within.add(Calendar.YEAR, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.MONTHS) { within.add(Calendar.MONTH, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.WEEKS) { within.add(Calendar.WEEK_OF_YEAR, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.DAYS) { within.add(Calendar.DAY_OF_YEAR, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.HOURS) { within.add(Calendar.HOUR_OF_DAY, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.MINUTES) { within.add(Calendar.MINUTE, duration.getDuration().intValue()); } else if (duration.getUnits() == Duration.Units.SECONDS) { within.add(Calendar.SECOND, duration.getDuration().intValue()); } if (indexDate.compareTo(within.getTime()) > 0) { criterion.add(Restrictions.between("obsDatetime", within.getTime(), indexDate)); } else { criterion.add(Restrictions.between("obsDatetime", indexDate, within.getTime())); } } Criterion c = null; for (Criterion crit : criterion) { if (c == null) { c = crit; } else { c = Restrictions.and(c, crit); } } return c; }