Example usage for org.hibernate.criterion Projections max

List of usage examples for org.hibernate.criterion Projections max

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections max.

Prototype

public static AggregateProjection max(String propertyName) 

Source Link

Document

A property maximum value projection

Usage

From source file:org.openbravo.common.actionhandler.OrderCreatePOLines.java

License:Open Source License

private void createOrderLines(JSONObject jsonRequest) throws JSONException, OBException {
    JSONArray selectedLines = jsonRequest.getJSONArray("_selection");
    final String strOrderId = jsonRequest.getString("C_Order_ID");
    Order order = OBDal.getInstance().get(Order.class, strOrderId);
    // if no lines selected don't do anything.
    OBCriteria<OrderLine> obc = OBDal.getInstance().createCriteria(OrderLine.class);
    obc.add(Restrictions.eq(OrderLine.PROPERTY_SALESORDER, order));
    obc.setProjection(Projections.max(OrderLine.PROPERTY_LINENO));
    Long lineNo = 0L;/*from   w  ww. j a  v a2s  .  c  o  m*/
    Object o = obc.uniqueResult();
    if (o != null) {
        lineNo = (Long) o;
    }

    for (int i = 0; i < selectedLines.length(); i++) {
        JSONObject selectedLine = selectedLines.getJSONObject(i);
        log.debug("{}", selectedLine);

        OrderLine newOrderLine = OBProvider.getInstance().get(OrderLine.class);
        newOrderLine.setSalesOrder(order);
        newOrderLine.setOrganization(order.getOrganization());
        lineNo = lineNo + 10L;
        newOrderLine.setLineNo(lineNo);
        newOrderLine.setOrderDate(order.getOrderDate());
        newOrderLine.setWarehouse(order.getWarehouse());
        newOrderLine.setCurrency(order.getCurrency());

        Product product = OBDal.getInstance().get(Product.class, selectedLine.getString("product"));
        if (product.getAttributeSetValue() != null && "D".equals(product.getUseAttributeSetValueAs())) {
            newOrderLine.setAttributeSetValue(product.getAttributeSetValue());
        }
        UOM uom = OBDal.getInstance().get(UOM.class, selectedLine.get("product$uOM"));

        newOrderLine.setProduct(product);

        newOrderLine.setUOM(uom);
        // Ordered Quantity = returned quantity.
        BigDecimal qtyOrdered = new BigDecimal(selectedLine.getString("orderedQuantity"));
        newOrderLine.setOrderedQuantity(qtyOrdered);

        List<Object> parameters = new ArrayList<Object>();
        parameters.add(product.getId());
        parameters.add(order.getOrderDate());
        parameters.add(order.getOrganization().getId());
        parameters.add(order.getWarehouse().getId());
        parameters.add(order.getPartnerAddress().getId());
        parameters.add(order.getInvoiceAddress().getId());
        if (order.getProject() != null) {
            parameters.add(order.getProject().getId());
        } else {
            parameters.add(null);
        }
        parameters.add("N");

        String taxId = (String) CallStoredProcedure.getInstance().call("C_Gettax", parameters, null);
        if (taxId == null || "".equals(taxId)) {
            Map<String, String> errorParameters = new HashMap<String, String>();
            errorParameters.put("product", product.getName());
            String message = OBMessageUtils.messageBD("NoTaxFoundForProduct");
            throw new OBException(OBMessageUtils.parseTranslation(message, errorParameters));
        }
        TaxRate tax = OBDal.getInstance().get(TaxRate.class, taxId);
        newOrderLine.setTax(tax);

        // Price
        BigDecimal unitPrice, netPrice, grossPrice, stdPrice, limitPrice, grossAmt, netListPrice,
                grossListPrice;
        stdPrice = BigDecimal.ZERO;
        final int pricePrecision = order.getCurrency().getPricePrecision().intValue();
        final int stdPrecision = order.getCurrency().getStandardPrecision().intValue();

        unitPrice = new BigDecimal(selectedLine.getString("standardPrice"));
        limitPrice = netListPrice = grossListPrice = stdPrice = unitPrice;

        if (order.getPriceList().isPriceIncludesTax()) {
            grossPrice = unitPrice;
            grossAmt = grossPrice.multiply(qtyOrdered).setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);
            netPrice = FinancialUtils.calculateNetFromGross(tax.getId(), grossAmt, pricePrecision, grossAmt,
                    qtyOrdered);
            limitPrice = netPrice;
            stdPrice = netPrice;
            netListPrice = netPrice;
        } else {
            netPrice = unitPrice;
            grossListPrice = grossAmt = grossPrice = BigDecimal.ZERO;
        }

        newOrderLine.setUnitPrice(netPrice);
        newOrderLine.setGrossUnitPrice(grossPrice);
        newOrderLine.setListPrice(netListPrice);
        newOrderLine.setGrossListPrice(grossListPrice);
        newOrderLine.setPriceLimit(limitPrice);
        newOrderLine.setStandardPrice(stdPrice);
        newOrderLine.setLineNetAmount(
                netPrice.multiply(qtyOrdered).setScale(stdPrecision, BigDecimal.ROUND_HALF_UP));
        newOrderLine.setLineGrossAmount(grossAmt);

        List<OrderLine> orderLines = order.getOrderLineList();
        orderLines.add(newOrderLine);
        order.setOrderLineList(orderLines);

        OBDal.getInstance().save(newOrderLine);
        OBDal.getInstance().save(order);
        OBDal.getInstance().flush();
    }

}

