Example usage for org.hibernate.criterion DetachedCriteria setProjection

List of usage examples for org.hibernate.criterion DetachedCriteria setProjection

Introduction

In this page you can find the example usage for org.hibernate.criterion DetachedCriteria setProjection.

Prototype

public DetachedCriteria setProjection(Projection projection) 

Source Link

Document

Set the projection to use.

Usage

From source file:org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao.java

License:Open Source License

public List<FIN_FinancialAccount> getFilteredFinancialAccounts(String strPaymentMethodId, String strOrgId,
        String strCurrencyId, PaymentDirection paymentDirection) {
    final OBCriteria<FIN_FinancialAccount> obc = OBDal.getInstance().createCriteria(FIN_FinancialAccount.class,
            "acc");
    obc.add(Restrictions.in("organization.id",
            OBContext.getOBContext().getOrganizationStructureProvider().getNaturalTree(strOrgId)));
    obc.setFilterOnReadableOrganization(false);

    Currency requiredCurrency = null;
    if (strCurrencyId != null && !strCurrencyId.isEmpty()) {
        DetachedCriteria multiCurrAllowed = DetachedCriteria
                .forEntityName(FinAccPaymentMethod.ENTITY_NAME, "fapm")
                .add(Restrictions.eqProperty(FinAccPaymentMethod.PROPERTY_ACCOUNT + ".id", "acc.id"));
        if (paymentDirection == PaymentDirection.IN || paymentDirection == PaymentDirection.EITHER) {
            multiCurrAllowed.add(Restrictions.eq(FinAccPaymentMethod.PROPERTY_PAYINISMULTICURRENCY, true));
        }/*  w w w.j a  v  a 2s  .c  o m*/
        if (paymentDirection == PaymentDirection.OUT || paymentDirection == PaymentDirection.EITHER) {
            multiCurrAllowed.add(Restrictions.eq(FinAccPaymentMethod.PROPERTY_PAYOUTISMULTICURRENCY, true));
        }
        requiredCurrency = OBDal.getInstance().get(Currency.class, strCurrencyId);
        obc.add(Restrictions.or(Restrictions.eq(FIN_FinancialAccount.PROPERTY_CURRENCY, requiredCurrency),
                Subqueries.exists(multiCurrAllowed.setProjection(Projections.id()))));
    }

    if (strPaymentMethodId != null && !strPaymentMethodId.isEmpty()) {
        List<FinAccPaymentMethod> finAccsMethods = getObject(FIN_PaymentMethod.class, strPaymentMethodId)
                .getFinancialMgmtFinAccPaymentMethodList();

        if (finAccsMethods.isEmpty()) {
            return (new ArrayList<FIN_FinancialAccount>());
        }
        ExpressionForFinAccPayMethod exp = new ExpressionForFinAccPayMethod();

        for (FinAccPaymentMethod finAccPayMethod : finAccsMethods) {
            boolean validPaymentDirection = true;
            if (paymentDirection == PaymentDirection.IN) {
                validPaymentDirection = finAccPayMethod.isPayinAllow();
            } else if (paymentDirection == PaymentDirection.OUT) {
                validPaymentDirection = finAccPayMethod.isPayoutAllow();
            }

            boolean validCurrency = true;
            if (requiredCurrency != null) {
                boolean multiCurrencyAllowed = false;
                if (paymentDirection == PaymentDirection.IN) {
                    multiCurrencyAllowed = finAccPayMethod.isPayinIsMulticurrency();
                } else if (paymentDirection == PaymentDirection.OUT) {
                    multiCurrencyAllowed = finAccPayMethod.isPayoutIsMulticurrency();
                } else if (paymentDirection == PaymentDirection.EITHER) {
                    multiCurrencyAllowed = finAccPayMethod.isPayinIsMulticurrency()
                            || finAccPayMethod.isPayoutIsMulticurrency();
                }

                validCurrency = multiCurrencyAllowed
                        || requiredCurrency.equals(finAccPayMethod.getAccount().getCurrency());
            }

            if (validPaymentDirection && validCurrency) {
                exp.addFinAccPaymentMethod(finAccPayMethod);
            }

        }

        Criterion crit = exp.getCriterion();
        if (crit != null) {
            obc.add(crit);
        } else {
            return new ArrayList<FIN_FinancialAccount>();
        }
    }
    return obc.list();
}

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

License:Mozilla Public License

