Example usage for java.util Calendar getActualMinimum

List of usage examples for java.util Calendar getActualMinimum

Introduction

In this page you can find the example usage for java.util Calendar getActualMinimum.

Prototype

public int getActualMinimum(int field) 

Source Link

Document

Returns the minimum value that the specified calendar field could have, given the time value of this Calendar.

Usage

From source file:com.s3d.webapps.util.time.DateUtils.java

/**
 * <p>Internal calculation method.</p>
 * //  www.j a  v a 2  s  .c om
 * @param val  the calendar
 * @param field  the field constant
 * @param modType  type to truncate, round or ceiling
 * @throws ArithmeticException if the year is over 280 million
 */
private static void modify(Calendar val, int field, int modType) {
    if (val.get(Calendar.YEAR) > 280000000) {
        throw new ArithmeticException("Calendar value too large for accurate calculations");
    }

    if (field == Calendar.MILLISECOND) {
        return;
    }

    // ----------------- Fix for LANG-59 ---------------------- START ---------------
    // see http://issues.apache.org/jira/browse/LANG-59
    //
    // Manually truncate milliseconds, seconds and minutes, rather than using
    // Calendar methods.

    Date date = val.getTime();
    long time = date.getTime();
    boolean done = false;

    // truncate milliseconds
    int millisecs = val.get(Calendar.MILLISECOND);
    if (MODIFY_TRUNCATE == modType || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

    // truncate seconds
    int seconds = val.get(Calendar.SECOND);
    if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) {
        time = time - (seconds * 1000L);
    }
    if (field == Calendar.MINUTE) {
        done = true;
    }

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) {
        time = time - (minutes * 60000L);
    }

    // reset time
    if (date.getTime() != time) {
        date.setTime(time);
        val.setTime(date);
    }
    // ----------------- Fix for LANG-59 ----------------------- END ----------------

    boolean roundUp = false;
    for (int i = 0; i < fields.length; i++) {
        for (int j = 0; j < fields[i].length; j++) {
            if (fields[i][j] == field) {
                //This is our field... we stop looping
                if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) {
                    if (field == DateUtils.SEMI_MONTH) {
                        //This is a special case that's hard to generalize
                        //If the date is 1, we round up to 16, otherwise
                        //  we subtract 15 days and add 1 month
                        if (val.get(Calendar.DATE) == 1) {
                            val.add(Calendar.DATE, 15);
                        } else {
                            val.add(Calendar.DATE, -15);
                            val.add(Calendar.MONTH, 1);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- START ---------------
                    } else if (field == Calendar.AM_PM) {
                        // This is a special case
                        // If the time is 0, we round up to 12, otherwise
                        //  we subtract 12 hours and add 1 day
                        if (val.get(Calendar.HOUR_OF_DAY) == 0) {
                            val.add(Calendar.HOUR_OF_DAY, 12);
                        } else {
                            val.add(Calendar.HOUR_OF_DAY, -12);
                            val.add(Calendar.DATE, 1);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- END ---------------
                    } else {
                        //We need at add one to this field since the
                        //  last number causes us to round up
                        val.add(fields[i][0], 1);
                    }
                }
                return;
            }
        }
        //We have various fields that are not easy roundings
        int offset = 0;
        boolean offsetSet = false;
        //These are special types of fields that require different rounding rules
        switch (field) {
        case DateUtils.SEMI_MONTH:
            if (fields[i][0] == Calendar.DATE) {
                //If we're going to drop the DATE field's value,
                //  we want to do this our own way.
                //We need to subtrace 1 since the date has a minimum of 1
                offset = val.get(Calendar.DATE) - 1;
                //If we're above 15 days adjustment, that means we're in the
                //  bottom half of the month and should stay accordingly.
                if (offset >= 15) {
                    offset -= 15;
                }
                //Record whether we're in the top or bottom half of that range
                roundUp = offset > 7;
                offsetSet = true;
            }
            break;
        case Calendar.AM_PM:
            if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                //If we're going to drop the HOUR field's value,
                //  we want to do this our own way.
                offset = val.get(Calendar.HOUR_OF_DAY);
                if (offset >= 12) {
                    offset -= 12;
                }
                roundUp = offset >= 6;
                offsetSet = true;
            }
            break;
        }
        if (!offsetSet) {
            int min = val.getActualMinimum(fields[i][0]);
            int max = val.getActualMaximum(fields[i][0]);
            //Calculate the offset from the minimum allowed value
            offset = val.get(fields[i][0]) - min;
            //Set roundUp if this is more than half way between the minimum and maximum
            roundUp = offset > ((max - min) / 2);
        }
        //We need to remove this field
        if (offset != 0) {
            val.set(fields[i][0], val.get(fields[i][0]) - offset);
        }
    }
    throw new IllegalArgumentException("The field " + field + " is not supported");

}