From source file:org.openbravo.common.actionhandler.SRMOPickEditLines.java

License:Open Source License

private void createOrderLines(JSONObject jsonRequest, List<String> idList) throws JSONException, OBException {
    JSONObject grid = jsonRequest.getJSONObject("_params").getJSONObject("grid");
    JSONArray selectedLines = grid.getJSONArray("_selection");
    JSONObject orphanlinesgrid = jsonRequest.getJSONObject("_params").getJSONObject("orphanlinesgrid");
    JSONArray selectedLinesOrphan = orphanlinesgrid.getJSONArray("_selection");

    final String strOrderId = jsonRequest.getString("C_Order_ID");
    Order order = OBDal.getInstance().get(Order.class, strOrderId);
    boolean isSOTrx = order.isSalesTransaction();
    // if no lines selected don't do anything.
    if (selectedLines.length() == 0) {
        removeNonSelectedLines(idList, order);
        return;// w  w  w. j  a  v  a 2s. c om
    }
    OBCriteria<OrderLine> obc = OBDal.getInstance().createCriteria(OrderLine.class);
    obc.add(Restrictions.eq(OrderLine.PROPERTY_SALESORDER, order));
    obc.setProjection(Projections.max(OrderLine.PROPERTY_LINENO));
    Long lineNo = 0L;
    Object o = obc.list().get(0);
    if (o != null) {
        lineNo = (Long) o;
    }
    for (long i = 0; i < selectedLinesOrphan.length(); i++) {
        JSONObject selectedLineOrphan = selectedLinesOrphan.getJSONObject((int) i);
        selectedLines.put(selectedLineOrphan);
    }

    for (long i = 0; i < selectedLines.length(); i++) {
        JSONObject selectedLine = selectedLines.getJSONObject((int) i);
        log.debug(selectedLine);
        if (selectedLine.get("returned").equals(null)) {
            continue;
        }

        OrderLine newOrderLine = null;
        boolean notExistsOrderLine = selectedLine.get("salesOrderLine").equals(null)
                || "".equals(selectedLine.get("salesOrderLine"));
        if (notExistsOrderLine) {
            newOrderLine = OBProvider.getInstance().get(OrderLine.class);
            newOrderLine.setSalesOrder(order);
            newOrderLine.setOrganization(order.getOrganization());
            lineNo = lineNo + 10L;
            newOrderLine.setLineNo(lineNo);
            newOrderLine.setOrderDate(order.getOrderDate());
            newOrderLine.setWarehouse(order.getWarehouse());
            newOrderLine.setCurrency(order.getCurrency());
        } else {
            newOrderLine = OBDal.getInstance().get(OrderLine.class, selectedLine.get("salesOrderLine"));
            idList.remove(selectedLine.get("salesOrderLine"));
        }

        ShipmentInOutLine shipmentLine = OBDal.getInstance().get(ShipmentInOutLine.class,
                selectedLine.getString("goodsShipmentLine"));
        Product product = OBDal.getInstance().get(Product.class, selectedLine.getString("product"));
        AttributeSetInstance asi = null;
        if (!selectedLine.get("attributeSetValue").equals(null)) {
            asi = OBDal.getInstance().get(AttributeSetInstance.class,
                    selectedLine.getString("attributeSetValue"));
        }
        UOM uom = OBDal.getInstance().get(UOM.class, selectedLine.get("uOM"));

        newOrderLine.setGoodsShipmentLine(shipmentLine);
        newOrderLine.setProduct(product);
        newOrderLine.setAttributeSetValue(asi);
        newOrderLine.setUOM(uom);
        // Ordered Quantity = returned quantity.
        BigDecimal qtyReturned = new BigDecimal(selectedLine.getString("returned")).negate();
        newOrderLine.setOrderedQuantity(qtyReturned);

        TaxRate tax = null;
        if (shipmentLine != null && shipmentLine.getSalesOrderLine() != null) {
            tax = shipmentLine.getSalesOrderLine().getTax();
        } else {
            String taxId = "";
            if (selectedLine.get("tax").equals(null) || selectedLine.get("tax").equals("")) {
                List<Object> parameters = new ArrayList<Object>();

                parameters.add(product.getId());
                parameters.add(order.getOrderDate());
                parameters.add(order.getOrganization().getId());
                parameters.add(order.getWarehouse().getId());
                parameters.add(order.getPartnerAddress().getId());
                parameters.add(order.getInvoiceAddress().getId());
                if (order.getProject() != null) {
                    parameters.add(order.getProject().getId());
                } else {
                    parameters.add(null);
                }
                parameters.add("Y");

                taxId = (String) CallStoredProcedure.getInstance().call("C_Gettax", parameters, null);
                if (taxId == null || "".equals(taxId)) {
                    Map<String, String> errorParameters = new HashMap<String, String>();
                    errorParameters.put("product", product.getName());
                    String message = OBMessageUtils.messageBD("NoTaxFoundForProduct");
                    throw new OBException(OBMessageUtils.parseTranslation(message, errorParameters));
                }
            } else {
                taxId = selectedLine.getString("tax");
            }
            tax = OBDal.getInstance().get(TaxRate.class, taxId);
        }
        newOrderLine.setTax(tax);

        // Price
        BigDecimal unitPrice, netPrice, grossPrice, stdPrice, limitPrice, grossAmt, netListPrice,
                grossListPrice;
        stdPrice = BigDecimal.ZERO;
        final int pricePrecision = order.getCurrency().getPricePrecision().intValue();
        final int stdPrecision = order.getCurrency().getStandardPrecision().intValue();

        if (selectedLine.get("unitPrice").equals(null) || "".equals(selectedLine.get("unitPrice"))) {
            try {
                final ProductPrice pp = FinancialUtils.getProductPrice(product, order.getOrderDate(), isSOTrx,
                        order.getPriceList());
                unitPrice = pp.getStandardPrice();
                limitPrice = pp.getPriceLimit();
                netListPrice = pp.getListPrice();
                grossListPrice = pp.getListPrice();
                stdPrice = pp.getStandardPrice();
            } catch (OBException e) {
                // Product not found in price list. Prices default to ZERO
                unitPrice = limitPrice = netListPrice = grossListPrice = stdPrice = BigDecimal.ZERO;
            }
        } else {
            unitPrice = new BigDecimal(selectedLine.getString("unitPrice"));
            if (shipmentLine != null && shipmentLine.getSalesOrderLine() != null) {
                limitPrice = shipmentLine.getSalesOrderLine().getPriceLimit();
                netListPrice = shipmentLine.getSalesOrderLine().getListPrice();
                grossListPrice = shipmentLine.getSalesOrderLine().getGrossListPrice();
                stdPrice = shipmentLine.getSalesOrderLine().getStandardPrice();
            } else {
                limitPrice = netListPrice = grossListPrice = stdPrice = unitPrice;
            }
        }

        if (order.getPriceList().isPriceIncludesTax()) {
            grossPrice = unitPrice;
            grossAmt = grossPrice.multiply(qtyReturned).setScale(stdPrecision, BigDecimal.ROUND_HALF_UP);
            netPrice = FinancialUtils.calculateNetFromGross(tax.getId(), grossAmt, pricePrecision, grossAmt,
                    qtyReturned);
            limitPrice = netPrice;
            stdPrice = netPrice;
            netListPrice = netPrice;
        } else {
            netPrice = unitPrice;
            grossListPrice = grossAmt = grossPrice = BigDecimal.ZERO;
        }

        newOrderLine.setUnitPrice(netPrice);
        newOrderLine.setGrossUnitPrice(grossPrice);
        newOrderLine.setListPrice(netListPrice);
        newOrderLine.setGrossListPrice(grossListPrice);
        newOrderLine.setPriceLimit(limitPrice);
        newOrderLine.setStandardPrice(stdPrice);
        newOrderLine.setLineNetAmount(
                netPrice.multiply(qtyReturned).setScale(stdPrecision, BigDecimal.ROUND_HALF_UP));
        newOrderLine.setLineGrossAmount(grossAmt);

        if (!selectedLine.get("returnReason").equals(null)) {
            newOrderLine.setReturnReason(
                    OBDal.getInstance().get(ReturnReason.class, selectedLine.getString("returnReason")));
        } else {
            newOrderLine.setReturnReason(order.getReturnReason());
        }

        if (notExistsOrderLine) {
            List<OrderLine> orderLines = order.getOrderLineList();
            orderLines.add(newOrderLine);
            order.setOrderLineList(orderLines);
        }

        OBDal.getInstance().save(newOrderLine);
        OBDal.getInstance().save(order);
        OBDal.getInstance().flush();
    }

    removeNonSelectedLines(idList, order);
}