/**
 * Convenience method to create the same hibernate criteria object for both getForms and
 * getFormCount/*from   w  w  w  .  ja  v a 2 s  .c o m*/
 *
 * @param partialName
 * @param published
 * @param encounterTypes
 * @param retired
 * @param containingAnyFormField
 * @param containingAllFormFields
 * @param fields
 * @return
 */
private Criteria getFormCriteria(String partialName, Boolean published,
        Collection<EncounterType> encounterTypes, Boolean retired, Collection<FormField> containingAnyFormField,
        Collection<FormField> containingAllFormFields, Collection<Field> fields) {

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Form.class, "form");

    if (StringUtils.isNotEmpty(partialName)) {
        crit.add(Restrictions.or(Restrictions.like("name", partialName, MatchMode.START),
                Restrictions.like("name", " " + partialName, MatchMode.ANYWHERE)));
    }
    if (published != null) {
        crit.add(Restrictions.eq("published", published));
    }

    if (!encounterTypes.isEmpty()) {
        crit.add(Restrictions.in("encounterType", encounterTypes));
    }

    if (retired != null) {
        crit.add(Restrictions.eq("retired", retired));
    }

    // TODO junit test
    if (!containingAnyFormField.isEmpty()) {
        // Convert form field persistents to integers
        Set<Integer> anyFormFieldIds = new HashSet<Integer>();
        for (FormField ff : containingAnyFormField) {
            anyFormFieldIds.add(ff.getFormFieldId());
        }

        DetachedCriteria subquery = DetachedCriteria.forClass(FormField.class, "ff");
        subquery.setProjection(Projections.property("ff.form.formId"));
        subquery.add(Restrictions.in("ff.formFieldId", anyFormFieldIds));
        crit.add(Subqueries.propertyIn("form.formId", subquery));
    }

    //select * from form where len(containingallformfields) = (select count(*) from form_field ff where ff.form_id = form_id and form_field_id in (containingallformfields);
    if (!containingAllFormFields.isEmpty()) {

        // Convert form field persistents to integers
        Set<Integer> allFormFieldIds = new HashSet<Integer>();
        for (FormField ff : containingAllFormFields) {
            allFormFieldIds.add(ff.getFormFieldId());
        }
        DetachedCriteria subquery = DetachedCriteria.forClass(FormField.class, "ff");
        subquery.setProjection(Projections.count("ff.formFieldId"));
        subquery.add(Restrictions.eqProperty("ff.form", "form"));
        subquery.add(Restrictions.in("ff.formFieldId", allFormFieldIds));

        crit.add(Subqueries.eq(Long.valueOf(containingAllFormFields.size()), subquery));
    }

    // get all forms (dupes included) that have this field on them
    if (!fields.isEmpty()) {
        Criteria crit2 = crit.createCriteria("formFields", "ff");
        crit2.add(Restrictions.eqProperty("ff.form.formId", "form.formId"));
        crit2.add(Restrictions.in("ff.field", fields));
    }

    return crit;
}

From source file:org.openmrs.module.emr.api.db.hibernate.HibernateEmrDAO.java

License:Open Source License

