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.openmrs.module.hospitalcore.db.hibernate.HibernateInventoryDAO.java

public Integer countViewStockBalance(Integer storeId, Integer categoryId, String drugName, String fromDate,
        String toDate, boolean isExpiry) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreDrugTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .createAlias("transactionDetail.drug", "drugAlias");

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("drug")).add(Projections.groupProperty("formulation"))
            .add(Projections.sum("currentQuantity")).add(Projections.sum("quantity"))
            .add(Projections.sum("issueQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (categoryId != null) {
        criteria.add(Restrictions.eq("drugAlias.category.id", categoryId));
    }//from   www  .  jav  a 2s.  c om
    if (!StringUtils.isBlank(drugName)) {
        criteria.add(Restrictions.like("drugAlias.name", "%" + drugName + "%"));
    }
    if (!StringUtils.isBlank(fromDate) && StringUtils.isBlank(toDate)) {
        String startFromDate = fromDate + " 00:00:00";
        String endFromDate = fromDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startFromDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endFromDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = toDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (!StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = fromDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listInventorySubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    }
    if (isExpiry) {
        criteria.add(Restrictions.lt("transactionDetail.dateExpiry", new Date()));
    } else {
        criteria.add(Restrictions.ge("transactionDetail.dateExpiry", new Date()));
    }
    criteria.setProjection(proList);
    List<Object> list = criteria.list();
    Number total = 0;
    if (!CollectionUtils.isEmpty(list)) {
        total = (Number) list.size();
    }
    return total.intValue();
}

From source file:org.openmrs.module.inventory.db.hibernate.HibernateInventoryDAO.java

License:Open Source License

public List<InventoryStoreDrugTransactionDetail> listStoreDrugAvaiable(Integer storeId,
        Collection<Integer> drugs, Collection<Integer> formulations) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreDrugTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("drug")).add(Projections.groupProperty("formulation"))
            .add(Projections.sum("currentQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (drugs != null) {
        criteria.createCriteria("transactionDetail.drug", Criteria.INNER_JOIN)
                .add(Restrictions.in("id", drugs));
    }//from   www  .j a v a 2 s. c  o m
    criteria.add(Restrictions.eq("transaction.typeTransaction", ActionValue.TRANSACTION[0]));
    if (formulations != null) {
        criteria.createCriteria("transactionDetail.formulation", Criteria.INNER_JOIN)
                .add(Restrictions.in("id", formulations));
    }
    criteria.setProjection(proList);
    criteria.add(Restrictions.ge("transactionDetail.dateExpiry", new Date()));
    List<Object> lst = criteria.list();
    if (lst == null || lst.size() == 0) {
        return null;
    }
    List<InventoryStoreDrugTransactionDetail> list = new ArrayList<InventoryStoreDrugTransactionDetail>();
    // System.out.println("lst size: "+lst.size());
    for (int i = 0; i < lst.size(); i++) {
        Object[] row = (Object[]) lst.get(i);
        InventoryStoreDrugTransactionDetail tDetail = new InventoryStoreDrugTransactionDetail();
        tDetail.setDrug((InventoryDrug) row[0]);
        tDetail.setFormulation((InventoryDrugFormulation) row[1]);
        tDetail.setCurrentQuantity((Integer) row[2]);
        list.add(tDetail);
        // System.out.println("I: "+i+" drug: "+tDetail.getDrug().getName()+" formulation: "+tDetail.getFormulation().getName()+" quantity: "+tDetail.getCurrentQuantity());
    }
    return list;
}

From source file:org.openmrs.module.inventory.db.hibernate.HibernateInventoryDAO.java

License:Open Source License