From source file:org.openbravo.erpCommon.ad_forms.AcctServer.java

License:Open Source License

/**
 * Is Document convertible to currency and Conversion Type
 * /*from  w w w. j  ava  2s .  c  om*/
 * @param acctSchema
 *          accounting schema
 * @return true, if convertible to accounting currency
 */
public boolean isConvertible(AcctSchema acctSchema, ConnectionProvider conn) throws ServletException {
    // No Currency in document
    if (NO_CURRENCY.equals(C_Currency_ID)) {
        // if (log4j.isDebugEnabled())
        // log4j.debug("AcctServer - isConvertible (none) - " + DocumentNo);
        return true;
    }
    // Get All Currencies
    Vector<Object> set = new Vector<Object>();
    set.addElement(C_Currency_ID);
    for (int i = 0; p_lines != null && i < p_lines.length; i++) {
        String currency = p_lines[i].m_C_Currency_ID;
        if (currency != null && !currency.equals(""))
            set.addElement(currency);
    }

    // just one and the same
    if (set.size() == 1 && acctSchema.m_C_Currency_ID.equals(C_Currency_ID)) {
        // if (log4j.isDebugEnabled()) log4j.debug
        // ("AcctServer - isConvertible (same) Cur=" + C_Currency_ID + " - "
        // + DocumentNo);
        return true;
    }
    boolean convertible = true;
    for (int i = 0; i < set.size() && convertible == true; i++) {
        // if (log4j.isDebugEnabled()) log4j.debug
        // ("AcctServer - get currency");
        String currency = (String) set.elementAt(i);
        if (currency == null)
            currency = "";
        // if (log4j.isDebugEnabled()) log4j.debug
        // ("AcctServer - currency = " + currency);
        if (!currency.equals(acctSchema.m_C_Currency_ID)) {
            // if (log4j.isDebugEnabled()) log4j.debug
            // ("AcctServer - get converted amount (init)");
            String amt = "";
            OBQuery<ConversionRateDoc> conversionQuery = null;
            int conversionCount = 0;
            if (AD_Table_ID.equals(TABLEID_Invoice)) {
                conversionQuery = OBDal.getInstance().createQuery(ConversionRateDoc.class,
                        "invoice = '" + Record_ID + "' and currency='" + currency + "' and toCurrency='"
                                + acctSchema.m_C_Currency_ID + "'");
            } else if (AD_Table_ID.equals(TABLEID_Payment)) {
                conversionQuery = OBDal.getInstance().createQuery(ConversionRateDoc.class,
                        "payment = '" + Record_ID + "' and currency='" + currency + "' and toCurrency='"
                                + acctSchema.m_C_Currency_ID + "'");
            } else if (AD_Table_ID.equals(TABLEID_Transaction)) {
                conversionQuery = OBDal.getInstance().createQuery(ConversionRateDoc.class,
                        "financialAccountTransaction = '" + Record_ID + "' and currency='" + currency
                                + "' and toCurrency='" + acctSchema.m_C_Currency_ID + "'");
            }
            if (conversionQuery != null) {
                conversionCount = conversionQuery.count();
            }
            if (conversionCount > 0) {
                List<ConversionRateDoc> conversionRate = conversionQuery.list();
                OBCriteria<Currency> currencyCrit = OBDal.getInstance().createCriteria(Currency.class);
                currencyCrit.add(Restrictions.eq(Currency.PROPERTY_ID, acctSchema.m_C_Currency_ID));
                currencyCrit.setProjection(Projections.max(Currency.PROPERTY_STANDARDPRECISION));
                Long precision = 0L;
                if (currencyCrit.count() > 0) {
                    List<Currency> toCurrency = currencyCrit.list();
                    precision = toCurrency.get(0).getStandardPrecision();
                }
                BigDecimal convertedAmount = new BigDecimal("1").multiply(conversionRate.get(0).getRate());
                amt = convertedAmount.setScale(precision.intValue(), RoundingMode.HALF_UP).toString();
            }
            if (("").equals(amt) || amt == null)
                amt = getConvertedAmt("1", currency, acctSchema.m_C_Currency_ID, DateAcct,
                        acctSchema.m_CurrencyRateType, AD_Client_ID, AD_Org_ID, conn);
            // if (log4j.isDebugEnabled()) log4j.debug
            // ("get converted amount (end)");
            if (amt == null || ("").equals(amt)) {
                convertible = false;
                log4j.warn("AcctServer - isConvertible NOT from " + currency + " - " + DocumentNo);
            } else if (log4j.isDebugEnabled())
                log4j.debug("AcctServer - isConvertible from " + currency);
        }
    }
    // if (log4j.isDebugEnabled()) log4j.debug
    // ("AcctServer - isConvertible=" + convertible + ", AcctSchemaCur=" +
    // acctSchema.m_C_Currency_ID + " - " + DocumentNo);
    return convertible;
}