@Override
@Transactional(readOnly = true)/*from ww  w  . j  av a  2s . co  m*/
public List<ConceptSearchResult> conceptSearch(String query, Locale locale, Collection<ConceptClass> classes,
        Collection<Concept> inSets, Collection<ConceptSource> sources, Integer limit) {
    List<String> uniqueWords = ConceptWord.getUniqueWords(query, locale);
    if (uniqueWords.size() == 0) {
        return Collections.emptyList();
    }

    List<ConceptSearchResult> results = new ArrayList<ConceptSearchResult>();

    // find matches based on name
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptName.class, "cn");
        criteria.add(Restrictions.eq("voided", false));
        criteria.add(Restrictions.eq("locale", locale));
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }
        if (inSets != null) {
            DetachedCriteria allowedSetMembers = DetachedCriteria.forClass(ConceptSet.class);
            allowedSetMembers.add(Restrictions.in("conceptSet", inSets));
            allowedSetMembers.setProjection(Projections.property("concept"));
            criteria.add(Subqueries.propertyIn("concept", allowedSetMembers));
        }

        for (String word : uniqueWords) {
            criteria.add(Restrictions.ilike("name", word, MatchMode.ANYWHERE));
        }

        Set<Concept> conceptsMatchedByPreferredName = new HashSet<Concept>();
        for (ConceptName matchedName : (List<ConceptName>) criteria.list()) {
            results.add(new ConceptSearchResult(null, matchedName.getConcept(), matchedName,
                    calculateMatchScore(query, uniqueWords, matchedName)));
            if (matchedName.isLocalePreferred()) {
                conceptsMatchedByPreferredName.add(matchedName.getConcept());
            }
        }

        // don't display synonym matches if the preferred name matches too
        for (Iterator<ConceptSearchResult> i = results.iterator(); i.hasNext();) {
            ConceptSearchResult candidate = i.next();
            if (!candidate.getConceptName().isLocalePreferred()
                    && conceptsMatchedByPreferredName.contains(candidate.getConcept())) {
                i.remove();
            }
        }
    }

    // find matches based on mapping
    if (sources != null) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptMap.class);
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }

        Criteria mappedTerm = criteria.createCriteria("conceptReferenceTerm");
        mappedTerm.add(Restrictions.eq("retired", false));
        mappedTerm.add(Restrictions.in("conceptSource", sources));
        mappedTerm.add(Restrictions.ilike("code", query, MatchMode.EXACT));

        for (ConceptMap mapping : (List<ConceptMap>) criteria.list()) {
            results.add(new ConceptSearchResult(null, mapping.getConcept(), null,
                    calculateMatchScore(query, mapping)));
        }
    }

    Collections.sort(results, new Comparator<ConceptSearchResult>() {
        @Override
        public int compare(ConceptSearchResult left, ConceptSearchResult right) {
            return right.getTransientWeight().compareTo(left.getTransientWeight());
        }
    });

    if (results.size() > limit) {
        results = results.subList(0, limit);
    }
    return results;
}

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  ww.j a va2s .  c o  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.concept.HibernateEmrConceptDAO.java

License:Open Source License

@Override
@Transactional(readOnly = true)//from  ww  w  . j a v  a2  s  .  c o m
public List<ConceptSearchResult> conceptSearch(String query, Locale locale, Collection<ConceptClass> classes,
        Collection<Concept> inSets, Collection<ConceptSource> sources, Integer limit) {
    List<String> uniqueWords = getUniqueWords(query, locale);
    if (uniqueWords.size() == 0) {
        return Collections.emptyList();
    }

    List<ConceptSearchResult> results = new ArrayList<ConceptSearchResult>();

    // find matches based on name
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptName.class, "cn");
        criteria.add(Restrictions.eq("voided", false));
        if (StringUtils.isNotBlank(locale.getCountry()) || StringUtils.isNotBlank(locale.getVariant())) {
            Locale[] locales = new Locale[] { locale, new Locale(locale.getLanguage()) };
            criteria.add(Restrictions.in("locale", locales));
        } else {
            criteria.add(Restrictions.eq("locale", locale));
        }
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }
        if (inSets != null) {
            DetachedCriteria allowedSetMembers = DetachedCriteria.forClass(ConceptSet.class);
            allowedSetMembers.add(Restrictions.in("conceptSet", inSets));
            allowedSetMembers.setProjection(Projections.property("concept"));
            criteria.add(Subqueries.propertyIn("concept", allowedSetMembers));
        }

        for (String word : uniqueWords) {
            criteria.add(Restrictions.ilike("name", word, MatchMode.ANYWHERE));
        }

        Set<Concept> conceptsMatchedByPreferredName = new HashSet<Concept>();
        for (ConceptName matchedName : (List<ConceptName>) criteria.list()) {
            results.add(new ConceptSearchResult(null, matchedName.getConcept(), matchedName,
                    calculateMatchScore(query, uniqueWords, matchedName)));
            if (matchedName.isLocalePreferred()) {
                conceptsMatchedByPreferredName.add(matchedName.getConcept());
            }
        }

        // don't display synonym matches if the preferred name matches too
        for (Iterator<ConceptSearchResult> i = results.iterator(); i.hasNext();) {
            ConceptSearchResult candidate = i.next();
            if (!candidate.getConceptName().isLocalePreferred()
                    && conceptsMatchedByPreferredName.contains(candidate.getConcept())) {
                i.remove();
            }
        }
    }

    // find matches based on mapping
    if (sources != null) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptMap.class);
        criteria.setMaxResults(limit);

        Criteria conceptCriteria = criteria.createCriteria("concept");
        conceptCriteria.add(Restrictions.eq("retired", false));
        if (classes != null) {
            conceptCriteria.add(Restrictions.in("conceptClass", classes));
        }

        Criteria mappedTerm = criteria.createCriteria("conceptReferenceTerm");
        mappedTerm.add(Restrictions.eq("retired", false));
        mappedTerm.add(Restrictions.in("conceptSource", sources));
        mappedTerm.add(Restrictions.ilike("code", query, MatchMode.EXACT));

        for (ConceptMap mapping : (List<ConceptMap>) criteria.list()) {
            results.add(new ConceptSearchResult(null, mapping.getConcept(), null,
                    calculateMatchScore(query, mapping)));
        }
    }

    Collections.sort(results, new Comparator<ConceptSearchResult>() {
        @Override
        public int compare(ConceptSearchResult left, ConceptSearchResult right) {
            return right.getTransientWeight().compareTo(left.getTransientWeight());
        }
    });

    if (results.size() > limit) {
        results = results.subList(0, limit);
    }
    return results;
}

