Java Code Examples for org.apache.commons.lang.time.DateUtils#truncate()

The following examples show how to use org.apache.commons.lang.time.DateUtils#truncate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateTimeUtils.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Converts the time (hour.minute) to a calendar object.
 */
public static Calendar timeToCalendar(Calendar calendar, double time) {
    if (time < 0.0) {
        return null;
    }
    Calendar cal = (Calendar) calendar.clone();
    int hour = 0;
    int minute = 0;
    if (time == 24.0) {
        cal.add(Calendar.DAY_OF_MONTH, 1);
    } else {
        hour = (int) time;
        minute = (int) ((time * 100) - (hour * 100));
    }
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, minute);
    return DateUtils.truncate(cal, Calendar.MINUTE);
}
 
Example 2
Source File: Account.java    From kfs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * This method determines whether the account is expired or not. Note that if Expiration Date is the same date as testDate, then
 * this will return false. It will only return true if the account expiration date is one day earlier than testDate or earlier.
 * Note that this logic ignores all time components when doing the comparison. It only does the before/after comparison based on
 * date values, not time-values.
 *
 * @param testDate - Calendar instance with the date to test the Account's Expiration Date against. This is most commonly set to
 *        today's date.
 * @return true or false based on the logic outlined above
 */
@Override
public boolean isExpired(Calendar testDate) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("entering isExpired(" + testDate + ")");
    }

    // dont even bother trying to test if the accountExpirationDate is null
    if (accountExpirationDate == null) {
        return false;
    }

    // remove any time-components from the testDate
    testDate = DateUtils.truncate(testDate, Calendar.DAY_OF_MONTH);

    // get a calendar reference to the Account Expiration
    // date, and remove any time components
    Calendar acctDate = Calendar.getInstance();
    acctDate.setTime(this.accountExpirationDate);
    acctDate = DateUtils.truncate(acctDate, Calendar.DAY_OF_MONTH);

    // if the Account Expiration Date is before the testDate
    return acctDate.before(testDate);
}
 
Example 3
Source File: DashboardController.java    From cloud-portal with MIT License 6 votes vote down vote up
private void addProvisioningHistoryToMap(ProvisionLog provisionLog, Map<Long, Integer> provisioningHistoryMap) {

		Date date = provisionLog.getDate();
		
		if (date.after(this.dateBefore)) {
			
			Date calculatedDate = DateUtils.truncate(date, Calendar.DAY_OF_MONTH); // NOSONAR
			long timeInMillis = calculatedDate.getTime();
			
			Integer counter = provisioningHistoryMap.get(timeInMillis);
			if (counter == null) {
				counter = 0;
			}
			counter = counter + 1;
			
			provisioningHistoryMap.put(timeInMillis, counter);
		}
	}
 
Example 4
Source File: DateTimeUtils.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Converts the time (hour.minute) to a calendar object.
 */
public static Calendar timeToCalendar(Calendar calendar, double time) {
    if (time < 0.0) {
        return null;
    }
    Calendar cal = (Calendar) calendar.clone();
    int hour = 0;
    int minute = 0;
    if (time == 24.0) {
        cal.add(Calendar.DAY_OF_MONTH, 1);
    } else {
        hour = (int) time;
        minute = (int) ((time * 100) - (hour * 100));
    }
    cal.set(Calendar.HOUR_OF_DAY, hour);
    cal.set(Calendar.MINUTE, minute);
    return DateUtils.truncate(cal, Calendar.MINUTE);
}
 
Example 5
Source File: DiscoveryLogic.java    From datawave with Apache License 2.0 5 votes vote down vote up
public static BatchScanner configureBatchScannerForDiscovery(DiscoveryQueryConfiguration config, ScannerFactory scannerFactory, String tableName,
                Collection<Range> seekRanges, Set<Text> columnFamilies, Multimap<String,String> literals, Multimap<String,String> patterns,
                Multimap<String,LiteralRange<String>> ranges, boolean reverseIndex) throws TableNotFoundException {
    
    // if we have no ranges, then nothing to scan
    if (seekRanges.isEmpty()) {
        return null;
    }
    
    BatchScanner bs = scannerFactory.newScanner(tableName, config.getAuthorizations(), config.getNumQueryThreads(), config.getQuery());
    bs.setRanges(seekRanges);
    if (!columnFamilies.isEmpty()) {
        for (Text family : columnFamilies) {
            bs.fetchColumnFamily(family);
        }
    }
    
    // The begin date from the query may be down to the second, for doing lookups in the index we want to use the day because
    // the times in the index table have been truncated to the day.
    Date begin = DateUtils.truncate(config.getBeginDate(), Calendar.DAY_OF_MONTH);
    // we don't need to bump up the end date any more because it's not apart of the range set on the scanner
    Date end = config.getEndDate();
    
    LongRange dateRange = new LongRange(begin.getTime(), end.getTime());
    
    ShardIndexQueryTableStaticMethods.configureGlobalIndexDateRangeFilter(config, bs, dateRange);
    ShardIndexQueryTableStaticMethods.configureGlobalIndexDataTypeFilter(config, bs, config.getDatatypeFilter());
    
    configureIndexMatchingIterator(config, bs, literals, patterns, ranges, reverseIndex);
    
    IteratorSetting discoveryIteratorSetting = new IteratorSetting(config.getBaseIteratorPriority() + 50, DiscoveryIterator.class);
    discoveryIteratorSetting.addOption(REVERSE_INDEX, Boolean.toString(reverseIndex));
    discoveryIteratorSetting.addOption(SEPARATE_COUNTS_BY_COLVIS, config.getSeparateCountsByColVis().toString());
    if (config.getShowReferenceCount()) {
        discoveryIteratorSetting.addOption(SHOW_REFERENCE_COUNT, config.getShowReferenceCount().toString());
    }
    bs.addScanIterator(discoveryIteratorSetting);
    
    return bs;
}
 
