Example usage for org.hibernate.criterion ProjectionList add

List of usage examples for org.hibernate.criterion ProjectionList add

Introduction

In this page you can find the example usage for org.hibernate.criterion ProjectionList add.

Prototype

public ProjectionList add(Projection projection) 

Source Link

Document

Add a projection to this list of projections

Usage

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

License:Open Source License

/**
 * Calculates the ending balance of automatic reconciliations. The sum of all the bank statement
 * lines of the reconciliation financial account that belong to the given reconciliation plus the
 * ones that does not have a transaction associated yet.
 * //w  w  w  .j a va2s .com
 * @param reconciliation
 *          Reconciliation.
 * @return Ending balance of an automatic reconciliation.
 */
@Deprecated
public static BigDecimal getReconciliationEndingBalance(FIN_Reconciliation reconciliation) {
    BigDecimal total = BigDecimal.ZERO;
    OBContext.setAdminMode(true);
    try {
        OBCriteria<FIN_BankStatementLine> obcBsl = OBDal.getInstance()
                .createCriteria(FIN_BankStatementLine.class);
        obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, "bs");
        obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION, "tr",
                OBCriteria.LEFT_JOIN);
        obcBsl.add(Restrictions.or(
                Restrictions.isNull(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION),
                Restrictions.eq("tr." + FIN_FinaccTransaction.PROPERTY_RECONCILIATION, reconciliation)));

        obcBsl.add(Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_ACCOUNT, reconciliation.getAccount()));
        obcBsl.add(Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_PROCESSED, true));
        ProjectionList projections = Projections.projectionList();
        projections.add(Projections.sum(FIN_BankStatementLine.PROPERTY_CRAMOUNT));
        projections.add(Projections.sum(FIN_BankStatementLine.PROPERTY_DRAMOUNT));
        obcBsl.setProjection(projections);

        @SuppressWarnings("rawtypes")
        List o = obcBsl.list();
        if (o != null && o.size() > 0) {
            Object[] resultSet = (Object[]) o.get(0);
            BigDecimal credit = (resultSet[0] != null) ? (BigDecimal) resultSet[0] : BigDecimal.ZERO;
            BigDecimal debit = (resultSet[1] != null) ? (BigDecimal) resultSet[1] : BigDecimal.ZERO;
            total = credit.subtract(debit);
        }
        o.clear();

    } finally {
        OBContext.restorePreviousMode();
    }

    return total;
}

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

License:Open Source License

/**
 * Calculates the balance of unmatched bank statements for the given reconciliation
 * // www.j a va2  s.c  om
 * @param lastReconciliation
 *          Reconciliation.
 * @return Last reconciliation UnMatched balance
 */
public static BigDecimal getLastReconciliationUnmatchedBalance(FIN_Reconciliation lastReconciliation) {
    BigDecimal total = BigDecimal.ZERO;
    OBContext.setAdminMode(true);
    try {
        OBCriteria<FIN_BankStatementLine> obcBsl = OBDal.getInstance()
                .createCriteria(FIN_BankStatementLine.class);
        obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, "bs");
        obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION, "tr",
                OBCriteria.LEFT_JOIN);

        List<FIN_Reconciliation> afterReconciliations = getReconciliationListAfterDate(lastReconciliation);
        if (afterReconciliations.size() > 0) {
            obcBsl.add(Restrictions.or(
                    Restrictions.isNull(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION),
                    Restrictions.in("tr." + FIN_FinaccTransaction.PROPERTY_RECONCILIATION,
                            afterReconciliations)));
        } else {
            obcBsl.add(Restrictions.isNull(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION));
        }
        obcBsl.add(
                Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_ACCOUNT, lastReconciliation.getAccount()));
        obcBsl.add(Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_PROCESSED, true));
        obcBsl.add(Restrictions.le(FIN_BankStatementLine.PROPERTY_TRANSACTIONDATE,
                lastReconciliation.getTransactionDate()));
        ProjectionList projections = Projections.projectionList();
        projections.add(Projections.sum(FIN_BankStatementLine.PROPERTY_CRAMOUNT));
        projections.add(Projections.sum(FIN_BankStatementLine.PROPERTY_DRAMOUNT));
        obcBsl.setProjection(projections);

        @SuppressWarnings("rawtypes")
        List o = obcBsl.list();
        if (o != null && o.size() > 0) {
            Object[] resultSet = (Object[]) o.get(0);
            BigDecimal credit = (resultSet[0] != null) ? (BigDecimal) resultSet[0] : BigDecimal.ZERO;
            BigDecimal debit = (resultSet[1] != null) ? (BigDecimal) resultSet[1] : BigDecimal.ZERO;
            total = credit.subtract(debit);
        }
        o.clear();

    } finally {
        OBContext.restorePreviousMode();
    }

    return total;
}

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

