Example usage for org.hibernate.criterion Restrictions not

List of usage examples for org.hibernate.criterion Restrictions not

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions not.

Prototype

public static Criterion not(Criterion expression) 

Source Link

Document

Return the negation of an expression

Usage

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  .ja va2s  .  c o  m*/
        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.openmrs.api.db.hibernate.HibernateProviderDAO.java

License:Mozilla Public License

/**
 * @see org.openmrs.api.db.ProviderDAO#getProviderByIdentifier(java.lang.String)
 *//* w  ww . j a v a  2 s.  c  o  m*/
@Override
public boolean isProviderIdentifierUnique(Provider provider) throws DAOException {

    Criteria criteria = getSession().createCriteria(Provider.class);
    criteria.add(Restrictions.eq("identifier", provider.getIdentifier()));
    if (provider.getProviderId() != null) {
        criteria.add(Restrictions.not(Restrictions.eq("providerId", provider.getProviderId())));
    }
    criteria.setProjection(Projections.countDistinct("providerId"));

    return (Long) criteria.uniqueResult() == 0L;
}

From source file:org.openmrs.api.db.hibernate.PatientSearchCriteria.java

License:Mozilla Public License

/**
 * @param query defines search parameters
 * @param matchExactly// w  w  w.j  a  v  a 2  s  .  com
 * @param orderByNames
 * @param includeVoided true/false whether or not to included voided patients
 * @return criteria for searching by name OR identifier OR searchable attributes
 */
Criteria prepareCriteria(String query, Boolean matchExactly, boolean orderByNames, boolean includeVoided) {
    addAliasForName(criteria, orderByNames);

    if (matchExactly == null) {
        criteria.add(Restrictions.conjunction().add(prepareCriterionForName(query, null, includeVoided))
                .add(Restrictions.not(prepareCriterionForName(query, true, includeVoided)))
                .add(Restrictions.not(prepareCriterionForName(query, false, includeVoided))));
    } else if (!matchExactly) {
        criteria.add(prepareCriterionForName(query, false, includeVoided));
    } else {
        personSearchCriteria.addAliasForAttribute(criteria);
        addAliasForIdentifiers(criteria);

        criteria.add(Restrictions.disjunction().add(prepareCriterionForName(query, true, includeVoided))
                .add(prepareCriterionForAttribute(query, includeVoided)).add(prepareCriterionForIdentifier(
                        query, new ArrayList<PatientIdentifierType>(), false, includeVoided)));
    }

    if (!includeVoided) {
        criteria.add(Restrictions.eq("voided", false));
    }
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    log.debug(criteria.toString());

    return criteria;
}

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 w w w .j  a  va2s  . c o m
 * @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  . ja va2  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;
}

From source file:org.openmrs.logic.util.LogicExpressionToCriterion.java

License:Open Source License

public List<Criterion> evaluateNot(String leftItem, Operand leftOperand, Operand rightOperand,
        Operator operator, Date indexDate, List<Criterion> c, Criteria criteria) throws LogicException {

    Criterion rightCriteria = null;//from   w  ww .j a  va2  s . c  o  m
    if (rightOperand instanceof LogicExpression) {
        rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate, criteria);
    }
    if (rightCriteria != null) {
        nullSafeCriterionAdd(c, Restrictions.not(rightCriteria));
    }
    return c;
}

From source file:org.openmrs.module.clinicalsummary.db.hibernate.HibernateUtilDAO.java

License:Open Source License

/**
 * @see UtilDAO#getOrderedObs(java.util.Map, java.util.Date, java.util.Date)
 *///from  w w w . j a  v  a  2 s.  c om