Example 6
Source File: CurrentDateMMDDYYYYFinder.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
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, "MM/dd/yyyy");
}
 
Example 7
Source File: PriorYearAccount.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method determines whether the account is expired or not. Note that if Expiration Date is the same date as testDate, then
 * this will return false. It will only return true if the account expiration date is one day earlier than testDate or earlier.
 * Note that this logic ignores all time components when doing the comparison. It only does the before/after comparison based on
 * date values, not time-values.
 *
 * @param testDate - Calendar instance with the date to test the Account's Expiration Date against. This is most commonly set to
 *        today's date.
 * @return true or false based on the logic outlined above
 */
@Override
public boolean isExpired(Calendar testDate) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("entering isExpired(" + testDate + ")");
    }

    // dont even bother trying to test if the accountExpirationDate is null
    if (this.accountExpirationDate == null) {
        return false;
    }

    // remove any time-components from the testDate
    testDate = DateUtils.truncate(testDate, Calendar.DAY_OF_MONTH);

    // get a calendar reference to the Account Expiration
    // date, and remove any time components
    Calendar acctDate = Calendar.getInstance();
    acctDate.setTime(this.accountExpirationDate);
    acctDate = DateUtils.truncate(acctDate, Calendar.DAY_OF_MONTH);

    // if the Account Expiration Date is before the testDate
    if (acctDate.before(testDate)) {
        return true;
    }
    else {
        return false;
    }
}
 
Example 8
Source File: DateTimeUtils.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private static Calendar adjustTime(Calendar cal, int minutes) {
    if (minutes > 0) {
        Calendar cTime = Calendar.getInstance();
        cTime = DateUtils.truncate(cal, Calendar.DAY_OF_MONTH);
        cTime.add(Calendar.MINUTE, minutes);
        return cTime;
    }
    return cal;
}
 
Example 9
Source File: ProspectorReducer.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(Context context) throws IOException, InterruptedException {
    super.setup(context);

    final Configuration conf = context.getConfiguration();
    final long now = conf.getLong("DATE", System.currentTimeMillis());
    truncatedDate = DateUtils.truncate(new Date(now), Calendar.MINUTE);

    this.plans = ProspectorUtils.planMap(manager.getPlans());
}
 
Example 10
Source File: ShardIndexQueryTable.java    From datawave with Apache License 2.0 5 votes vote down vote up
public static BatchScanner configureBatchScannerForDiscovery(ShardQueryConfiguration config, ScannerFactory scannerFactory, String tableName,
                Collection<Range> ranges, Collection<String> literals, Collection<String> patterns, boolean reverseIndex, boolean uniqueTermsOnly,
                Collection<String> expansionFields) throws TableNotFoundException {
    
    // if we have no ranges, then nothing to scan
    if (ranges.isEmpty()) {
        return null;
    }
    
    BatchScanner bs = scannerFactory.newScanner(tableName, config.getAuthorizations(), config.getNumQueryThreads(), config.getQuery());
    
    bs.setRanges(ranges);
    
    // The begin date from the query may be down to the second, for doing lookups in the index we want to use the day because
    // the times in the index table have been truncated to the day.
    Date begin = DateUtils.truncate(config.getBeginDate(), Calendar.DAY_OF_MONTH);
    // we don't need to bump up the end date any more because it's not apart of the range set on the scanner
    Date end = config.getEndDate();
    
    LongRange dateRange = new LongRange(begin.getTime(), end.getTime());
    
    ShardIndexQueryTableStaticMethods.configureGlobalIndexDateRangeFilter(config, bs, dateRange);
    ShardIndexQueryTableStaticMethods.configureGlobalIndexDataTypeFilter(config, bs, config.getDatatypeFilter());
    
    ShardIndexQueryTableStaticMethods.configureGlobalIndexTermMatchingIterator(config, bs, literals, patterns, reverseIndex, uniqueTermsOnly,
                    expansionFields);
    
    bs.addScanIterator(new IteratorSetting(config.getBaseIteratorPriority() + 50, DiscoveryIterator.class));
    
    return bs;
}
 