License:Open Source License

private static BigDecimal getBSLAmount(FIN_Reconciliation reconciliation) {
    BigDecimal total = BigDecimal.ZERO;
    OBContext.setAdminMode(false);/*  w w w. j  a v  a 2 s  .c om*/
    try {
        OBCriteria<FIN_BankStatementLine> obcBsl = OBDal.getInstance()
                .createCriteria(FIN_BankStatementLine.class);
        obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_BANKSTATEMENT, "bs");
        obcBsl.createAlias(FIN_BankStatementLine.PROPERTY_FINANCIALACCOUNTTRANSACTION, "tr",
                OBCriteria.LEFT_JOIN);
        obcBsl.add(Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_ACCOUNT, reconciliation.getAccount()));
        obcBsl.add(Restrictions.eq("bs." + FIN_BankStatement.PROPERTY_PROCESSED, true));
        obcBsl.add(Restrictions.le(FIN_BankStatementLine.PROPERTY_TRANSACTIONDATE,
                reconciliation.getEndingDate()));
        ProjectionList projections = Projections.projectionList();
        projections.add(Projections.sum(FIN_BankStatementLine.PROPERTY_CRAMOUNT));
        projections.add(Projections.sum(FIN_BankStatementLine.PROPERTY_DRAMOUNT));
        obcBsl.setProjection(projections);

        @SuppressWarnings("rawtypes")
        List o = obcBsl.list();
        if (o != null && o.size() > 0) {
            Object[] resultSet = (Object[]) o.get(0);
            BigDecimal credit = (resultSet[0] != null) ? (BigDecimal) resultSet[0] : BigDecimal.ZERO;
            BigDecimal debit = (resultSet[1] != null) ? (BigDecimal) resultSet[1] : BigDecimal.ZERO;
            total = credit.subtract(debit);
        }
        o.clear();

    } finally {
        OBContext.restorePreviousMode();
    }
    return total;
}

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;
    }/* w  ww . j a  v  a  2  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.openhie.openempi.blocking.basicblockinghp.dao.hibernate.BlockingDaoHibernate.java

License:Open Source License

private org.hibernate.Criteria createQueryFromFields(Session session, List<String> fieldNameSet) {
    org.hibernate.Criteria criteria = session.createCriteria(Person.class);
    ProjectionList projectionsList = Projections.projectionList();
    for (String fieldName : fieldNameSet) {
        projectionsList.add(Projections.property(fieldName));
    }// ww  w  . j  a v a  2  s.co m
    criteria.setProjection(projectionsList);
    criteria.add(Restrictions.isNull("dateVoided"));
    return criteria;
}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, List<List<Object>>> getObservationsValues(Cohort patients, Concept c,
        List<String> attributes, Integer limit, boolean showMostRecentFirst) {
    Map<Integer, List<List<Object>>> ret = new HashMap<Integer, List<List<Object>>>();

    List<String> aliases = new Vector<String>();
    Boolean conditional = false;// w  w w.j a  v  a 2s.c  o  m

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria("org.openmrs.Obs", "obs");
    criteria.setCacheMode(CacheMode.IGNORE);

    List<String> columns = new Vector<String>();

    for (String attribute : attributes) {
        List<String> classNames = new Vector<String>();
        if (attribute == null) {
            columns = findObsValueColumnName(c);
            if (columns.size() > 1) {
                conditional = true;
            }
            continue;
            //log.debug("c: " + c.getConceptId() + " attribute: " + attribute);
        } else if ("valueDate".equals(attribute)) {
            // pass -- same column name
        } else if ("valueTime".equals(attribute)) {
            // pass -- same column name
        } else if ("valueDatetime".equals(attribute)) {
            // pass -- same column name
        } else if ("obsDatetime".equals(attribute)) {
            // pass -- same column name
        } else if ("location".equals(attribute)) {
            // pass -- same column name
            classNames.add("obs.location");
            attribute = "location.name";
        } else if ("comment".equals(attribute)) {
            // pass -- same column name
        } else if ("encouterType".equals(attribute)) {
            classNames.add("obs.encounter");
            classNames.add("encounter.encounterType");
            attribute = "encounterType.name";
        } else if ("provider".equals(attribute)) {
            classNames.add("obs.encounter");
            attribute = "encounter.provider";
        } else {
            throw new DAOException("Attribute: " + attribute + " is not recognized. Please add reference in "
                    + this.getClass());
        }

        for (String className : classNames) { // if aliasing is necessary
            if (!aliases.contains(className)) { // if we haven't aliased this already
                criteria.createAlias(className, className.split("\\.")[1]);
                aliases.add(className);
            }
        }

        columns.add(attribute);
    }

    String aliasName = "obs";

    // set up the query
    ProjectionList projections = Projections.projectionList();
    projections.add(Projections.property("obs.personId"));
    for (String col : columns) {
        if (col.contains(".")) {
            projections.add(Projections.property(col));
        } else {
            projections.add(Projections.property(aliasName + "." + col));
        }
    }
    criteria.setProjection(projections);

    // only restrict on patient ids if some were passed in
    if (patients != null) {
        criteria.add(Restrictions.in("obs.personId", patients.getMemberIds()));
    }

    criteria.add(Restrictions.eq("obs.concept", c));
    criteria.add(Restrictions.eq("obs.voided", false));

    if (showMostRecentFirst) {
        criteria.addOrder(org.hibernate.criterion.Order.desc("obs.obsDatetime"));
    } else {
        criteria.addOrder(org.hibernate.criterion.Order.asc("obs.obsDatetime"));
    }

    long start = System.currentTimeMillis();
    List<Object[]> rows = criteria.list();
    log.debug("Took: " + (System.currentTimeMillis() - start) + " ms to run the patient/obs query");

    // set up the return map
    for (Object[] rowArray : rows) {
        //log.debug("row[0]: " + row[0] + " row[1]: " + row[1] + (row.length > 2 ? " row[2]: " + row[2] : ""));
        Integer ptId = (Integer) rowArray[0];

        List<List<Object>> oldArr = ret.get(ptId);

        // if we have already fetched all of the results the user wants 
        if (limit != null && limit > 0 && oldArr != null && oldArr.size() >= limit) {
            // the user provided a limit value and this patient already has more than
            // that number of values.
            // do nothing with this row
        } else {
            Boolean tmpConditional = conditional.booleanValue();

            // get all columns
            int index = 1;
            List<Object> row = new Vector<Object>();
            while (index < rowArray.length) {
                Object value = rowArray[index++];
                if (tmpConditional) {
                    if (index == 2 && value != null) {
                        // skip null first value if we must
                        row.add(value);
                    } else {
                        row.add(rowArray[index]);
                    }
                    tmpConditional = false;
                    index++; // increment counter for next column.  (Skips over value_concept)
                } else {
                    row.add(value == null ? "" : value);
                }
            }

            // if we haven't seen a different row for this patient already:
            if (oldArr == null) {
                List<List<Object>> arr = new Vector<List<Object>>();
                arr.add(row);
                ret.put(ptId, arr);
            }
            // if we have seen a row for this patient already
            else {
                oldArr.add(row);
                ret.put(ptId, oldArr);
            }
        }
    }

    return ret;

}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, Object> getPatientAttributes(Cohort patients, String className, String property,
        boolean returnAll) throws DAOException {
    Map<Integer, Object> ret = new HashMap<Integer, Object>();

    className = "org.openmrs." + className;

    // default query
    Criteria criteria = null;//  www .jav  a2s.  c o  m

    // make 'patient.**' reference 'patient' like alias instead of object
    if ("org.openmrs.Patient".equals(className)) {
        criteria = sessionFactory.getCurrentSession().createCriteria("org.openmrs.Patient", "patient");
    } else if ("org.openmrs.Person".equals(className)) {
        criteria = sessionFactory.getCurrentSession().createCriteria("org.openmrs.Person", "person");
    } else {
        criteria = sessionFactory.getCurrentSession().createCriteria(className);
    }

    criteria.setCacheMode(CacheMode.IGNORE);

    // set up the query
    ProjectionList projectionList = Projections.projectionList();

    // if Person, PersonName, or PersonAddress
    if (className.contains("Person")) {
        projectionList.add(Projections.property("person.personId"));
        projectionList.add(Projections.property(property));

        if (patients != null) {
            criteria.add(Restrictions.in("person.personId", patients.getMemberIds()));
        }

        // do not include voided person rows
        if ("org.openmrs.Person".equals(className)) {
            // the voided column on the person table is mapped to the person object
            // through the getPersonVoided() to distinguish it from patient/user.voided
            criteria.add(Restrictions.eq("personVoided", false));
        } else {
            // this is here to support PersonName and PersonAddress
            criteria.add(Restrictions.eq("voided", false));
        }
    }
    // if one of the Patient tables
    else {
        projectionList.add(Projections.property("patient.personId"));
        projectionList.add(Projections.property(property));

        if (patients != null) {
            criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
        }

        // do not include voided patients
        criteria.add(Restrictions.eq("voided", false));
    }
    criteria.setProjection(projectionList);

    // add 'preferred' sort order if necessary
    try {
        boolean hasPreferred = false;
        for (Field f : Class.forName(className).getDeclaredFields()) {
            if ("preferred".equals(f.getName())) {
                hasPreferred = true;
            }
        }

        if (hasPreferred) {
            criteria.addOrder(org.hibernate.criterion.Order.desc("preferred"));
        }
    } catch (ClassNotFoundException e) {
        log.warn("Class not found: " + className);
    }

    criteria.addOrder(org.hibernate.criterion.Order.desc("dateCreated"));
    List<Object[]> rows = criteria.list();

    // set up the return map
    if (returnAll) {
        for (Object[] row : rows) {
            Integer ptId = (Integer) row[0];
            Object columnValue = row[1];
            if (!ret.containsKey(ptId)) {
                Object[] arr = { columnValue };
                ret.put(ptId, arr);
            } else {
                Object[] oldArr = (Object[]) ret.get(ptId);
                Object[] newArr = new Object[oldArr.length + 1];
                System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
                newArr[oldArr.length] = columnValue;
                ret.put(ptId, newArr);
            }
        }
    } else {
        for (Object[] row : rows) {
            Integer ptId = (Integer) row[0];
            Object columnValue = row[1];
            if (!ret.containsKey(ptId)) {
                ret.put(ptId, columnValue);
            }
        }
    }

    return ret;
}

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

License:Mozilla Public License

/**
 * @param patients/*from   w w  w.  j a  v  a  2  s .com*/
 * @param types List&lt;PatientIdentifierTypes&gt; of types to get
 * @return Map of {@link PatientIdentifier}s
 */
