Example usage for org.apache.commons.lang.time DateUtils truncate

List of usage examples for org.apache.commons.lang.time DateUtils truncate

Introduction

In this page you can find the example usage for org.apache.commons.lang.time DateUtils truncate.

Prototype

public static Date truncate(Object date, int field) 

Source Link

Document

Truncate this date, leaving the field specified as the most significant field.

For example, if you had the datetime of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000.

Usage

From source file:org.kuali.ole.coa.document.validation.impl.AccountRuleTest.java

@Test
public void testGuidelinesConditionallyRequired_TodaysDate() {

    boolean result;
    Account account = new Account();
    MaintenanceDocument maintDoc = newMaintDoc(account);
    AccountRule rule = (AccountRule) setupMaintDocRule(maintDoc, AccountRule.class);

    // setup a var with today's date
    Date today = new Date(SpringContext.getBean(DateTimeService.class).getCurrentDate().getTime());
    today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime());
    account.setAccountExpirationDate(today);
    result = rule.areGuidelinesRequired(account);
    assertEquals("Guidelines should be required for Account expiring today.", true, result);

}

From source file:org.kuali.ole.coa.document.validation.impl.AccountRuleTest.java

@Test
public void testCheckAccountExpirationDateTodayOrEarlier_TodaysDate() {

    MaintenanceDocument maintDoc = newMaintDoc(newAccount);
    AccountRule rule = (AccountRule) setupMaintDocRule(maintDoc, AccountRule.class);
    boolean result;
    Calendar testCalendar;/*w  w w  .  j  av  a2  s .  c  om*/
    Date testTimestamp;

    // get today's date (or whatever's provided by the DateTimeService)
    testCalendar = Calendar.getInstance();
    testCalendar.setTime(SpringContext.getBean(DateTimeService.class).getCurrentDate());
    testCalendar = DateUtils.truncate(testCalendar, Calendar.DAY_OF_MONTH);
    testTimestamp = new Date(testCalendar.getTimeInMillis());

    // current date - pass
    newAccount.setAccountExpirationDate(testTimestamp);
    result = rule.checkAccountExpirationDateValidTodayOrEarlier(newAccount);
    assertEquals("Today's date should pass.", true, result);
    assertGlobalMessageMapEmpty();

}

From source file:org.kuali.ole.coa.document.validation.impl.DelegateGlobalRule.java

private boolean checkStartDate(AccountDelegateGlobalDetail delegateGlobalDetail, int lineNum) {
    boolean success = true;
    if (ObjectUtils.isNotNull(delegateGlobalDetail.getAccountDelegateStartDate())) {
        Timestamp today = getDateTimeService().getCurrentTimestamp();
        today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime());
        if (delegateGlobalDetail.getAccountDelegateStartDate().before(today)) {
            success = false;//from  w w w.  j  a  va  2 s.c o  m
            String errorPath = DELEGATE_GLOBALS_PREFIX + "[" + lineNum + "]." + "accountDelegateStartDate";
            putFieldError(errorPath, OLEKeyConstants.ERROR_DOCUMENT_ACCTDELEGATEMAINT_STARTDATE_IN_PAST,
                    new String[0]);
        }
    }
    return success;
}

From source file:org.kuali.ole.coa.document.validation.impl.DelegateRule.java

/**
 * This checks to see if/*  w  w w. j  a  v a  2  s .c om*/
 * <ul>
 * <li>the delegate start date is valid and they are active</li>
 * <li>from amount is >= 0</li>
 * <li>to amount cannot be empty when from amount is filled out</li>
 * <li>to amount is >= from amount</li>
 * <li>account cannot be closed</li>
 * </ul>
 * 
 * @return
 */