@Override
@SuppressWarnings("unchecked")
public List<Object[]> aggregateOrderedObs(final Map<String, Collection<OpenmrsObject>> restrictions,
        final Collection<String> groupingProperties, final StatusType statusType, final Date startTime,
        final Date endTime) throws DAOException {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(OrderedObs.class);

    // hack to prevent results for tests ordered concept when grouping results on concept
    if (groupingProperties.contains("concept"))
        criteria.add(Restrictions
                .not(Restrictions.eq("concept", CacheUtils.getConcept(EvaluableNameConstants.TESTS_ORDERED))));

    if (MapUtils.isNotEmpty(restrictions)) {
        OrderedObs orderedObs = new OrderedObs();
        for (String property : restrictions.keySet()) {
            Collection<OpenmrsObject> objects = restrictions.get(property);
            if (CollectionUtils.isNotEmpty(objects) && PropertyUtils.isReadable(orderedObs, property))
                criteria.add(Restrictions.in(property, objects));
        }
    }

    if (statusType != null)
        criteria.add(Restrictions.eq("status", statusType));

    if (startTime != null)
        criteria.add(Restrictions.ge("orderedDatetime", startTime));

    if (endTime != null)
        criteria.add(Restrictions.le("orderedDatetime", endTime));

    ProjectionList projectionList = Projections.projectionList();
    for (String groupingProperty : groupingProperties) {
        // group by the property and order by the same property desc and the property must not null
        criteria.add(Restrictions.isNotNull(groupingProperty));
        projectionList.add(Projections.groupProperty(groupingProperty));
        criteria.addOrder(Order.asc(groupingProperty));
    }
    // add the row count projection to the projection list
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);

    return criteria.list();
}

From source file:org.openmrs.module.emr.reporting.cohort.definition.evaluator.DiagnosisCohortDefinitionEvaluator.java

License:Open Source License

@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context)
        throws EvaluationException {
    DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();

    DiagnosisCohortDefinition cd = (DiagnosisCohortDefinition) cohortDefinition;

    if (cd.isIncludeAllCodedDiagnoses() && cd.getCodedDiagnoses() != null) {
        throw new IllegalArgumentException(
                "Cannot specify both includeAllCodedDiagnoses, and specific coded diagnoses");
    }/*from  w  w  w .j  a  va2 s .co  m*/

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Obs.class, "obsgroup");
    crit.setProjection(Projections.distinct(Projections.property("person.id")));

    crit.add(Restrictions.eq("voided", false));
    crit.createCriteria("person").add(Restrictions.eq("voided", false));

    // we're looking for an obs group whose grouping concept is VISIT DIAGNOSES (or the equivalent)
    crit.add(Restrictions.eq("concept", dmd.getDiagnosisSetConcept()));

    if (cd.getOnOrAfter() != null) {
        crit.add(Restrictions.ge("obsDatetime", cd.getOnOrAfter()));
    }
    if (cd.getOnOrBefore() != null) {
        crit.add(Restrictions.le("obsDatetime", DateUtil.getEndOfDayIfTimeExcluded(cd.getOnOrBefore())));
    }

    if (cd.getDiagnosisOrder() != null) {
        DetachedCriteria orderClause = DetachedCriteria.forClass(Obs.class, "orderObs");
        orderClause.add(Restrictions.eq("voided", false));
        orderClause.add(Restrictions.eq("concept", dmd.getDiagnosisOrderConcept()));
        orderClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getDiagnosisOrder())));
        orderClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        orderClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(orderClause));
    }

    if (cd.getCertainty() != null) {
        DetachedCriteria certaintyClause = DetachedCriteria.forClass(Obs.class, "certaintyObs");
        certaintyClause.add(Restrictions.eq("voided", false));
        certaintyClause.add(Restrictions.eq("concept", dmd.getDiagnosisCertaintyConcept()));
        certaintyClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getCertainty())));
        certaintyClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        certaintyClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(certaintyClause));
    }

    if (cd.isIncludeAllCodedDiagnoses()) {
        // Note: since every diagnosis is either coded or non-coded if they want to include all coded *and* non-coded
        // diagnoses, we can just ignore both clauses
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria anyCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            anyCodedClause.add(Restrictions.eq("voided", false));
            anyCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            anyCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            anyCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(anyCodedClause));
        }
    } else if (cd.getCodedDiagnoses() != null || cd.getExcludeCodedDiagnoses() != null) {
        if (cd.isIncludeAllNonCodedDiagnoses()) {
            throw new IllegalArgumentException(
                    "Not Yet Implemented: handling both all-non-coded and specific coded diagnoses together");
        }
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria specificCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            specificCodedClause.add(Restrictions.eq("voided", false));
            specificCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            if (cd.getCodedDiagnoses() != null) {
                specificCodedClause.add(Restrictions.in("valueCoded", cd.getCodedDiagnoses()));
            }
            if (cd.getExcludeCodedDiagnoses() != null) {
                specificCodedClause
                        .add(Restrictions.not(Restrictions.in("valueCoded", cd.getExcludeCodedDiagnoses())));
            }
            specificCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            specificCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(specificCodedClause));
        }
    } else if (cd.isIncludeAllNonCodedDiagnoses()) {
        DetachedCriteria anyNonCodedClause = DetachedCriteria.forClass(Obs.class, "nonCodedDiagnosisObs");
        anyNonCodedClause.add(Restrictions.eq("voided", false));
        anyNonCodedClause.add(Restrictions.eq("concept", dmd.getNonCodedDiagnosisConcept()));
        anyNonCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        anyNonCodedClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(anyNonCodedClause));
    }

    Cohort c = new Cohort();
    for (Integer i : (List<Integer>) crit.list()) {
        c.addMember(i);
    }
    return new EvaluatedCohort(c, cohortDefinition, context);
}