From source file:org.openbravo.service.datasource.ADTreeDatasourceService.java

License:Open Source License

/**
 * Returns the sequence number of a node that has just been moved, and recompontes the sequence
 * number of its peers when needed//from   w ww . j av a  2s  .  c o  m
 * 
 * @param tree
 *          the ADTree being modified
 * @param prevNodeId
 *          id of the node that will be placed just before the updated node after it has been
 *          moved
 * @param nextNodeId
 *          id of the node that will be placed just after the updated node after it has been moved
 * @param newParentId
 *          id of the parent node of the node whose sequence number is being calculated
 * @return The sequence number of the node that has just been reparented
 * @throws Exception
 */
private Long calculateSequenceNumberAndRecompute(Tree tree, String prevNodeId, String nextNodeId,
        String newParentId) throws Exception {
    Long seqNo = null;
    if (prevNodeId == null && nextNodeId == null) {
        // Only child, no need to recompute sequence numbers
        seqNo = 10L;
    } else if (nextNodeId == null) {
        // Last positioned child. Pick the highest sequence number of its brothers and add 10
        // No need to recompute sequence numbers
        OBCriteria<TreeNode> maxSeqNoCriteria = OBDal.getInstance().createCriteria(TreeNode.class);
        maxSeqNoCriteria.setFilterOnActive(false);
        maxSeqNoCriteria.add(Restrictions.eq(TreeNode.PROPERTY_TREE, tree));
        maxSeqNoCriteria.add(Restrictions.eq(TreeNode.PROPERTY_REPORTSET, newParentId));
        maxSeqNoCriteria.setProjection(Projections.max(TreeNode.PROPERTY_SEQUENCENUMBER));
        Long maxSeqNo = (Long) maxSeqNoCriteria.uniqueResult();
        seqNo = maxSeqNo + 10;
    } else {
        // Sequence numbers of the nodes that are positioned after the new one needs to be recomputed
        OBCriteria<TreeNode> nextNodeCriteria = OBDal.getInstance().createCriteria(TreeNode.class);
        nextNodeCriteria.setFilterOnActive(false);
        nextNodeCriteria.add(Restrictions.eq(TreeNode.PROPERTY_TREE, tree));
        nextNodeCriteria.add(Restrictions.eq(TreeNode.PROPERTY_NODE, nextNodeId));
        TreeNode nextNode = (TreeNode) nextNodeCriteria.uniqueResult();
        seqNo = nextNode.getSequenceNumber();
        recomputeSequenceNumbers(tree, newParentId, seqNo);
    }
    return seqNo;
}

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