protected boolean checkSimpleRules() {
    boolean success = true;

    Map<String, String> fieldValues = new HashMap<String, String>();
    fieldValues.put(OLEPropertyConstants.CHART_OF_ACCOUNTS_CODE, newDelegate.getChartOfAccountsCode());
    fieldValues.put(OLEPropertyConstants.ACCOUNT_NUMBER, newDelegate.getAccountNumber());

    int accountExist = getBoService().countMatching(Account.class, fieldValues);
    if (accountExist <= 0) {
        putFieldError(OLEPropertyConstants.ACCOUNT_NUMBER, OLEKeyConstants.ERROR_EXISTENCE,
                newDelegate.getAccountNumber());
        success &= false;
    }

    // start date must be greater than or equal to today if active
    boolean newActive = newDelegate.isActive();
    if ((ObjectUtils.isNotNull(newDelegate.getAccountDelegateStartDate())) && newActive) {
        Timestamp today = getDateTimeService().getCurrentTimestamp();
        today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime());
        if (newDelegate.getAccountDelegateStartDate().before(today)) {
            putFieldError(OLEPropertyConstants.ACCOUNT_DELEGATE_START_DATE,
                    OLEKeyConstants.ERROR_DOCUMENT_ACCTDELEGATEMAINT_STARTDATE_IN_PAST);
            success &= false;
        }
    }

    // FROM amount must be >= 0 (may not be negative)
    KualiDecimal fromAmount = newDelegate.getFinDocApprovalFromThisAmt();
    if (ObjectUtils.isNotNull(fromAmount)) {
        if (fromAmount.isLessThan(KualiDecimal.ZERO)) {
            putFieldError(OLEPropertyConstants.FIN_DOC_APPROVAL_FROM_THIS_AMT,
                    OLEKeyConstants.ERROR_DOCUMENT_ACCTDELEGATEMAINT_FROM_AMOUNT_NONNEGATIVE);
            success &= false;
        }
    }

    // TO amount must be >= FROM amount or Zero
    KualiDecimal toAmount = newDelegate.getFinDocApprovalToThisAmount();
    if (ObjectUtils.isNotNull(toAmount) && !toAmount.equals(KualiDecimal.ZERO)) {
        // case if FROM amount is non-null and positive, disallow TO amount being less
        if (fromAmount != null && toAmount.isLessThan(fromAmount)) {
            putFieldError(OLEPropertyConstants.FIN_DOC_APPROVAL_TO_THIS_AMOUNT,
                    OLEKeyConstants.ERROR_DOCUMENT_ACCTDELEGATEMAINT_TO_AMOUNT_MORE_THAN_FROM_OR_ZERO);
            success &= false;
        } else if (toAmount.isLessThan(KualiDecimal.ZERO)) {
            putFieldError(OLEPropertyConstants.FIN_DOC_APPROVAL_TO_THIS_AMOUNT,
                    OLEKeyConstants.ERROR_DOCUMENT_ACCTDELEGATEMAINT_TO_AMOUNT_MORE_THAN_FROM_OR_ZERO);
            success &= false;
        }
    }

    // do we have a good document type?
    final FinancialSystemDocumentTypeService documentService = SpringContext
            .getBean(FinancialSystemDocumentTypeService.class);
    if (!documentService.isFinancialSystemDocumentType(newDelegate.getFinancialDocumentTypeCode())) {
        putFieldError(OLEPropertyConstants.FINANCIAL_DOCUMENT_TYPE_CODE,
                OLEKeyConstants.ERROR_DOCUMENT_ACCTDELEGATEMAINT_INVALID_DOC_TYPE,
                new String[] { newDelegate.getFinancialDocumentTypeCode(), OLEConstants.ROOT_DOCUMENT_TYPE });
        success = false;
    }

    return success;
}

From source file:org.kuali.ole.coa.document.validation.impl.OrgRule.java

/**
 * This checks the following conditions:
 * <ul>//  w  ww  . j av  a2s .c o  m
 * <li>begin date must be greater than or equal to end date</li>
 * <li>start date must be greater than or equal to today if new Document</li>
 * <li>Reports To Chart/Org should not be same as this Chart/Org</li>
 * </ul>
 *
 * @param document
 * @return true if it passes all the rules, false otherwise
 */