public List<InventoryStoreDrugTransactionDetail> listViewStockBalance(Integer storeId, Integer categoryId,
        String drugName, String fromDate, String toDate, boolean isExpiry, int min, int max)
        throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreDrugTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .createAlias("transactionDetail.drug", "drugAlias")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("drug")).add(Projections.groupProperty("formulation"))
            .add(Projections.sum("currentQuantity")).add(Projections.sum("quantity"))
            .add(Projections.sum("issueQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (categoryId != null) {
        criteria.add(Restrictions.eq("drugAlias.category.id", categoryId));
    }/*w  w  w. java 2 s.  c  o m*/
    if (!StringUtils.isBlank(drugName)) {
        criteria.add(Restrictions.like("drugAlias.name", "%" + drugName + "%"));
    }
    if (!StringUtils.isBlank(fromDate) && StringUtils.isBlank(toDate)) {
        String startFromDate = fromDate + " 00:00:00";
        String endFromDate = fromDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startFromDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endFromDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = toDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (!StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = fromDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listInventorySubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    }
    if (isExpiry) {
        criteria.add(Restrictions.lt("transactionDetail.dateExpiry", new Date()));
    } else {
        criteria.add(Restrictions.ge("transactionDetail.dateExpiry", new Date()));
    }

    /*
     * Sagar Bele : 13-08-2012 Bug #330 ( [INVENTORY]-error in Current
     * quantity of pharmacy )
     */
    criteria.add(Restrictions.ge("transactionDetail.currentQuantity", 0));

    criteria.setProjection(proList);
    if (max > 0) {
        criteria.setFirstResult(min).setMaxResults(max);
    }
    List<Object> lst = criteria.list();
    if (lst == null || lst.size() == 0) {
        return null;
    }
    List<InventoryStoreDrugTransactionDetail> list = new ArrayList<InventoryStoreDrugTransactionDetail>();
    for (int i = 0; i < lst.size(); i++) {
        Object[] row = (Object[]) lst.get(i);
        InventoryStoreDrugTransactionDetail tDetail = new InventoryStoreDrugTransactionDetail();
        tDetail.setDrug((InventoryDrug) row[0]);
        tDetail.setFormulation((InventoryDrugFormulation) row[1]);
        tDetail.setCurrentQuantity((Integer) row[2]);
        tDetail.setQuantity((Integer) row[3]);
        tDetail.setIssueQuantity((Integer) row[4]);
        list.add(tDetail);
    }

    return list;
}

From source file:org.openmrs.module.inventory.db.hibernate.HibernateInventoryDAO.java

License:Open Source License

@Override
public Integer sumStoreItemCurrentQuantity(Integer storeId, Integer itemId, Integer specificationId)
        throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreItemTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .add(Restrictions.eq("transaction.store.id", storeId))
            .add(Restrictions.eq("transaction.typeTransaction", ActionValue.TRANSACTION[0]))
            .add(Restrictions.eq("transactionDetail.item.id", itemId));
    if (specificationId != null && specificationId > 0) {
        criteria.add(Restrictions.eq("transactionDetail.specification.id", specificationId));
    } else {/*from  w w w  . ja  v a 2s .  co m*/
        criteria.add(Restrictions.isNull("transactionDetail.specification"));
    }

    criteria.add(Restrictions.gt("transactionDetail.currentQuantity", 0));
    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.sum("currentQuantity"));
    criteria.setProjection(proList);
    Object l = criteria.uniqueResult();
    return l != null ? (Integer) l : 0;
}

From source file:org.openmrs.module.inventory.db.hibernate.HibernateInventoryDAO.java

License:Open Source License

@Override
public List<InventoryStoreItemTransactionDetail> listStoreItemAvaiable(Integer storeId,
        Collection<Integer> items, Collection<Integer> specifications) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreItemTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("item")).add(Projections.groupProperty("specification"))
            .add(Projections.sum("currentQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (CollectionUtils.isNotEmpty(items)) {
        criteria.createCriteria("transactionDetail.item", Criteria.INNER_JOIN)
                .add(Restrictions.in("id", items));
    }/*from   w  ww.ja  va  2s.c o  m*/
    criteria.add(Restrictions.eq("transaction.typeTransaction", ActionValue.TRANSACTION[0]));
    if (CollectionUtils.isNotEmpty(specifications)) {
        criteria.createCriteria("transactionDetail.specification", Criteria.LEFT_JOIN)
                .add(Restrictions.in("id", specifications));
    }
    criteria.setProjection(proList);
    List<Object> lst = criteria.list();
    if (lst == null || lst.size() == 0) {
        return null;
    }
    List<InventoryStoreItemTransactionDetail> list = new ArrayList<InventoryStoreItemTransactionDetail>();
    // System.out.println("lst size: "+lst.size());
    for (int i = 0; i < lst.size(); i++) {
        Object[] row = (Object[]) lst.get(i);
        InventoryStoreItemTransactionDetail tDetail = new InventoryStoreItemTransactionDetail();
        tDetail.setItem((InventoryItem) row[0]);
        tDetail.setSpecification((InventoryItemSpecification) row[1]);
        tDetail.setCurrentQuantity((Integer) row[2]);
        list.add(tDetail);
        // System.out.println("I: "+i+" item: "+tDetail.getItem().getName()+" specification: "+(tDetail.getSpecification()
        // != null ?tDetail.getSpecification().getName() : " null ")
        // +" quantity: "+tDetail.getCurrentQuantity());
    }
    // System.out.println("list available: "+list);
    return list;
}

From source file:org.openmrs.module.inventory.db.hibernate.HibernateInventoryDAO.java

License:Open Source License