From source file:org.openmrs.module.errorlogging.api.db.hibernate.HibernateExceptionLogDAO.java

License:Open Source License

/**
 * Utility method that returns a criteria for searching for exception logs
 * that match the specified search phrase and arguments
 *
 * @param username user who experienced the exception
 * @param exceptionClass class name of the exception
 * @param exceptionMessage message on the exception
 * @param openmrsVersion version of the OpenMRS
 * @param fileName file name where the exception occurred
 * @param lineNum line number of the file where the exception occurred
 * @param startExceptionDateTime date since which exceptions thrown
 * @param endExceptionDateTime date to which exceptions thrown
 * @param start starting from the "start" record
 * @param length retrieve the next "length" records from database
 * @return the generated criteria object
 *///from  w  ww.ja v  a  2 s . c o m
private Criteria createExceptionLogSearchCriteria(String username, String exceptionClass,
        String exceptionMessage, String openmrsVersion, String fileName, String methodName, Integer lineNum,
        Date startExceptionDateTime, Date endExceptionDateTime) {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ExceptionLog.class);
    Conjunction junction = Restrictions.conjunction();
    if (username != null) {
        DetachedCriteria subCriteria = DetachedCriteria.forClass(User.class);
        subCriteria.add(Restrictions.like("username", username));
        subCriteria.setProjection(Projections.property("userId"));
        junction.add(Subqueries.propertyEq("creator.userId", subCriteria));
    }
    if (exceptionClass != null) {
        criteria.add(Restrictions.like("exceptionClass", exceptionClass));
    }
    if (exceptionMessage != null) {
        criteria.add(Restrictions.like("exceptionMessage", exceptionMessage, MatchMode.ANYWHERE));
    }
    if (openmrsVersion != null) {
        criteria.add(Restrictions.like("openmrsVersion", openmrsVersion));
    }
    if (fileName != null) {
        DetachedCriteria subCriteria = DetachedCriteria.forClass(ExceptionLogDetail.class);
        subCriteria.add(Restrictions.like("fileName", fileName));
        subCriteria.setProjection(Projections.property("exceptionLogDetailId"));
        junction.add(Subqueries.propertyIn("exceptionLogId", subCriteria));
    }
    if (methodName != null) {
        DetachedCriteria subCriteria = DetachedCriteria.forClass(ExceptionLogDetail.class);
        subCriteria.add(Restrictions.like("methodName", methodName));
        subCriteria.setProjection(Projections.property("exceptionLogDetailId"));
        junction.add(Subqueries.propertyIn("exceptionLogId", subCriteria));
    }
    if (lineNum != null) {
        DetachedCriteria subCriteria = DetachedCriteria.forClass(ExceptionLogDetail.class);
        subCriteria.add(Restrictions.eq("lineNumber", lineNum));
        subCriteria.setProjection(Projections.property("exceptionLogDetailId"));
        junction.add(Subqueries.propertyIn("exceptionLogId", subCriteria));
    }
    if (startExceptionDateTime != null) {
        criteria.add(Restrictions.ge("dateCreated", startExceptionDateTime));
    }
    if (endExceptionDateTime != null) {
        criteria.add(Restrictions.le("dateCreated", endExceptionDateTime));
    }
    criteria.add(junction);
    return criteria;
}