protected boolean checkSimpleRules(MaintenanceDocument document) {

    boolean success = true;
    String lastReportsToChartOfAccountsCode;
    String lastReportsToOrganizationCode;
    boolean continueSearch;
    Organization tempOrg;
    Integer loopCount;
    Integer maxLoopCount = 40;

    // begin date must be greater than or equal to end date
    if ((ObjectUtils.isNotNull(newOrg.getOrganizationBeginDate())
            && (ObjectUtils.isNotNull(newOrg.getOrganizationEndDate())))) {

        Date beginDate = newOrg.getOrganizationBeginDate();
        Date endDate = newOrg.getOrganizationEndDate();

        if (endDate.before(beginDate)) {
            putFieldError("organizationEndDate",
                    OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_END_DATE_GREATER_THAN_BEGIN_DATE);
            success &= false;
        }
    }

    // start date must be greater than or equal to today if new Document
    if ((ObjectUtils.isNotNull(newOrg.getOrganizationBeginDate()) && (document.isNew()))) {
        Timestamp today = getDateTimeService().getCurrentTimestamp();
        today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime());
        if (newOrg.getOrganizationBeginDate().before(today)) {
            putFieldError("organizationBeginDate", OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_STARTDATE_IN_PAST);
            success &= false;
        }
    }

    // Reports To Chart/Org should not be same as this Chart/Org
    // However, allow special case where organization type is listed in the business rules
    if (ObjectUtils.isNotNull(newOrg.getReportsToChartOfAccountsCode())
            && ObjectUtils.isNotNull(newOrg.getReportsToOrganizationCode())
            && ObjectUtils.isNotNull(newOrg.getChartOfAccountsCode())
            && ObjectUtils.isNotNull(newOrg.getOrganizationCode())) {
        if (!getOrgMustReportToSelf(newOrg)) {

            if ((newOrg.getReportsToChartOfAccountsCode().equals(newOrg.getChartOfAccountsCode()))
                    && (newOrg.getReportsToOrganizationCode().equals(newOrg.getOrganizationCode()))) {
                putFieldError("reportsToOrganizationCode",
                        OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_CANNOT_BE_SAME_ORG);
                success = false;
            } else {
                // Don't allow a circular reference on Reports to Chart/Org
                // terminate the search when a top-level org is found
                lastReportsToChartOfAccountsCode = newOrg.getReportsToChartOfAccountsCode();
                lastReportsToOrganizationCode = newOrg.getReportsToOrganizationCode();
                continueSearch = true;
                loopCount = 0;
                do {
                    tempOrg = orgService.getByPrimaryId(lastReportsToChartOfAccountsCode,
                            lastReportsToOrganizationCode);
                    loopCount++;
                    ;
                    if (ObjectUtils.isNull(tempOrg)) {
                        continueSearch = false;
                        // if a null is returned on the first iteration, then the reports-to org does not exist
                        // fail the validation
                        if (loopCount == 1) {
                            putFieldError("reportsToOrganizationCode",
                                    OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_EXIST);
                            success = false;
                        }
                    } else {
                        // on the first iteration, check whether the reports-to organization is active
                        if (loopCount == 1 && !tempOrg.isActive()) {
                            putFieldError("reportsToOrganizationCode",
                                    OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_EXIST);
                            success = false;
                            continueSearch = false;
                        } else {
                            // LOG.info("Found Org = " + lastReportsToChartOfAccountsCode + "/" +
                            // lastReportsToOrganizationCode);
                            lastReportsToChartOfAccountsCode = tempOrg.getReportsToChartOfAccountsCode();
                            lastReportsToOrganizationCode = tempOrg.getReportsToOrganizationCode();

                            if ((tempOrg.getReportsToChartOfAccountsCode()
                                    .equals(newOrg.getChartOfAccountsCode()))
                                    && (tempOrg.getReportsToOrganizationCode()
                                            .equals(newOrg.getOrganizationCode()))) {
                                putFieldError("reportsToOrganizationCode",
                                        OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_CANNOT_BE_CIRCULAR_REF_TO_SAME_ORG);
                                success = false;
                                continueSearch = false;
                            }
                        }
                    }
                    if (loopCount > maxLoopCount) {
                        continueSearch = false;
                    }
                    // stop the search if we reach an org that must report to itself
                    if (continueSearch && /*REFACTORME*/SpringContext.getBean(ParameterEvaluatorService.class)
                            .getParameterEvaluator(Organization.class,
                                    OLEConstants.ChartApcParms.ORG_MUST_REPORT_TO_SELF_ORG_TYPES,
                                    tempOrg.getOrganizationTypeCode())
                            .evaluationSucceeds()) {
                        continueSearch = false;
                    }

                } while (continueSearch == true);
            } // end else (checking for circular ref)
        } else { // org must report to self (university level organization)
            if (!(newOrg.getReportsToChartOfAccountsCode().equals(newOrg.getChartOfAccountsCode())
                    && newOrg.getReportsToOrganizationCode().equals(newOrg.getOrganizationCode()))) {
                putFieldError("reportsToOrganizationCode",
                        OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_REPORTING_ORG_MUST_BE_SAME_ORG);
                success = false;
            }
            // org must be the only one of that type
            String topLevelOrgTypeCode = SpringContext.getBean(ParameterService.class)
                    .getParameterValueAsString(Organization.class,
                            OLEConstants.ChartApcParms.ORG_MUST_REPORT_TO_SELF_ORG_TYPES);
            List<Organization> topLevelOrgs = orgService.getActiveOrgsByType(topLevelOrgTypeCode);
            if (!topLevelOrgs.isEmpty()) {
                // is the new org in the topLevelOrgs list? If not, then there's an error; if so, we're editing the top level
                // org
                if (!topLevelOrgs.contains(newOrg)) {
                    putFieldError("organizationTypeCode",
                            OLEKeyConstants.ERROR_DOCUMENT_ORGMAINT_ONLY_ONE_TOP_LEVEL_ORG,
                            topLevelOrgs.get(0).getChartOfAccountsCode() + "-"
                                    + topLevelOrgs.get(0).getOrganizationCode());
                    success = false;
                }
            }
        }
    }

    return success;
}