Example 11
Source File: ShardIndexQueryTable.java    From datawave with Apache License 2.0 5 votes vote down vote up
/**
 * scan a global index (shardIndex or shardReverseIndex) for the specified ranges and create a set of fieldname/TermInformation values. The Key/Values
 * scanned are trimmed based on a set of terms to match, and a set of data types (found in the config)
 *
 * @param config
 * @param scannerFactory
 * @param tableName
 * @param ranges
 * @param literals
 * @param patterns
 * @param reverseIndex
 * @param expansionFields
 * @return the batch scanner
 * @throws TableNotFoundException
 */
public static BatchScanner configureBatchScanner(ShardQueryConfiguration config, ScannerFactory scannerFactory, String tableName, Collection<Range> ranges,
                Collection<String> literals, Collection<String> patterns, boolean reverseIndex, Collection<String> expansionFields)
                throws TableNotFoundException {
    
    // if we have no ranges, then nothing to scan
    if (ranges.isEmpty()) {
        return null;
    }
    
    if (log.isTraceEnabled()) {
        log.trace("Scanning " + tableName + " against " + ranges + " with auths " + config.getAuthorizations());
    }
    
    BatchScanner bs = scannerFactory.newScanner(tableName, config.getAuthorizations(), config.getNumQueryThreads(), config.getQuery());
    
    bs.setRanges(ranges);
    
    // The begin date from the query may be down to the second, for doing lookups in the index we want to use the day because
    // the times in the index table have been truncated to the day.
    Date begin = DateUtils.truncate(config.getBeginDate(), Calendar.DAY_OF_MONTH);
    // we don't need to bump up the end date any more because it's not apart of the range set on the scanner
    Date end = config.getEndDate();
    
    LongRange dateRange = new LongRange(begin.getTime(), end.getTime());
    
    ShardIndexQueryTableStaticMethods.configureGlobalIndexDateRangeFilter(config, bs, dateRange);
    ShardIndexQueryTableStaticMethods.configureGlobalIndexDataTypeFilter(config, bs, config.getDatatypeFilter());
    
    ShardIndexQueryTableStaticMethods.configureGlobalIndexTermMatchingIterator(config, bs, literals, patterns, reverseIndex, true, expansionFields);
    
    return bs;
}
 
Example 12
Source File: DateIndexDataTypeHandler.java    From datawave with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a date index entry
 * 
 * @param shardId
 * @param dataType
 * @param type
 * @param dateField
 * @param dateValue
 * @param visibility
 * @return The key and value
 */
public KeyValue getDateIndexEntry(String shardId, String dataType, String type, String dateField, String dateValue, ColumnVisibility visibility) {
    Date date = null;
    try {
        // get the date to be indexed
        date = dateNormalizer.denormalize(dateValue);
    } catch (Exception e) {
        log.error("Failed to normalize date value (skipping): " + dateValue, e);
        return null;
    }
    
    // set the time to 00:00:00 (for key timestamp)
    date = DateUtils.truncate(date, Calendar.DATE);
    
    // format the date and the shardId date as yyyyMMdd
    String rowDate = DateIndexUtil.format(date);
    String shardDate = ShardIdFactory.getDateString(shardId);
    
    ColumnVisibility biased = new ColumnVisibility(flatten(visibility));
    
    // The row is the date plus the shard partition
    String row = rowDate + '_' + getDateIndexShardPartition(rowDate, type, shardDate, dataType, dateField, new String(biased.getExpression()));
    
    // the colf is the type (e.g. LOAD or ACTIVITY)
    
    // the colq is the event date yyyyMMdd \0 the datatype \0 the field name
    String colq = shardDate + '\0' + dataType + '\0' + dateField;
    
    // the value is a bitset denoting the shard
    Value shardList = createDateIndexValue(ShardIdFactory.getShard(shardId));
    
    // create the key
    Key key = new Key(row, type, colq, biased, date.getTime());
    
    if (log.isTraceEnabled()) {
        log.trace("Dateate index key: " + key + " for shardId " + shardId);
    }
    
    return new KeyValue(key, shardList);
}
 
Example 13
Source File: DateTimeUtils.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Truncates the time from the calendar object.
 */