From source file:org.openmrs.module.openhmis.inventory.api.impl.StockOperationDataServiceImpl.java

License:Open Source License

@Override
public List<StockOperation> getUserOperations(final User user, final StockOperationStatus status,
        PagingInfo paging) {/*from  w ww .ja  va 2s  . c o m*/
    if (user == null) {
        throw new IllegalArgumentException("The user must be defined.");
    }

    // Get all the roles for this user (this traverses the role relationships to get any parent roles)
    final Set<Role> roles = user.getAllRoles();

    List<StockOperation> stockOperations = executeCriteria(StockOperation.class, paging,
            new Action1<Criteria>() {
                @Override
                public void apply(Criteria criteria) {
                    DetachedCriteria subQuery = DetachedCriteria.forClass(IStockOperationType.class);
                    subQuery.setProjection(Property.forName("id"));

                    // Add user/role filter
                    if (roles != null && roles.size() > 0) {
                        subQuery.add(Restrictions.or(
                                // Types that require user approval
                                Restrictions.eq("user", user),
                                // Types that require role approval
                                Restrictions.in("role", roles)));
                    } else {
                        // Types that require user approval
                        subQuery.add(Restrictions.eq("user", user));
                    }

                    if (status != null) {
                        criteria.add(Restrictions.and(Restrictions.eq("status", status), Restrictions.or(
                                // Transactions created by the user
                                Restrictions.eq("creator", user),
                                Property.forName("instanceType").in(subQuery))));
                    } else {
                        criteria.add(Restrictions.or(
                                // Transactions created by the user
                                Restrictions.eq("creator", user),
                                Property.forName("instanceType").in(subQuery)));
                    }
                }
            }, Order.desc("dateCreated"));

    //This code ensures that the resulting operations are all belonging to the appropriate stockrooms from the user defaultLocation
    List<StockOperation> result = new ArrayList<StockOperation>();
    Location location = Context.getLocationService()
            .getLocation(Integer.parseInt(Context.getAuthenticatedUser().getUserProperty(LOCATIONPROPERTY)));
    for (StockOperation stockOperation : stockOperations) {
        if (ensuredStockOperationBelongsToLocation(stockOperation, location) == true) {
            result.add(stockOperation);
        }
    }
    return result;
}

From source file:org.opennms.dashboard.server.CriteriaAddingVisitor.java

License:Open Source License

/**
 * <p>addCriteriaForCategories</p>
 *
 * @param criteria a {@link org.opennms.netmgt.model.OnmsCriteria} object.
 * @param categories a {@link java.lang.String} object.
 *//*ww w.  j  av  a  2 s.  co m*/
public void addCriteriaForCategories(OnmsCriteria criteria, String... categories) {
    if (criteria.resultsOfType(OnmsMonitoredService.class) || criteria.resultsOfType(OnmsOutage.class)) {
        // Make a detached criteria to subselect the node IDs that are in the
        // specified surveillance categories
        DetachedCriteria categoryNodeCriteria = DetachedCriteria.forClass(OnmsNode.class, "categoryNodes");

        // HACK: Hibernate 3.6 aliases 'categoryNodes' as 'categoryNodes_' so use that for the raw SQL statement.
        // Also note that the database field that we use here is 'nodeId' but the bean property for node ID
        // in OnmsNode is 'id'.
        String sql = "categoryNodes_.nodeId in (select distinct cn.nodeId from category_node cn join categories c on cn.categoryId = c.categoryId where c.categoryName in ("
                + commaDelimitedQuestionMarks(categories.length) + "))";
        categoryNodeCriteria.add(
                Restrictions.sqlRestriction(sql, categories, arrayOfType(categories.length, new StringType())));

        // Join the categoryNodes IDs found by the subselect with the outer 'node' alias.
        // This requires that the criteria already has a 'node' alias to the node table.
        //
        // @see org.opennms.web.svclayer.support.DefaultRtcService#createOutageCriteria()
        // @see org.opennms.web.svclayer.support.DefaultRtcService#createServiceCriteria()
        //
        categoryNodeCriteria.add(Restrictions.eqProperty("categoryNodes.id", "node.id"));

        // Add a projection for 'id' so that the categoryNodes.id can be joined to
        // node.id in the outer criteria
        categoryNodeCriteria.setProjection(Projections.property("id"));

        // Use an exists subquery to evaluate the subselect
        criteria.add(Subqueries.exists(categoryNodeCriteria));
    } else {
        // TODO: This case assumes that the OnmsCriteria is querying an object with a 'nodeId' property.
        // I'm not sure this is ever used... I think this visitor is just for OnmsMonitoredService and 
        // OnmsOutage queries.
        String sql = "{alias}.nodeId in (select distinct cn.nodeId from category_node cn join categories c on cn.categoryId = c.categoryId where c.categoryName in ("
                + commaDelimitedQuestionMarks(categories.length) + "))";
        criteria.add(
                Restrictions.sqlRestriction(sql, categories, arrayOfType(categories.length, new StringType())));
    }
}