From source file:org.kuali.ole.sys.businessobject.defaultvalue.CurrentDateMMDDYYYYFinder.java

public String getValue() {
    // get the current date from the service
    Date date = SpringContext.getBean(DateTimeService.class).getCurrentDate();

    // remove the time component
    date = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);

    // format it as expected
    return DateFormatUtils.format(date, RiceConstants.SIMPLE_DATE_FORMAT_FOR_DATE);
}

From source file:org.ngrinder.infra.report.PeriodicCollectDataToGAService.java

/**
 * Send the number of executed test./*w w  w . jav  a 2 s.  co m*/
 */
@Scheduled(cron = "0 1 1 * * ?")
@Transactional
public void reportUsage() {
    if (config.isUsageReportEnabled()) {
        doRandomDelay();
        GoogleAnalytic googleAnalytic = new GoogleAnalytic(ControllerConstants.GOOGLE_ANALYTICS_APP_NAME,
                config.getVersion(), ControllerConstants.GOOGLE_ANALYTICS_TRACKING_ID);
        MeasureProtocolRequest measureProtocolRequest = googleAnalytic.getMeasureProtocolRequest();
        measureProtocolRequest.setEventCategory("usage");
        measureProtocolRequest.setEventAction("executions");
        String currentAddress = NetworkUtils.getLocalHostAddress();
        Date yesterday = DateUtils.addDays(new Date(), -1);
        Date start = DateUtils.truncate(yesterday, Calendar.DATE);
        Date end = DateUtils.addMilliseconds(DateUtils.ceiling(yesterday, Calendar.DATE), -1);
        googleAnalytic.sendStaticDataToUA(currentAddress, String.valueOf(getUsage(start, end)));
    }
}

From source file:org.objectstyle.cayenne.dataview.DataTypeSpec.java