License:Open Source License

/**
 * @see ReminderDAO#getLatestReminders(org.openmrs.Patient)
 *//*from  ww  w  .  j ava 2  s  . c  o  m*/
@Override
@SuppressWarnings("unchecked")
public List<Reminder> getLatestReminders(final Patient patient) throws DAOException {

    Criteria criteria;

    criteria = sessionFactory.getCurrentSession().createCriteria(Reminder.class);
    criteria.add(Restrictions.eq("patient", patient));
    criteria.setProjection(Projections.projectionList().add(Projections.max("dateCreated"))
            .add(Projections.max("reminderDatetime")));
    List<Object[]> objects = criteria.list();

    Object[] dates = new Object[2];
    for (Object[] object : objects)
        dates = object;

    criteria = sessionFactory.getCurrentSession().createCriteria(Reminder.class);
    criteria.add(Restrictions.eq("patient", patient));
    // we found valid date object for the latest date created
    if (isValidDateObject(dates[0]))
        criteria.add(Property.forName("dateCreated").ge(truncate((Date) dates[0])));
    // we found valid date object for the latest encounter datetime
    if (isValidDateObject(dates[1]))
        criteria.add(Property.forName("reminderDatetime").ge(truncate((Date) dates[1])));
    criteria.addOrder(Order.desc("dateCreated"));
    return criteria.list();
}