From source file:org.opennms.netmgt.dao.hibernate.AssetRecordDaoHibernate.java

License:Open Source License

@Override
public List<OnmsAssetRecord> getDistinctProperties() {
    DetachedCriteria criteria = DetachedCriteria.forClass(OnmsAssetRecord.class);
    ProjectionList projList = Projections.projectionList();

    // projList.add(Projections.alias(Projections.property("geolocation"), "geolocation"));
    projList.add(Projections.alias(Projections.property("additionalhardware"), "additionalhardware"));
    projList.add(Projections.alias(Projections.property("geolocation.address1"), "address1"));
    projList.add(Projections.alias(Projections.property("geolocation.address2"), "address2"));
    projList.add(Projections.alias(Projections.property("admin"), "admin"));
    projList.add(Projections.alias(Projections.property("assetNumber"), "assetNumber"));
    projList.add(Projections.alias(Projections.property("autoenable"), "autoenable"));
    projList.add(Projections.alias(Projections.property("building"), "building"));
    projList.add(Projections.alias(Projections.property("category"), "category"));
    projList.add(Projections.alias(Projections.property("circuitId"), "circuitId"));
    projList.add(Projections.alias(Projections.property("geolocation.city"), "city"));
    projList.add(Projections.alias(Projections.property("comment"), "comment"));
    projList.add(Projections.alias(Projections.property("connection"), "connection"));
    projList.add(Projections.alias(Projections.property("geolocation.longitude"), "longitude"));
    projList.add(Projections.alias(Projections.property("geolocation.latitude"), "latitude"));
    projList.add(Projections.alias(Projections.property("cpu"), "cpu"));
    projList.add(Projections.alias(Projections.property("department"), "department"));
    projList.add(Projections.alias(Projections.property("description"), "description"));
    projList.add(Projections.alias(Projections.property("displayCategory"), "displayCategory"));
    projList.add(Projections.alias(Projections.property("division"), "division"));
    projList.add(Projections.alias(Projections.property("enable"), "enable"));
    projList.add(Projections.alias(Projections.property("floor"), "floor"));
    projList.add(Projections.alias(Projections.property("hdd1"), "hdd1"));
    projList.add(Projections.alias(Projections.property("hdd2"), "hdd2"));
    projList.add(Projections.alias(Projections.property("hdd3"), "hdd3"));
    projList.add(Projections.alias(Projections.property("hdd4"), "hdd4"));
    projList.add(Projections.alias(Projections.property("hdd5"), "hdd5"));
    projList.add(Projections.alias(Projections.property("hdd6"), "hdd6"));
    projList.add(Projections.alias(Projections.property("inputpower"), "inputpower"));
    projList.add(Projections.alias(Projections.property("lease"), "lease"));
    projList.add(Projections.alias(Projections.property("maintcontract"), "maintcontract"));
    projList.add(Projections.alias(Projections.property("manufacturer"), "manufacturer"));
    projList.add(Projections.alias(Projections.property("modelNumber"), "modelNumber"));
    projList.add(Projections.alias(Projections.property("notifyCategory"), "notifyCategory"));
    projList.add(Projections.alias(Projections.property("numpowersupplies"), "numpowersupplies"));
    projList.add(Projections.alias(Projections.property("operatingSystem"), "operatingSystem"));
    projList.add(Projections.alias(Projections.property("pollerCategory"), "pollerCategory"));
    projList.add(Projections.alias(Projections.property("port"), "port"));
    projList.add(Projections.alias(Projections.property("rack"), "rack"));
    projList.add(Projections.alias(Projections.property("ram"), "ram"));
    projList.add(Projections.alias(Projections.property("region"), "region"));
    projList.add(Projections.alias(Projections.property("room"), "room"));
    projList.add(Projections.alias(Projections.property("serialNumber"), "serialNumber"));
    projList.add(Projections.alias(Projections.property("slot"), "slot"));
    projList.add(Projections.alias(Projections.property("snmpcommunity"), "snmpcommunity"));
    projList.add(Projections.alias(Projections.property("geolocation.state"), "state"));
    projList.add(Projections.alias(Projections.property("storagectrl"), "storagectrl"));
    projList.add(Projections.alias(Projections.property("supportPhone"), "supportPhone"));
    projList.add(Projections.alias(Projections.property("thresholdCategory"), "thresholdCategory"));
    projList.add(Projections.alias(Projections.property("username"), "username"));
    projList.add(Projections.alias(Projections.property("vendor"), "vendor"));
    projList.add(Projections.alias(Projections.property("vendorAssetNumber"), "vendorAssetNumber"));
    projList.add(Projections.alias(Projections.property("vendorFax"), "vendorFax"));
    projList.add(Projections.alias(Projections.property("vendorPhone"), "vendorPhone"));
    projList.add(Projections.alias(Projections.property("geolocation.zip"), "zip"));
    projList.add(Projections.alias(Projections.property("vmwareManagedObjectId"), "vmwareManagedObjectId"));
    projList.add(Projections.alias(Projections.property("vmwareManagedEntityType"), "vmwareManagedEntityType"));
    projList.add(Projections.alias(Projections.property("vmwareManagementServer"), "vmwareManagementServer"));
    projList.add(Projections.alias(Projections.property("vmwareTopologyInfo"), "vmwareTopologyInfo"));
    projList.add(Projections.alias(Projections.property("vmwareState"), "vmwareState"));

    criteria.setProjection(Projections.distinct(projList));
    criteria.setResultTransformer(Transformers.aliasToBean(OnmsAssetRecord.class));

    @SuppressWarnings("unchecked")
    List<OnmsAssetRecord> result = (List<OnmsAssetRecord>) getHibernateTemplate().findByCriteria(criteria);
    return result;
}