public Object create(DataTypeEnum dataType) {
    Class clazz = getJavaClass(dataType);
    if (clazz != null) {
        try {/*from  w w w .ja va2  s . com*/
            Object value = clazz.newInstance();
            if (DataTypeEnum.DATE_TYPE.equals(dataType))
                value = DateUtils.truncate(value, Calendar.DATE);
            return value;
        } catch (InstantiationException ex) {
            return null;
        } catch (IllegalAccessException ex) {
            return null;
        }
    }
    return null;
}

From source file:org.objectstyle.cayenne.dataview.DataTypeSpec.java

public Object toDataType(DataTypeEnum dataType, Object untypedValue) {
    Class dataTypeClass = getJavaClass(dataType);
    if (dataTypeClass == null || untypedValue == null
            || ClassUtils.isAssignable(untypedValue.getClass(), dataTypeClass)) {
        if (DataTypeEnum.DATE_TYPE.equals(dataType) && Date.class.equals(dataTypeClass)) {
            return DateUtils.truncate(untypedValue, Calendar.DATE);
        }/*from w w w  .  j  a  v a  2 s .  c  o  m*/
        return untypedValue;
    }

    Object v = null;
    String strUntypedValue = null;
    boolean isStringUntypedValue;
    Number numUntypedValue = null;
    boolean isNumberUntypedValue;
    if (isStringUntypedValue = untypedValue instanceof String)
        strUntypedValue = (String) untypedValue;
    if (isNumberUntypedValue = untypedValue instanceof Number)
        numUntypedValue = (Number) untypedValue;

    switch (dataType.getValue()) {
    case DataTypeEnum.BOOLEAN_TYPE_VALUE:
        if (isNumberUntypedValue)
            v = BooleanUtils.toBooleanObject(numUntypedValue.intValue());
        else if (isStringUntypedValue)
            v = BooleanUtils.toBooleanObject(strUntypedValue);
        break;
    case DataTypeEnum.INTEGER_TYPE_VALUE:
        if (isNumberUntypedValue)
            v = new Integer(numUntypedValue.intValue());
        else if (isStringUntypedValue)
            v = NumberUtils.createInteger(strUntypedValue);
        break;
    case DataTypeEnum.DOUBLE_TYPE_VALUE:
        if (isNumberUntypedValue)
            v = new Double(numUntypedValue.doubleValue());
        else if (isStringUntypedValue)
            v = NumberUtils.createDouble(strUntypedValue);
        break;
    case DataTypeEnum.STRING_TYPE_VALUE:
        v = ObjectUtils.toString(untypedValue);
        break;
    case DataTypeEnum.DATE_TYPE_VALUE:
        if (isNumberUntypedValue)
            v = DateUtils.truncate(new Date(numUntypedValue.longValue()), Calendar.DATE);
        break;
    case DataTypeEnum.DATETIME_TYPE_VALUE:
        if (isNumberUntypedValue)
            v = new Date(numUntypedValue.longValue());
        break;
    case DataTypeEnum.MONEY_TYPE_VALUE:
        if (isNumberUntypedValue)
            v = new Double(numUntypedValue.doubleValue());
        else if (isStringUntypedValue)
            v = NumberUtils.createDouble(strUntypedValue);
        break;
    case DataTypeEnum.PERCENT_TYPE_VALUE:
        if (isNumberUntypedValue)
            v = new Double(numUntypedValue.doubleValue());
        else if (isStringUntypedValue)
            v = NumberUtils.createDouble(strUntypedValue);
        break;
    }
    return v;
}

From source file:org.olat.course.condition.interpreter.TodayVariable.java

/**
 * @see com.neemsoft.jmep.VariableCB#getValue()
 *///w ww.j av a2s  .  c  om
public Object getValue() {
    CourseEditorEnv cev = getUserCourseEnv().getCourseEditorEnv();
    if (cev != null) {
        return new Double(0);
    }
    CourseEnvironment ce = getUserCourseEnv().getCourseEnvironment();
    long time = ce.getCurrentTimeMillis();
    Date date = new Date(time);
    Date day = DateUtils.truncate(date, Calendar.DATE);
    Double dDay = new Double(day.getTime());
    return dDay;
}