From source file:com.xunlei.util.DateUtils.java

/**
 * <p>/*from  w w w.ja va  2  s . co  m*/
 * Internal calculation method.
 * </p>
 * 
 * @param val the calendar
 * @param field the field constant
 * @param modType type to truncate, round or ceiling
 * @throws ArithmeticException if the year is over 280 million
 */
static void modify(Calendar val, int field, int modType) {
    if (val.get(Calendar.YEAR) > 280000000) {
        throw new ArithmeticException("Calendar value too large for accurate calculations");
    }

    if (field == Calendar.MILLISECOND) {
        return;
    }

    // ----------------- Fix for LANG-59 ---------------------- START ---------------
    // see http://issues.apache.org/jira/browse/LANG-59
    //
    // Manually truncate milliseconds, seconds and minutes, rather than using
    // Calendar methods.

    Date date = val.getTime();
    long time = date.getTime();
    boolean done = false;

    // truncate milliseconds
    int millisecs = val.get(Calendar.MILLISECOND);
    if (MODIFY_TRUNCATE == modType || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

    // truncate seconds
    int seconds = val.get(Calendar.SECOND);
    if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) {
        time = time - (seconds * 1000L);
    }
    if (field == Calendar.MINUTE) {
        done = true;
    }

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) {
        time = time - (minutes * 60000L);
    }

    // reset time
    if (date.getTime() != time) {
        date.setTime(time);
        val.setTime(date);
    }
    // ----------------- Fix for LANG-59 ----------------------- END ----------------

    boolean roundUp = false;
    for (int i = 0; i < fields.length; i++) {
        for (int j = 0; j < fields[i].length; j++) {
            if (fields[i][j] == field) {
                // This is our field... we stop looping
                if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) {
                    if (field == DateUtils.SEMI_MONTH) {
                        // This is a special case that's hard to generalize
                        // If the date is 1, we round up to 16, otherwise
                        // we subtract 15 days and add 1 month
                        if (val.get(Calendar.DATE) == 1) {
                            val.add(Calendar.DATE, 15);
                        } else {
                            val.add(Calendar.DATE, -15);
                            val.add(Calendar.MONTH, 1);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- START ---------------
                    } else if (field == Calendar.AM_PM) {
                        // This is a special case
                        // If the time is 0, we round up to 12, otherwise
                        // we subtract 12 hours and add 1 day
                        if (val.get(Calendar.HOUR_OF_DAY) == 0) {
                            val.add(Calendar.HOUR_OF_DAY, 12);
                        } else {
                            val.add(Calendar.HOUR_OF_DAY, -12);
                            val.add(Calendar.DATE, 1);
                        }
                        // ----------------- Fix for LANG-440 ---------------------- END ---------------
                    } else {
                        // We need at add one to this field since the
                        // last number causes us to round up
                        val.add(fields[i][0], 1);
                    }
                }
                return;
            }
        }
        // We have various fields that are not easy roundings
        int offset = 0;
        boolean offsetSet = false;
        // These are special types of fields that require different rounding rules
        switch (field) {
        case DateUtils.SEMI_MONTH:
            if (fields[i][0] == Calendar.DATE) {
                // If we're going to drop the DATE field's value,
                // we want to do this our own way.
                // We need to subtrace 1 since the date has a minimum of 1
                offset = val.get(Calendar.DATE) - 1;
                // If we're above 15 days adjustment, that means we're in the
                // bottom half of the month and should stay accordingly.
                if (offset >= 15) {
                    offset -= 15;
                }
                // Record whether we're in the top or bottom half of that range
                roundUp = offset > 7;
                offsetSet = true;
            }
            break;
        case Calendar.AM_PM:
            if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                // If we're going to drop the HOUR field's value,
                // we want to do this our own way.
                offset = val.get(Calendar.HOUR_OF_DAY);
                if (offset >= 12) {
                    offset -= 12;
                }
                roundUp = offset >= 6;
                offsetSet = true;
            }
            break;
        }
        if (!offsetSet) {
            int min = val.getActualMinimum(fields[i][0]);
            int max = val.getActualMaximum(fields[i][0]);
            // Calculate the offset from the minimum allowed value
            offset = val.get(fields[i][0]) - min;
            // Set roundUp if this is more than half way between the minimum and maximum
            roundUp = offset > ((max - min) / 2);
        }
        // We need to remove this field
        if (offset != 0) {
            val.set(fields[i][0], val.get(fields[i][0]) - offset);
        }
    }
    throw new IllegalArgumentException("The field " + field + " is not supported");

}