@SuppressWarnings("unchecked")
public Map<Integer, String> getPatientIdentifierByType(Cohort patients, List<PatientIdentifierType> types) {
    Map<Integer, String> patientIdentifiers = new HashMap<Integer, String>();

    // default query
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PatientIdentifier.class);

    // only get the "identifier" and "patientId" columns
    ProjectionList projections = Projections.projectionList();
    projections.add(Projections.property("identifier"));
    projections.add(Projections.property("patient.personId"));
    criteria.setProjection(projections);

    criteria.setCacheMode(CacheMode.IGNORE);

    // Add patient restriction if necessary
    if (patients != null) {
        criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
    }

    // all identifiers must be non-voided
    criteria.add(Restrictions.eq("voided", false));

    // Add identifier type filter
    if (types != null && types.size() > 0) {
        criteria.add(Restrictions.in("identifierType", types));
    }

    // Order by ID
    criteria.addOrder(org.hibernate.criterion.Order.desc("patient.personId"));

    List<Object[]> rows = criteria.list();

    // set up the return map
    for (Object[] row : rows) {
        String identifier = (String) row[0];
        Integer patientId = (Integer) row[1];
        if (!patientIdentifiers.containsKey(patientId)) {
            patientIdentifiers.put(patientId, identifier);
        }
    }

    return patientIdentifiers;
}