@Override
public List<InventoryStoreItemTransactionDetail> listStoreItemViewStockBalance(Integer storeId,
        Integer categoryId, String itemName, String fromDate, String toDate, int min, int max)
        throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreItemTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .createAlias("transactionDetail.item", "itemAlias")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("item")).add(Projections.groupProperty("specification"))
            .add(Projections.sum("currentQuantity")).add(Projections.sum("quantity"))
            .add(Projections.sum("issueQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (categoryId != null) {
        criteria.add(Restrictions.eq("itemAlias.subCategory.id", categoryId));
    }/*ww  w  . j  a v a2 s  . c o m*/
    if (!StringUtils.isBlank(itemName)) {
        criteria.add(Restrictions.like("itemAlias.name", "%" + itemName + "%"));
    }
    if (!StringUtils.isBlank(fromDate) && StringUtils.isBlank(toDate)) {
        String startFromDate = fromDate + " 00:00:00";
        String endFromDate = fromDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startFromDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endFromDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = toDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (!StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = fromDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listInventorySubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    }

    criteria.setProjection(proList);
    if (max > 0) {
        criteria.setFirstResult(min).setMaxResults(max);
    }
    List<Object> lst = criteria.list();
    if (lst == null || lst.size() == 0) {
        return null;
    }
    List<InventoryStoreItemTransactionDetail> list = new ArrayList<InventoryStoreItemTransactionDetail>();
    for (int i = 0; i < lst.size(); i++) {
        Object[] row = (Object[]) lst.get(i);
        InventoryStoreItemTransactionDetail tDetail = new InventoryStoreItemTransactionDetail();
        tDetail.setItem((InventoryItem) row[0]);
        tDetail.setSpecification((InventoryItemSpecification) row[1]);
        tDetail.setCurrentQuantity((Integer) row[2]);
        tDetail.setQuantity((Integer) row[3]);
        tDetail.setIssueQuantity((Integer) row[4]);
        list.add(tDetail);
    }

    return list;
}

From source file:org.openmrs.module.inventory.db.hibernate.HibernateInventoryDAO.java

License:Open Source License

@Override
public Integer countStoreItemViewStockBalance(Integer storeId, Integer categoryId, String itemName,
        String fromDate, String toDate) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreItemTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .createAlias("transactionDetail.item", "itemAlias");

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("item")).add(Projections.groupProperty("specification"))
            .add(Projections.sum("currentQuantity")).add(Projections.sum("quantity"))
            .add(Projections.sum("issueQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (categoryId != null) {
        criteria.add(Restrictions.eq("itemAlias.subCategory.id", categoryId));
    }/*ww  w.  j  a  v  a 2  s . c o  m*/
    if (!StringUtils.isBlank(itemName)) {
        criteria.add(Restrictions.like("itemAlias.name", "%" + itemName + "%"));
    }
    if (!StringUtils.isBlank(fromDate) && StringUtils.isBlank(toDate)) {
        String startFromDate = fromDate + " 00:00:00";
        String endFromDate = fromDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startFromDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endFromDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = toDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (!StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = fromDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listInventorySubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    }
    criteria.setProjection(proList);
    List<Object> list = criteria.list();
    Number total = 0;
    if (!CollectionUtils.isEmpty(list)) {
        total = (Number) list.size();
    }
    return total.intValue();
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source 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;//from w w w  .  j  a  va2s  .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 (attribute.equals("valueDatetime")) {
            // pass -- same column name
        } else if (attribute.equals("obsDatetime")) {
            // pass -- same column name
        } else if (attribute.equals("location")) {
            // pass -- same column name
            classNames.add("obs.location");
            attribute = "location.name";
        } else if (attribute.equals("comment")) {
            // pass -- same column name
        } else if (attribute.equals("encounterType")) {
            classNames.add("obs.encounter");
            classNames.add("encounter.encounterType");
            attribute = "encounterType.name";
        } else if (attribute.equals("provider")) {
            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(Expression.eq("obs.concept", c));
    criteria.add(Expression.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.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
// TODO: this method seems to be missing a check for voided==false.
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;/* w  ww  .j  a  va2  s .  co  m*/

    // make 'patient.**' reference 'patient' like alias instead of object
    if (className.equals("org.openmrs.Patient"))
        criteria = sessionFactory.getCurrentSession().createCriteria("org.openmrs.Patient", "patient");
    else if (className.equals("org.openmrs.Person"))
        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 (className.equals("org.openmrs.Person"))
            // 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(Expression.eq("personVoided", false));
        else
            // this is here to support PersonName and PersonAddress
            criteria.add(Expression.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(Expression.eq("voided", false));
    }
    criteria.setProjection(projectionList);

    // add 'preferred' sort order if necessary
    try {
        boolean hasPreferred = false;
        for (Field f : Class.forName(className).getDeclaredFields()) {
            if (f.getName().equals("preferred"))
                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.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

/**
 * @param patients// w w  w  .  java2  s  . c o m
 * @param types List<PatientIdentifierTypes> 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;
}