public static Calendar truncateToMidnight(Calendar calendar) {
    return DateUtils.truncate(calendar, Calendar.DAY_OF_MONTH);
}
 
Example 14
Source File: DataValueSetServiceTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testImportDataValuesWithDataSetAllowsPeriods()
    throws Exception
{
    Date thisMonth = DateUtils.truncate( new Date(), Calendar.MONTH );

    dsA.setExpiryDays( 62 );
    dsA.setOpenFuturePeriods( 2 );

    dataSetService.updateDataSet( dsA );

    Period tooEarly = createMonthlyPeriod( DateUtils.addMonths( thisMonth, 4 ) );
    Period okBefore = createMonthlyPeriod( DateUtils.addMonths( thisMonth, 1 ) );
    Period okAfter = createMonthlyPeriod( DateUtils.addMonths( thisMonth, -1 ) );
    Period tooLate = createMonthlyPeriod( DateUtils.addMonths( thisMonth, -4 ) );
    Period outOfRange =  createMonthlyPeriod( DateUtils.addMonths( thisMonth, 6 ) );

    periodService.addPeriod( tooEarly );
    periodService.addPeriod( okBefore );
    periodService.addPeriod( okAfter );
    periodService.addPeriod( tooLate );

    String importData =
        "<dataValueSet xmlns=\"http://dhis2.org/schema/dxf/2.0\" idScheme=\"code\" dataSet=\"DS_A\" orgUnit=\"OU_A\">\n" +
        "  <dataValue dataElement=\"DE_A\" period=\"" + tooEarly.getIsoDate() + "\" value=\"10001\" />\n" +
        "  <dataValue dataElement=\"DE_B\" period=\"" + okBefore.getIsoDate() + "\" value=\"10002\" />\n" +
        "  <dataValue dataElement=\"DE_C\" period=\"" + okAfter.getIsoDate() + "\" value=\"10003\" />\n" +
        "  <dataValue dataElement=\"DE_D\" period=\"" + tooLate.getIsoDate() + "\" value=\"10004\" />\n" +
        "  <dataValue dataElement=\"DE_D\" period=\"" + outOfRange.getIsoDate() + "\" value=\"10005\" />\n" +
        "</dataValueSet>\n";

    in = new ByteArrayInputStream( importData.getBytes( StandardCharsets.UTF_8 ) );

    ImportSummary summary = dataValueSetService.saveDataValueSet( in );

    assertEquals( summary.getConflicts().toString(), 3, summary.getConflicts().size() );
    assertEquals( 2, summary.getImportCount().getImported() );
    assertEquals( 0, summary.getImportCount().getUpdated() );
    assertEquals( 0, summary.getImportCount().getDeleted() );
    assertEquals( 3, summary.getImportCount().getIgnored() );
    assertEquals( ImportStatus.WARNING, summary.getStatus() );

    Collection<DataValue> dataValues = mockDataValueBatchHandler.getInserts();

    assertNotNull( dataValues );
    assertEquals( 2, dataValues.size() );
    assertTrue( dataValues.contains( new DataValue( deB, okBefore, ouA, ocDef, ocDef ) ) );
    assertTrue( dataValues.contains( new DataValue( deC, okAfter, ouA, ocDef, ocDef ) ) );
}
 
Example 15
Source File: DateTimeUtils.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Returns true, if cal1 is greater or equal than cal2, ignoring seconds.
 */
public static boolean isTimeGreaterEquals(Calendar cal1, Calendar cal2) {
    Calendar truncCal1 = DateUtils.truncate(cal1, Calendar.MINUTE);
    Calendar truncCal2 = DateUtils.truncate(cal2, Calendar.MINUTE);
    return truncCal1.getTimeInMillis() >= truncCal2.getTimeInMillis();
}
 
Example 16
Source File: QueryMetric.java    From datawave with Apache License 2.0 4 votes vote down vote up
public QueryMetric() {
    this.createDate = DateUtils.truncate(new Date(), Calendar.SECOND);
    this.host = System.getProperty("jboss.host.name");
}
 
Example 17
Source File: DateTimeUtils.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Truncates the time from the calendar object.
 */
public static Calendar truncateToMidnight(Calendar calendar) {
    return DateUtils.truncate(calendar, Calendar.DAY_OF_MONTH);
}
 
Example 18
Source File: DefaultQueryPlanner.java    From datawave with Apache License 2.0 2 votes vote down vote up
/**
 * Given a date, truncate it to year, month, date and increment the day by one to determine the following day.
 *
 * @param endDate
 * @return
 */
public static Date getEndDateForIndexLookup(Date endDate) {
    Date newDate = DateUtils.truncate(endDate, Calendar.DATE);
    return DateUtils.addDays(newDate, 1);
}