From source file:org.openmrs.module.amrscustomization.db.HibernateAMRSCustomizationDAO.java

License:Open Source License

public List<Form> getPopularRecentFormsForUser(User user) {
    String monthsStr = Context.getAdministrationService()
            .getGlobalProperty(AMRSCustomizationConstants.GP_RECENT_FORMS_INTERVAL);
    Integer months = AMRSCustomizationConstants.DEFAULT_RECENT_FORMS_INTERVAL;
    try {/*from w w w .  j a  va  2s . co m*/
        months = Integer.parseInt(monthsStr);
    } catch (NumberFormatException ex) {
        log.warn("could not interpret " + monthsStr + " interval as an integer.");
    }

    Calendar monthsAgo = Calendar.getInstance();
    monthsAgo.add(Calendar.MONTH, -1 * months);

    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("form"));
    projectionList.add(Projections.alias(Projections.rowCount(), "total"));

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Encounter.class)
            .add(Restrictions.and(Restrictions.eq("creator", user),
                    Restrictions.gt("dateCreated", monthsAgo.getTime())))
            .setProjection(projectionList).addOrder(Order.desc("total")).setMaxResults(5);

    List<Form> forms = new ArrayList<Form>();
    List<Object[]> foo = crit.list();
    for (Object[] result : foo) {
        log.warn(result[0] + ": " + result[1]);
        forms.add((Form) result[0]);
    }

    return forms;
}

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

License:Open Source License

/**
 * @see ReminderDAO#aggregateReminders(java.util.Map, java.util.Collection, java.util.Date, java.util.Date)
 *//*from  ww w . jav  a  2s  . co  m*/
@Override
@SuppressWarnings("unchecked")
public List<Object[]> aggregateReminders(final Map<String, Collection<OpenmrsObject>> restrictions,
        final Collection<String> groupingProperties, final Date reminderStart, final Date reminderEnd)
        throws DAOException {

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

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

    if (reminderStart != null)
        criteria.add(Restrictions.ge("reminderDatetime", reminderStart));

    if (reminderEnd != null)
        criteria.add(Restrictions.le("reminderDatetime", reminderEnd));

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