From source file:org.openbravo.test.costing.TestCosting.java

@SuppressWarnings("unchecked")
private void assertDocumentPost(BaseOBObject document, String productId,
        List<DocumentPostAssert> documentPostAssertList) {
    try {/*from   ww  w.j  a  v a  2  s.c om*/

        BaseOBObject doc = OBDal.getInstance().get(document.getClass(), document.getId());
        if (!doc.get("posted").equals("Y")) {
            OBDal.getInstance().refresh(doc);
            Thread.sleep(5000);
            for (int i = 0; i < 10 && !doc.get("posted").equals("Y"); i++) {
                postDocument(doc);
                doc = OBDal.getInstance().get(doc.getClass(), doc.getId());
                OBDal.getInstance().refresh(doc);
                Thread.sleep(1000);
            }
        }

        assertEquals(doc.get("posted"), "Y");

        final OBCriteria<Table> criteria1 = OBDal.getInstance().createCriteria(Table.class);
        criteria1.add(Restrictions.eq(Table.PROPERTY_NAME, doc.getEntityName()));
        Table table = criteria1.list().get(0);

        final OBCriteria<AccountingFact> criteria2 = OBDal.getInstance().createCriteria(AccountingFact.class);
        criteria2.add(Restrictions.eq(AccountingFact.PROPERTY_RECORDID, doc.getId()));
        criteria2.add(Restrictions.eq(AccountingFact.PROPERTY_TABLE, table));
        criteria2.addOrderBy(AccountingFact.PROPERTY_SEQUENCENUMBER, true);
        String groupId = criteria2.list().get(0).getGroupID();

        assertEquals(criteria2.list().size(), documentPostAssertList.size());

        int i = 0;
        for (AccountingFact accountingFact : criteria2.list()) {

            String lineListProperty = Character.toLowerCase(doc.getEntityName().charAt(0))
                    + doc.getEntityName().substring(1) + "LineList";

            BaseOBObject line = null;
            if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                if (i % 2 == 0) {
                    line = ((ReceiptInvoiceMatch) doc).getGoodsShipmentLine();
                } else {
                    line = ((ReceiptInvoiceMatch) doc).getInvoiceLine();
                }
            } else if (doc.getEntityName().equals(ProductionTransaction.ENTITY_NAME)) {
                StringBuffer where = new StringBuffer();
                where.append(" as t1 ");
                where.append("\n left join t1." + ProductionLine.PROPERTY_PRODUCTIONPLAN + " t2");
                where.append("\n where t2." + ProductionPlan.PROPERTY_PRODUCTION + " = :productionTransaction");
                where.append("\n order by t1." + ProductionLine.PROPERTY_LINENO);
                OBQuery<ProductionLine> hql = OBDal.getInstance().createQuery(ProductionLine.class,
                        where.toString());
                hql.setNamedParameter("productionTransaction",
                        OBDal.getInstance().get(ProductionTransaction.class, doc.getId()));
                line = hql.list().get(i / 2);
            } else if (doc.getEntityName().equals(CostAdjustment.ENTITY_NAME)) {
                final OBCriteria<CostAdjustmentLine> criteria3 = OBDal.getInstance()
                        .createCriteria(CostAdjustmentLine.class);
                criteria3.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_COSTADJUSTMENT, doc));
                criteria3.add(Restrictions.eq(CostAdjustmentLine.PROPERTY_NEEDSPOSTING, true));
                criteria3.addOrderBy(CostAdjustmentLine.PROPERTY_LINENO, true);
                line = criteria3.list().get(i / 2);
            } else if (productId != null && (productId.equals(LANDEDCOSTTYPE1_ID)
                    || productId.equals(LANDEDCOSTTYPE2_ID) || productId.equals(LANDEDCOSTTYPE3_ID))) {
                line = ((List<BaseOBObject>) OBDal.getInstance().get(doc.getClass(), doc.getId())
                        .get(lineListProperty)).get(0);
            } else if (doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                StringBuffer where = new StringBuffer();
                where.append(" as t1 ");
                where.append("\n join t1." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTRECEIPT + " t2");
                where.append("\n join t1." + LCReceiptLineAmt.PROPERTY_LANDEDCOSTCOST + " t3");
                where.append("\n join t1." + LCReceiptLineAmt.PROPERTY_GOODSSHIPMENTLINE + " t4");
                where.append("\n left join t4." + ShipmentInOutLine.PROPERTY_SHIPMENTRECEIPT + " t5");
                where.append("\n where t2." + LCReceipt.PROPERTY_LANDEDCOST + " = :landedCost");
                where.append("\n order by t3." + LandedCostCost.PROPERTY_LINENO);
                where.append("\n , t5." + ShipmentInOut.PROPERTY_DOCUMENTNO);
                where.append("\n , t4." + ShipmentInOutLine.PROPERTY_LINENO);
                OBQuery<LCReceiptLineAmt> hql = OBDal.getInstance().createQuery(LCReceiptLineAmt.class,
                        where.toString());
                LandedCost landedCost = OBDal.getInstance().get(LandedCost.class, doc.getId());
                hql.setNamedParameter("landedCost", landedCost);
                line = hql.list().get(i / 2);
            } else if (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)) {
                if (((LandedCostCost) doc).getLandedCostMatchedList().size() == 1) {
                    line = ((LandedCostCost) doc).getLandedCostMatchedList().get(0);
                } else if (!((LandedCostCost) doc).getAmount().setScale(2, BigDecimal.ROUND_HALF_UP).equals(
                        ((LandedCostCost) doc).getMatchingAmount().setScale(2, BigDecimal.ROUND_HALF_UP))
                        && ((LandedCostCost) doc).isMatchingAdjusted()) {
                    if (i == 0) {
                        line = ((LandedCostCost) doc).getLandedCostMatchedList().get(0);
                    } else {
                        line = ((LandedCostCost) doc).getLandedCostMatchedList().get(1);
                    }
                } else {
                    line = ((LandedCostCost) doc).getLandedCostMatchedList().get(i / 2);
                }
            } else if (doc.getEntityName().equals(Invoice.ENTITY_NAME) && i > 0) {
                line = ((List<BaseOBObject>) OBDal.getInstance().get(doc.getClass(), doc.getId())
                        .get(lineListProperty)).get(i - 1);
            } else {
                line = ((List<BaseOBObject>) OBDal.getInstance().get(doc.getClass(), doc.getId())
                        .get(lineListProperty)).get(i / 2);
            }
            DocumentPostAssert documentPostAssert = documentPostAssertList.get(i);
            assertGeneralData(accountingFact);

            /* Accounting window fields assert */

            assertEquals(accountingFact.getTable(), table);
            assertEquals(accountingFact.getRecordID(), doc.getId());
            assertEquals(accountingFact.getAccountingSchema().getName(), "Main US/A/Euro");

            assertEquals(accountingFact.getAccount().getSearchKey(), documentPostAssert.getAccount());
            assertEquals(accountingFact.getQuantity(), documentPostAssert.getQuantity());

            BigDecimal rate;
            if ((productId != null && productId.equals(LANDEDCOSTTYPE3_ID))
                    || (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && ((Invoice) doc).getCurrency().getId().equals(CURRENCY2_ID))
                    || (doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && ((LCReceiptLineAmt) line).getLandedCostCost().getLandedCostType()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getLandedCostTypeList().get(0)))
                    || (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && ((LCMatched) line).getInvoiceLine().getProduct() != null
                            && ((LCMatched) line).getInvoiceLine().getProduct().getId()
                                    .equals(LANDEDCOSTTYPE3_ID))
                    || (!doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && !doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && documentPostAssert.getProductId() != null
                            && !OBDal.getInstance().get(Product.class, documentPostAssert.getProductId())
                                    .getPricingProductPriceList().isEmpty()
                            && OBDal.getInstance().get(Product.class, documentPostAssert.getProductId())
                                    .getPricingProductPriceList().get(0).getPriceListVersion()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getPricingProductPriceList().get(0).getPriceListVersion()))) {

                if (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                        && ((Invoice) doc).getCurrencyConversionRateDocList().size() != 0) {
                    rate = ((Invoice) doc).getCurrencyConversionRateDocList().get(0).getRate();
                } else {
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(9999, 0, 1);
                    OBCriteria<ConversionRate> criteria = OBDal.getInstance()
                            .createCriteria(ConversionRate.class);
                    criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CLIENT,
                            OBDal.getInstance().get(Client.class, CLIENT_ID)));
                    criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CURRENCY,
                            OBDal.getInstance().get(Currency.class, CURRENCY2_ID)));
                    criteria.add(Restrictions.eq(ConversionRate.PROPERTY_TOCURRENCY,
                            OBDal.getInstance().get(Currency.class, CURRENCY1_ID)));
                    criteria.add(Restrictions.ge(ConversionRate.PROPERTY_VALIDTODATE, calendar.getTime()));
                    rate = criteria.list().get(0).getMultipleRateBy();
                }
            }

            else {
                rate = BigDecimal.ONE;
            }

            assertEquals(accountingFact.getDebit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getDebit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));
            assertEquals(accountingFact.getCredit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getCredit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));

            if ((productId != null && productId.equals(LANDEDCOSTTYPE3_ID))
                    || (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && ((Invoice) doc).getCurrency().getId().equals(CURRENCY2_ID))
                    || (doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && ((LCReceiptLineAmt) line).getLandedCostCost().getLandedCostType()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getLandedCostTypeList().get(0)))
                    || (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && ((LCMatched) line).getInvoiceLine().getProduct() != null && ((LCMatched) line)
                                    .getInvoiceLine().getProduct().getId().equals(LANDEDCOSTTYPE3_ID))) {
                rate = BigDecimal.ONE;
            }

            else if ((doc.getEntityName().equals(ShipmentInOut.ENTITY_NAME)
                    || doc.getEntityName().equals(CostAdjustment.ENTITY_NAME))
                    && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency() != null
                    && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency().getId()
                            .equals(CURRENCY2_ID)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(9999, 0, 1);
                OBCriteria<ConversionRate> criteria = OBDal.getInstance().createCriteria(ConversionRate.class);
                criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CLIENT,
                        OBDal.getInstance().get(Client.class, CLIENT_ID)));
                criteria.add(Restrictions.eq(ConversionRate.PROPERTY_CURRENCY,
                        OBDal.getInstance().get(Currency.class, CURRENCY1_ID)));
                criteria.add(Restrictions.eq(ConversionRate.PROPERTY_TOCURRENCY,
                        OBDal.getInstance().get(Currency.class, CURRENCY2_ID)));
                criteria.add(Restrictions.ge(ConversionRate.PROPERTY_VALIDTODATE, calendar.getTime()));
                rate = criteria.list().get(0).getMultipleRateBy();
            }

            assertEquals(accountingFact.getForeignCurrencyDebit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getDebit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));
            assertEquals(accountingFact.getForeignCurrencyCredit().setScale(2, BigDecimal.ROUND_HALF_UP),
                    documentPostAssert.getCredit().multiply(rate).setScale(2,
                            doc.getEntityName().equals(LandedCost.ENTITY_NAME) ? BigDecimal.ROUND_HALF_EVEN
                                    : BigDecimal.ROUND_HALF_UP));

            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(accountingFact.getAccountingDate());
            calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMinimum(Calendar.DAY_OF_MONTH));
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(accountingFact.getAccountingDate());
            calendar2.set(Calendar.DAY_OF_MONTH, calendar2.getActualMaximum(Calendar.DAY_OF_MONTH));
            final OBCriteria<Period> criteria3 = OBDal.getInstance().createCriteria(Period.class);
            criteria3.add(Restrictions.eq(Period.PROPERTY_STARTINGDATE, calendar1.getTime()));
            criteria3.add(Restrictions.eq(Period.PROPERTY_ENDINGDATE, calendar2.getTime()));
            assertEquals(accountingFact.getPeriod(), criteria3.list().get(0));

            if (doc.getEntityName().equals(CostAdjustment.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()), formatDate(today));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((CostAdjustmentLine) line).getAccountingDate()));
                if (((CostAdjustmentLine) line).getInventoryTransaction().getGoodsShipmentLine() != null) {
                    assertEquals(accountingFact.getBusinessPartner(),
                            ((CostAdjustmentLine) line).getInventoryTransaction().getGoodsShipmentLine()
                                    .getShipmentReceipt().getBusinessPartner());
                } else {
                    assertEquals(accountingFact.getBusinessPartner(), null);
                }
            } else if (doc.getEntityName().equals(InventoryCount.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((InventoryCount) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((InventoryCount) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((ReceiptInvoiceMatch) doc).getTransactionDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((ReceiptInvoiceMatch) doc).getTransactionDate()));
                assertEquals(accountingFact.getBusinessPartner(),
                        ((ReceiptInvoiceMatch) doc).getInvoiceLine().getBusinessPartner());
            } else if (doc.getEntityName().equals(InternalMovement.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((InternalMovement) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((InternalMovement) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(InternalConsumption.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((InternalConsumption) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((InternalConsumption) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(ProductionTransaction.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((ProductionTransaction) doc).getMovementDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((ProductionTransaction) doc).getMovementDate()));
                assertEquals(accountingFact.getBusinessPartner(), null);
            } else if (doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((LandedCost) doc).getReferenceDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((LandedCost) doc).getReferenceDate()));
                if (i % 2 == 0) {
                    assertEquals(accountingFact.getBusinessPartner(),
                            OBDal.getInstance()
                                    .get(ShipmentInOutLine.class,
                                            ((LCReceiptLineAmt) line).getGoodsShipmentLine().getId())
                                    .getBusinessPartner());
                } else {
                    assertEquals(accountingFact.getBusinessPartner(), null);
                }
            } else if (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)) {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate(((LandedCostCost) doc).getAccountingDate()));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate(((LandedCostCost) doc).getAccountingDate()));
                if (i == 0 || (documentPostAssert.getProductId() != null
                        && OBDal.getInstance()
                                .get(InvoiceLine.class,
                                        ((LandedCostCost) doc).getLandedCostMatchedList().get(0)
                                                .getInvoiceLine().getId())
                                .getProduct() != null
                        && documentPostAssert.getProductId()
                                .equals(OBDal.getInstance()
                                        .get(InvoiceLine.class, ((LandedCostCost) doc)
                                                .getLandedCostMatchedList().get(0).getInvoiceLine().getId())
                                        .getProduct().getId()))) {
                    assertEquals(accountingFact.getBusinessPartner(),
                            OBDal.getInstance().get(InvoiceLine.class, ((LandedCostCost) doc)
                                    .getLandedCostMatchedList().get(0).getInvoiceLine().getId())
                                    .getBusinessPartner());
                } else {
                    assertEquals(accountingFact.getBusinessPartner(), null);
                }
            } else {
                assertEquals(formatDate(accountingFact.getTransactionDate()),
                        formatDate((Date) doc.get("accountingDate")));
                assertEquals(formatDate(accountingFact.getAccountingDate()),
                        formatDate((Date) doc.get("accountingDate")));
                assertEquals(accountingFact.getBusinessPartner(), doc.get("businessPartner"));
            }

            if ((productId != null && productId.equals(LANDEDCOSTTYPE3_ID))
                    || (doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && ((Invoice) doc).getCurrency().getId().equals(CURRENCY2_ID))
                    || (doc.getEntityName().equals(LandedCost.ENTITY_NAME)
                            && ((LCReceiptLineAmt) line).getLandedCostCost().getLandedCostType()
                                    .equals(OBDal.getInstance().get(Product.class, LANDEDCOSTTYPE3_ID)
                                            .getLandedCostTypeList().get(0)))
                    || (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)
                            && ((LCMatched) line).getInvoiceLine().getProduct() != null
                            && ((LCMatched) line).getInvoiceLine().getProduct().getId()
                                    .equals(LANDEDCOSTTYPE3_ID))
                    || (!doc.getEntityName().equals(Invoice.ENTITY_NAME)
                            && !doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)
                            && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID)
                                    .getCurrency() != null
                            && OBDal.getInstance().get(Organization.class, ORGANIZATION_ID).getCurrency()
                                    .getId().equals(CURRENCY2_ID))) {
                assertEquals(accountingFact.getCurrency(),
                        OBDal.getInstance().get(Currency.class, CURRENCY2_ID));
            } else {
                assertEquals(accountingFact.getCurrency(),
                        OBDal.getInstance().get(Currency.class, CURRENCY1_ID));
            }

            if (productId != null && productId.equals(LANDEDCOSTTYPE2_ID)) {
                if (i == 0) {
                    assertEquals(accountingFact.getProduct(), null);
                    assertEquals(accountingFact.getUOM(), null);
                    assertEquals(accountingFact.getTax(), null);
                } else if (i == 1) {
                    assertEquals(accountingFact.getProduct(), null);
                    assertEquals(accountingFact.getUOM(), null);
                    assertEquals(accountingFact.getLineID(), null);
                    assertEquals(accountingFact.getRecordID2(), null);

                    OBCriteria<TaxRate> criteria = OBDal.getInstance().createCriteria(TaxRate.class);
                    criteria.add(Restrictions.eq(TaxRate.PROPERTY_TAXCATEGORY,
                            OBDal.getInstance().get(Product.class, productId).getTaxCategory()));
                    criteria.add(Restrictions.eq(TaxRate.PROPERTY_ORGANIZATION,
                            OBDal.getInstance().get(Organization.class, ORGANIZATION_ID)));
                    assertEquals(accountingFact.getTax(), criteria.list().get(0));
                } else {
                    assertEquals(accountingFact.getProduct().getId(), productId);
                    assertEquals(accountingFact.getUOM(), line.get("uOM"));
                    assertEquals(accountingFact.getLineID(), line.getId());
                    assertEquals(accountingFact.getRecordID2(), null);
                    assertEquals(accountingFact.getTax(), null);
                }
            }

            else {
                if (doc.getEntityName().equals(Invoice.ENTITY_NAME) && i == 0) {
                    assertEquals(accountingFact.getProduct(), null);
                    assertEquals(accountingFact.getUOM(), null);
                    assertEquals(accountingFact.getTax(), null);
                } else {
                    if (productId == null) {
                        assertEquals(accountingFact.getProduct(), documentPostAssert.getProductId() == null
                                ? null
                                : OBDal.getInstance().get(Product.class, documentPostAssert.getProductId()));
                    } else {
                        assertEquals(accountingFact.getProduct().getId(), productId);
                    }
                    if (line.getEntity().getProperty("uOM", false) == null) {
                        assertEquals(accountingFact.getUOM(), null);
                    } else {
                        assertEquals(accountingFact.getUOM(), line.get("uOM"));
                    }
                    if (!doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                        assertEquals(accountingFact.getLineID(), line.getId());
                    }
                    assertEquals(accountingFact.getRecordID2(), null);
                    assertEquals(accountingFact.getTax(), null);
                }
            }

            assertEquals(accountingFact.getProject(), null);
            assertEquals(accountingFact.getCostcenter(), null);
            assertEquals(accountingFact.getAsset(), null);
            assertEquals(accountingFact.getStDimension(), null);
            assertEquals(accountingFact.getNdDimension(), null);

            /* Rest of fields assert */

            if (doc.getEntityName().equals(ShipmentInOut.ENTITY_NAME)) {
                assertEquals(accountingFact.getGLCategory().getName(), "Material Management");
            } else if (doc.getEntityName().equals(Invoice.ENTITY_NAME)) {
                assertEquals(accountingFact.getGLCategory().getName(), "AP Invoice");
            } else if (doc.getEntityName().equals(CostAdjustment.ENTITY_NAME)) {
                assertEquals(accountingFact.getGLCategory().getName(), "None");
            } else {
                assertEquals(accountingFact.getGLCategory().getName(), "Standard");
            }

            assertEquals(accountingFact.getPostingType(), "A");

            if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                assertEquals(accountingFact.getStorageBin(), null);
            } else if (doc.getEntityName().equals(InternalMovement.ENTITY_NAME)) {
                if (i % 2 == 0) {
                    assertEquals(accountingFact.getStorageBin(),
                            line.get(InternalMovementLine.PROPERTY_STORAGEBIN));
                } else {
                    assertEquals(accountingFact.getStorageBin(),
                            line.get(InternalMovementLine.PROPERTY_NEWSTORAGEBIN));
                }
            } else if (line.getEntity().getProperty("storageBin", false) == null) {
                assertEquals(accountingFact.getStorageBin(), null);
            } else {
                assertEquals(accountingFact.getStorageBin(), line.get("storageBin"));
            }

            if (doc.getEntityName().equals(InventoryCount.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MMI");
            } else if (doc.getEntityName().equals(ReceiptInvoiceMatch.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MXI");
            } else if (doc.getEntityName().equals(InternalMovement.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MMM");
            } else if (doc.getEntityName().equals(InternalConsumption.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MIC");
            } else if (doc.getEntityName().equals(ProductionTransaction.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "MMP");
            } else if (doc.getEntityName().equals(LandedCost.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "LDC");
            } else if (doc.getEntityName().equals(LandedCostCost.ENTITY_NAME)) {
                assertEquals(accountingFact.getDocumentType(), null);
                assertEquals(accountingFact.getDocumentCategory(), "LCC");
            } else {
                assertEquals(accountingFact.getDocumentType(), doc.get("documentType"));
                assertEquals(accountingFact.getDocumentCategory(),
                        ((DocumentType) doc.get("documentType")).getDocumentCategory());
            }

            assertEquals(accountingFact.getSalesRegion(), null);
            assertEquals(accountingFact.getSalesCampaign(), null);
            assertEquals(accountingFact.getActivity(), null);
            assertEquals(accountingFact.getGroupID(), groupId);
            assertEquals(accountingFact.getType(), "N");
            assertEquals(accountingFact.getValue(), documentPostAssert.getAccount());
            assertEquals(accountingFact.getWithholding(), null);
            assertFalse(accountingFact.isModify());
            assertEquals(accountingFact.getDateBalanced(), null);

            final OBCriteria<ElementValue> criteria4 = OBDal.getInstance().createCriteria(ElementValue.class);
            criteria4.add(Restrictions.eq(ElementValue.PROPERTY_SEARCHKEY, documentPostAssert.getAccount()));
            assertEquals(accountingFact.getAccountingEntryDescription(),
                    criteria4.list().get(0).getDescription());

            i++;
        }
    } catch (Exception e) {
        throw new OBException(e);
    }
}

From source file:com.clark.func.Functions.java

/**
 * <p>/*from   w  w  w. j  av a  2s . c o m*/
 * Internal calculation method.
 * </p>
 * 
 * @param val
 *            the calendar
 * @param field
 *            the field constant
 * @param modType
 *            type to truncate, round or ceiling
 * @throws ArithmeticException
 *             if the year is over 280 million
 */
private static void modifyDate(Calendar val, int field, int modType) {
    if (val.get(Calendar.YEAR) > 280000000) {
        throw new ArithmeticException("Calendar value too large for accurate calculations");
    }

    if (field == Calendar.MILLISECOND) {
        return;
    }

    // ----------------- Fix for LANG-59 ---------------------- START
    // ---------------
    // see http://issues.apache.org/jira/browse/LANG-59
    //
    // Manually truncate milliseconds, seconds and minutes, rather than
    // using
    // Calendar methods.

    Date date = val.getTime();
    long time = date.getTime();
    boolean done = false;

    // truncate milliseconds
    int millisecs = val.get(Calendar.MILLISECOND);
    if (MODIFY_TRUNCATE == modType || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

    // truncate seconds
    int seconds = val.get(Calendar.SECOND);
    if (!done && (MODIFY_TRUNCATE == modType || seconds < 30)) {
        time = time - (seconds * 1000L);
    }
    if (field == Calendar.MINUTE) {
        done = true;
    }

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (MODIFY_TRUNCATE == modType || minutes < 30)) {
        time = time - (minutes * 60000L);
    }

    // reset time
    if (date.getTime() != time) {
        date.setTime(time);
        val.setTime(date);
    }
    // ----------------- Fix for LANG-59 ----------------------- END
    // ----------------

    boolean roundUp = false;
    for (int i = 0; i < fields.length; i++) {
        for (int j = 0; j < fields[i].length; j++) {
            if (fields[i][j] == field) {
                // This is our field... we stop looping
                if (modType == MODIFY_CEILING || (modType == MODIFY_ROUND && roundUp)) {
                    if (field == SEMI_MONTH) {
                        // This is a special case that's hard to generalize
                        // If the date is 1, we round up to 16, otherwise
                        // we subtract 15 days and add 1 month
                        if (val.get(Calendar.DATE) == 1) {
                            val.add(Calendar.DATE, 15);
                        } else {
                            val.add(Calendar.DATE, -15);
                            val.add(Calendar.MONTH, 1);
                        }
                        // ----------------- Fix for LANG-440
                        // ---------------------- START ---------------
                    } else if (field == Calendar.AM_PM) {
                        // This is a special case
                        // If the time is 0, we round up to 12, otherwise
                        // we subtract 12 hours and add 1 day
                        if (val.get(Calendar.HOUR_OF_DAY) == 0) {
                            val.add(Calendar.HOUR_OF_DAY, 12);
                        } else {
                            val.add(Calendar.HOUR_OF_DAY, -12);
                            val.add(Calendar.DATE, 1);
                        }
                        // ----------------- Fix for LANG-440
                        // ---------------------- END ---------------
                    } else {
                        // We need at add one to this field since the
                        // last number causes us to round up
                        val.add(fields[i][0], 1);
                    }
                }
                return;
            }
        }
        // We have various fields that are not easy roundings
        int offset = 0;
        boolean offsetSet = false;
        // These are special types of fields that require different rounding
        // rules
        switch (field) {
        case SEMI_MONTH:
            if (fields[i][0] == Calendar.DATE) {
                // If we're going to drop the DATE field's value,
                // we want to do this our own way.
                // We need to subtrace 1 since the date has a minimum of
                // 1
                offset = val.get(Calendar.DATE) - 1;
                // If we're above 15 days adjustment, that means we're
                // in
                // the
                // bottom half of the month and should stay accordingly.
                if (offset >= 15) {
                    offset -= 15;
                }
                // Record whether we're in the top or bottom half of
                // that
                // range
                roundUp = offset > 7;
                offsetSet = true;
            }
            break;
        case Calendar.AM_PM:
            if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                // If we're going to drop the HOUR field's value,
                // we want to do this our own way.
                offset = val.get(Calendar.HOUR_OF_DAY);
                if (offset >= 12) {
                    offset -= 12;
                }
                roundUp = offset >= 6;
                offsetSet = true;
            }
            break;
        }
        if (!offsetSet) {
            int min = val.getActualMinimum(fields[i][0]);
            int max = val.getActualMaximum(fields[i][0]);
            // Calculate the offset from the minimum allowed value
            offset = val.get(fields[i][0]) - min;
            // Set roundUp if this is more than half way between the minimum
            // and maximum
            roundUp = offset > ((max - min) / 2);
        }
        // We need to remove this field
        if (offset != 0) {
            val.set(fields[i][0], val.get(fields[i][0]) - offset);
        }
    }
    throw new IllegalArgumentException("The field " + field + " is not supported");

}