From source file:org.openmrs.module.emrapi.printer.db.HibernatePrinterDAO.java

License:Open Source License

private void addUuidExclusionRestriction(Criteria criteria, String uuid) {
    criteria.add(Restrictions.not(Restrictions.eq("uuid", uuid)));
}

From source file:org.openmrs.module.nbs.datasource.HibernateLogicProviderDAO.java

License:Open Source License

private Criterion getCriterion(LogicExpression logicExpression, Date indexDate) {
    Operator operator = logicExpression.getOperator();
    Object rightOperand = logicExpression.getRightOperand();
    Object leftOperand = null;//from  ww w  .j a va2s .  c o  m

    if (logicExpression instanceof LogicExpressionBinary) {
        leftOperand = ((LogicExpressionBinary) logicExpression).getLeftOperand();
    }
    List<Criterion> criterion = new ArrayList<Criterion>();
    String attr = "";
    String token = logicExpression.getRootToken();

    if (token != null && operator != null) {
        if (token.equalsIgnoreCase("username"))
            attr = "username";
        else if (token.equalsIgnoreCase("system_Id"))
            attr = "systemId";
        else if (token.equalsIgnoreCase("provider_id")) {
            attr = "attr.value";
        } else if (token.equalsIgnoreCase("given_name")) {
            attr = "na.givenName";
        } else if (token.equalsIgnoreCase("middle_name")) {
            attr = "na.middleName";
        } else if (token.equalsIgnoreCase("family_name")) {
            attr = "na.familyName";
        } else {
            this.log.error("Illegal or unsupported token:" + token);
        }
    }

    if (operator == null || operator instanceof org.openmrs.logic.op.After
            || operator instanceof org.openmrs.logic.op.GreaterThan
            || operator instanceof org.openmrs.logic.op.GreaterThanEquals
            || operator instanceof org.openmrs.logic.op.Before
            || operator instanceof org.openmrs.logic.op.LessThan
            || operator instanceof org.openmrs.logic.op.LessThanEquals
            || operator instanceof org.openmrs.logic.op.Exists || operator instanceof org.openmrs.logic.op.AsOf
            || operator instanceof org.openmrs.logic.op.Within) {
        // Nothing to do since all String tokens
    } else if (operator == Operator.AND || operator == Operator.OR) {

        Criterion leftCriteria = null;
        Criterion rightCriteria = null;

        if (leftOperand instanceof LogicExpression) {
            leftCriteria = this.getCriterion((LogicExpression) leftOperand, indexDate);
        }
        if (rightOperand instanceof LogicExpression) {
            rightCriteria = this.getCriterion((LogicExpression) rightOperand, indexDate);
        }

        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);
        }

        if (rightCriteria != null) {
            criterion.add(Restrictions.not(rightCriteria));
        }
    } else if (operator instanceof org.openmrs.logic.op.Contains
            || operator instanceof org.openmrs.logic.op.Equals) {
        criterion.add(Restrictions.eq(attr, rightOperand));

    }
    Criterion c = null;

    for (Criterion crit : criterion) {
        if (c == null) {
            c = crit;
        } else {
            c = Restrictions.and(c, crit);
        }
    }
    return c;
}