From source file:org.openmrs.module.drugorders.api.db.hibernate.HibernatedrugordersDAO.java

License:Mozilla Public License

@Override
public int getLastGroupID() {
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(drugorders.class);
    crit.setProjection(Projections.property("id"));
    List l = crit.list();//from  w w  w .j av a2  s .  c  o m
    Iterator it = l.iterator();
    int groupId = 0;
    if (it.hasNext()) {
        Criteria critMax = sessionFactory.getCurrentSession().createCriteria(drugorders.class)
                .setProjection(Projections.max("groupId"));
        if (critMax.uniqueResult() == null)
            groupId = 0;
        else
            groupId = (Integer) critMax.uniqueResult();
    }

    return groupId;
}

From source file:org.openmrs.module.drugorders.api.db.hibernate.HibernateplanordersDAO.java

@Override
public int getLastPlanID() {
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(planorders.class);
    crit.setProjection(Projections.property("id"));
    List l = crit.list();//from w  ww. j a  v a 2s .c  om
    Iterator it = l.iterator();
    int planId = 0;
    if (it.hasNext()) {
        Criteria critMax = sessionFactory.getCurrentSession().createCriteria(planorders.class)
                .setProjection(Projections.max("standardPlanId"));
        if (critMax.uniqueResult() == null)
            planId = 0;
        else
            planId = (Integer) critMax.uniqueResult();
    }

    return planId;
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

License:Open Source License

/**
 * @see org.openmrs.module.sync.api.db.SyncDAO#getNextSyncRecord()
 *///from  w ww  .j  a  va2s .  c  o m
@SuppressWarnings("unchecked")
public SyncRecord getLatestRecord() throws DAOException {
    List<Integer> result = sessionFactory.getCurrentSession().createCriteria(SyncRecord.class)
            .setProjection(Projections.max("recordId")).list();

    if (result.size() < 1) {
        return null;
    } else {
        Integer maxRecordId = result.get(0);
        return getSyncRecord(maxRecordId);
    }
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

License:Open Source License

/**
 * @see org.openmrs.module.sync.api.SyncService#getPreviousRecord(SyncRecord)
 *//*from ww w.j a  v  a 2 s.  c om*/
public SyncRecord getPreviousRecord(SyncRecord record) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(SyncRecord.class);
    criteria.setProjection(Projections.max("recordId"));
    criteria.add(Restrictions.lt("recordId", record.getRecordId()));
    Object prevRecordId = criteria.uniqueResult();
    if (prevRecordId == null) {
        return null;
    }
    return getSyncRecord((Integer) prevRecordId);
}

From source file:org.opentaps.financials.domain.ledger.EncumbranceRepository.java

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public List<EncumbranceDetail> getEncumbranceDetails(String organizationPartyId,
        Map<String, String> accountingTags, Timestamp asOfDate) throws RepositoryException {
    Session session = null;// ww w .  j  a v a  2  s.co  m
    List<EncumbranceDetail> encumbranceDetails = null;

    try {
        session = getInfrastructure().getSession();

        // retrieve max snapshot time under asOfDate
        Criteria lastSnapshotDate = session.createCriteria(EncumbranceSnapshot.class);
        lastSnapshotDate.add(Restrictions.le(EncumbranceSnapshot.Fields.snapshotDatetime.getName(), asOfDate));
        lastSnapshotDate.setProjection(Projections.max(EncumbranceSnapshot.Fields.snapshotDatetime.getName()));
        List<Timestamp> snapshotMaxDate = lastSnapshotDate.list();
        Timestamp ts = snapshotMaxDate.get(0);
        if (ts == null) {
            Debug.logWarning("There is no encumbrance snapshot created before " + asOfDate.toString(), MODULE);
            return new ArrayList<EncumbranceDetail>();
        }
        Debug.logInfo("Using encumbrance snapshot from " + ts.toString(), MODULE);

        Criteria snapshot = session.createCriteria(EncumbranceSnapshot.class);
        snapshot.add(Restrictions.eq(EncumbranceSnapshot.Fields.snapshotDatetime.getName(), ts));
        List<EncumbranceSnapshot> snapshots = snapshot.list();

        String snapshotId = snapshots.get(0).getEncumbranceSnapshotId();

        Criteria details = session.createCriteria(EncumbranceDetail.class);
        details.add(Restrictions.eq(
                String.format("id.%1$s", EncumbranceDetail.Fields.encumbranceSnapshotId.getName()),
                snapshotId));
        details.add(
                Restrictions.eq(EncumbranceDetail.Fields.organizationPartyId.getName(), organizationPartyId));
        buildAccountingTagConditions(details, accountingTags);
        details.addOrder(
                Order.asc(String.format("id.%1$s", EncumbranceDetail.Fields.encumbranceDetailSeqId.getName())));
        encumbranceDetails = details.list();

    } catch (InfrastructureException e) {
        throw new RepositoryException(e.getMessage());
    } catch (HibernateException e) {
        throw new RepositoryException(e.getMessage());
    } finally {
        if (session != null) {
            session.close();
        }
    }

    return encumbranceDetails;
}