From source file:org.opensingular.flow.persistence.service.AbstractHibernatePersistenceService.java

License:Apache License

public List<PROCESS_INSTANCE> retrieveProcessInstancesWith(PROCESS_DEF process, Date dataInicio, Date dataFim,
        java.util.Collection<? extends TASK_DEF> states) {
    Objects.requireNonNull(process);
    final Criteria c = getSession().createCriteria(getClassProcessInstance(), "PI");
    c.createAlias("PI.processVersion", "DEF");
    c.add(Restrictions.eq("DEF.processDefinition", process));
    if (states != null && !states.isEmpty()) {
        DetachedCriteria sub = DetachedCriteria.forClass(getClassTaskInstance(), "T");
        sub.add(Restrictions.eqProperty("T.processInstance.cod", "PI.cod"));
        sub.createAlias("T.task", "TV");
        sub.add(Restrictions.in("TV.taskDefinition", states));
        sub.add(Restrictions.isNull("T.endDate"));
        sub.setProjection(Projections.id());

        c.add(Subqueries.exists(sub));/* w  ww .j  ava  2  s . c  om*/
    }
    if (dataInicio != null && dataFim != null) {
        c.add(Restrictions.or(
                Restrictions.and(Restrictions.ge("PI.beginDate", dataInicio),
                        Restrictions.lt("PI.beginDate", dataFim)),
                Restrictions.and(Restrictions.ge("PI.endDate", dataInicio),
                        Restrictions.lt("PI.endDate", dataFim)),
                Restrictions.and(Restrictions.lt("PI.beginDate", dataInicio),
                        Restrictions.ge("PI.endDate", dataInicio)),
                Restrictions.and(Restrictions.isNull("PI.endDate"), Restrictions.lt("PI.beginDate", dataFim))));
    } else if (dataInicio != null) {
        c.add(Restrictions.or(Restrictions.ge("PI.beginDate", dataInicio),
                Restrictions.ge("PI.endDate", dataInicio), Restrictions
                        .and(Restrictions.lt("PI.beginDate", dataInicio), Restrictions.isNull("PI.endDate"))));
    } else if (dataFim != null) {
        c.add(Restrictions.or(Restrictions.le("PI.beginDate", dataFim),
                Restrictions.le("PI.endDate", dataFim)));
    }
    c.addOrder(Order.desc("PI.beginDate"));
    return c.list();
}