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:ch.algotrader.service.algo.VWAPOrderService.java

VWAPOrderStateVO createAlgoOrderState(final VWAPOrder algoOrder, final Date dateTime)
        throws OrderValidationException {

    Validate.notNull(algoOrder, "vwapOrder missing");

    Security security = algoOrder.getSecurity();
    SecurityFamily family = security.getSecurityFamily();
    Exchange exchange = family.getExchange();

    HistoricalDataService historicalDataService = this.applicationContext.getBean(HistoricalDataService.class);

    List<Bar> bars = historicalDataService.getHistoricalBars(security.getId(), //
            DateUtils.truncate(new Date(), Calendar.DATE), //
            algoOrder.getLookbackPeriod(), //
            TimePeriod.DAY, //
            algoOrder.getBucketSize(), //
            MarketDataEventType.TRADES, //
            Collections.emptyMap());

    TreeMap<LocalTime, Long> buckets = new TreeMap<>();
    Set<LocalDate> tradingDays = new HashSet<>();
    for (Bar bar : bars) {
        int vol = bar.getVol();
        LocalTime time = DateTimeLegacy.toLocalTime(bar.getDateTime());
        tradingDays.add(DateTimeLegacy.toLocalDate(bar.getDateTime()));
        if (buckets.containsKey(time)) {
            buckets.put(time, buckets.get(time) + vol);
        } else {/*  ww w.  j  a v  a  2 s  .  com*/
            buckets.put(time, (long) vol);
        }
    }

    // verify start and end time
    if (algoOrder.getStartTime() == null) {
        if (this.calendarService.isOpen(exchange.getId())) {
            algoOrder.setStartTime(dateTime);
        } else {
            Date nextOpenTime = this.calendarService.getNextOpenTime(exchange.getId());
            algoOrder.setStartTime(nextOpenTime);
        }
    }

    Date closeTime = this.calendarService.getNextCloseTime(exchange.getId());
    if (algoOrder.getEndTime() == null) {
        algoOrder.setEndTime(closeTime);
    }

    if (algoOrder.getStartTime().compareTo(dateTime) < 0) {
        throw new OrderValidationException("startTime needs to be in the future " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(dateTime) <= 0) {
        throw new OrderValidationException("endTime needs to be in the future " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(closeTime) > 0) {
        throw new OrderValidationException("endTime needs to be before next market closeTime for " + algoOrder);
    } else if (algoOrder.getEndTime().compareTo(algoOrder.getStartTime()) <= 0) {
        throw new OrderValidationException("endTime needs to be after startTime for " + algoOrder);
    }

    int historicalVolume = 0;
    LocalTime startTime = DateTimeLegacy.toLocalTime(algoOrder.getStartTime());
    LocalTime endTime = DateTimeLegacy.toLocalTime(algoOrder.getEndTime());
    LocalTime firstBucketStart = buckets.floorKey(startTime);
    LocalTime lastBucketStart = buckets.floorKey(endTime);

    SortedMap<LocalTime, Long> subBuckets = buckets.subMap(firstBucketStart, true, lastBucketStart, true);
    for (Map.Entry<LocalTime, Long> bucket : subBuckets.entrySet()) {

        long vol = bucket.getValue() / tradingDays.size();
        bucket.setValue(vol);

        if (bucket.getKey().equals(firstBucketStart)) {
            LocalTime firstBucketEnd = firstBucketStart.plus(algoOrder.getBucketSize().getValue(),
                    ChronoUnit.MILLIS);
            double fraction = (double) ChronoUnit.MILLIS.between(startTime, firstBucketEnd)
                    / algoOrder.getBucketSize().getValue();
            historicalVolume += vol * fraction;
        } else if (bucket.getKey().equals(lastBucketStart)) {
            double fraction = (double) ChronoUnit.MILLIS.between(lastBucketStart, endTime)
                    / algoOrder.getBucketSize().getValue();
            historicalVolume += vol * fraction;
        } else {
            historicalVolume += vol;
        }
    }

    double participation = algoOrder.getQuantity() / (double) historicalVolume;

    if (participation > MAX_PARTICIPATION) {
        throw new OrderValidationException("participation rate " + twoDigitFormat.format(participation * 100.0)
                + "% is above 50% of historical market volume for " + algoOrder);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.debug("participation of {} is {}%", algoOrder.getDescription(),
                twoDigitFormat.format(participation * 100.0));
    }

    return new VWAPOrderStateVO(participation, buckets);
}

From source file:com.augmentum.common.util.DateUtil.java

public static Date getDateFromStr(String str) {
    Date date = null;//from  w ww .j  ava 2s .  c o m

    if (NumberUtils.isDigits(str) && (str.length() == 4)) {
        Calendar cal = Calendar.getInstance();
        cal = DateUtils.truncate(cal, Calendar.MINUTE);
        cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(str.substring(0, 2)));
        cal.set(Calendar.MINUTE, Integer.parseInt(str.substring(2)));

        date = cal.getTime();
    }

    return date;
}

From source file:ch.algotrader.service.CalendarServiceImpl.java

/**
 * {@inheritDoc}//from w w  w . jav a2 s.c om
 */
@Override
public boolean isTradingDay(final long exchangeId, final Date date) {

    Validate.notNull(date, "Date is null");

    Exchange exchange = this.exchangeDao.get(exchangeId);
    Validate.notNull(exchange, "exchange not found");

    Date dateTruncated = DateUtils.truncate(date, Calendar.DATE);
    return isTradingDay(exchange, dateTruncated);

}

From source file:gov.utah.dts.det.ccl.model.view.BasicFacilityInformation.java

public int getDaysToExpiration() {
    if (licenseExpirationDate == null) {
        return 0;
    } else {/*from   w ww  .j  ava  2 s. c  o  m*/
        Date now = new Date();
        now = DateUtils.truncate(now, Calendar.DATE);
        if (licenseExpirationDate.compareTo(now) <= 0) {
            return 0;
        } else {
            int days = (int) Math
                    .ceil((licenseExpirationDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
            return days;
        }
    }
}

From source file:net.firejack.platform.api.statistics.StatisticsAPITests.java

@Test
public void checkStatisticsAPI() {
    OpenFlamePrincipal principal = OPFContext.getContext().getPrincipal();
    IUserInfoProvider user = principal.getUserInfoProvider();
    //=============== Log Entries ===============
    logger.info("Trying to read all log-entries...");
    ServiceResponse<LogEntry> logEntryResponse = OPFEngine.StatisticsService.readAllLogEntries();
    checkResponse(logEntryResponse);//  w w w  . ja  v a 2 s. c  o  m
    logger.info("logEntryResponse.getData().size() = " + logEntryResponse.getData().size());

    logger.info("Trying to find already existing test log entries.");
    logEntryResponse = searchTestLogEntries();
    int testEntriesCount = logEntryResponse.getData() == null ? 0 : logEntryResponse.getData().size();

    logger.info("Trying to create log entry");

    LogEntry logEntry1 = populateTestLogEntry(user, Boolean.TRUE);
    LogEntry logEntry2 = populateTestLogEntry(user, Boolean.FALSE);

    List<LogEntry> logEntriesToSave = new ArrayList<LogEntry>();
    logEntriesToSave.add(logEntry1);
    logEntriesToSave.add(logEntry2);

    ServiceRequest<LogEntry> request = new ServiceRequest<LogEntry>();
    request.setDataList(logEntriesToSave);

    ServiceResponse statusResponse = OPFEngine.StatisticsService.saveStatisticsBunch(request);
    checkResponse(statusResponse);

    logger.info("Trying to find just created log entries.");
    logEntryResponse = searchTestLogEntries();
    Assert.assertNotNull("logEntryResponse.getData() should not be null.", logEntryResponse.getData());
    Assert.assertTrue("testEntriesCount should be equal to " + (testEntriesCount + 2),
            logEntryResponse.getData().size() == testEntriesCount + 2);

    //================= Metrics =================
    logger.info("Trying to get count of already existent test metric tracks.");
    ServiceResponse<MetricsEntry> metricsResponse = searchTestMetrics();
    checkResponse(metricsResponse);
    int testMetricsCount = metricsResponse.getData() == null ? 0 : metricsResponse.getData().size();

    logger.info("Trying to save MetricsEntry...");
    MetricsEntry metricsEntry = new MetricsEntry();
    metricsEntry.setUserId(user.getId());
    metricsEntry.setUsername(user.getUsername());
    metricsEntry.setLookup(VAL_TEST_ACTION_LOOKUP);
    metricsEntry.setAverageExecutionTime(randomExecutionTime().doubleValue());
    metricsEntry.setAverageRequestSize(2000D);
    metricsEntry.setAverageResponseSize(2000D);
    metricsEntry.setMaxResponseTime(randomExecutionTime());
    metricsEntry.setMinResponseTime(randomExecutionTime());
    metricsEntry.setNumberOfInvocations(24L);
    metricsEntry.setSuccessRate(24D);
    Date hourlyDate = new Date();
    hourlyDate = DateUtils.truncate(hourlyDate, Calendar.HOUR);
    metricsEntry.setHourPeriod(hourlyDate.getTime());
    metricsEntry.setDayPeriod(DateUtils.truncate(hourlyDate, Calendar.DAY_OF_MONTH).getTime());
    Date weekPeriod = net.firejack.platform.core.utils.DateUtils.truncateDateToWeek(hourlyDate);
    metricsEntry.setWeekPeriod(weekPeriod.getTime());
    metricsEntry.setMonthPeriod(DateUtils.truncate(hourlyDate, Calendar.MONTH).getTime());

    ServiceRequest<MetricsEntry> metricsRequest = new ServiceRequest<MetricsEntry>(metricsEntry);
    statusResponse = OPFEngine.StatisticsService.saveMetricsEntry(metricsRequest);
    checkResponse(statusResponse);

    logger.info("Trying to get count of test metric tracks after saving one metric.");
    metricsResponse = searchTestMetrics();
    checkResponse(metricsResponse);
    Assert.assertNotNull("metricsResponse.getData() should nul be null", metricsResponse.getData());
    Assert.assertTrue("metricsResponse.getData().size() should be more or equal to " + testMetricsCount,
            metricsResponse.getData().size() >= testMetricsCount);

    logger.info("Trying to find metric by example...");
    metricsResponse = OPFEngine.StatisticsService.findMetricsEntryByExample(metricsRequest);
    checkResponse(metricsResponse);
    Assert.assertNotNull("metricsResponse.getData() should not be null.", metricsResponse.getData());
    logger.info("Tested all service methods successfully!");
}

From source file:ch.algotrader.service.CalendarServiceImpl.java

/**
 * {@inheritDoc}/* w  w  w  . ja v a2  s. c  om*/
 */
@Override
public Date getOpenTime(final long exchangeId, final Date date) {

    Validate.notNull(date, "Date is null");

    Exchange exchange = this.exchangeDao.get(exchangeId);
    Validate.notNull(exchange, "exchange not found");

    Date dateTruncated = DateUtils.truncate(date, Calendar.DATE);
    TimeIntervals timeIntervals = getTimeIntervals(exchange, dateTruncated);
    return timeIntervals.isEmpty() ? null : timeIntervals.first().getFrom();

}

From source file:com.iyonger.apm.web.service.PerfTestRunnable.java

private boolean isScheduledNow(PerfTest test) {
    Date current = new Date();
    Date scheduledDate = DateUtils.truncate((Date) defaultIfNull(test.getScheduledTime(), current),
            Calendar.MINUTE);/*w ww. j  a  v a 2  s.c om*/
    return current.after(scheduledDate);
}

From source file:de.hybris.platform.accountsummaryaddon.document.dao.impl.DefaultB2BDocumentDao.java

/**
 * Calculates the earliest file date as per the file age
 * for example: today 2000-01-5, numberOfDay is 4, so earliest file date is 2000-01-01
 *//* w  ww . ja v  a  2 s  .c o  m*/
protected Date getEarliestFileDate(final int numberOfDay) {

    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -1 * numberOfDay);
    c = DateUtils.truncate(c, Calendar.DATE);

    return c.getTime();
}

From source file:de.gmorling.scriptabledataset.ScriptableDataSetTest.java

private void assertNextRow(ResultSet rs, int expectedInt, String expectedString, Date expectedDate)
        throws SQLException {

    if (!rs.next())
        fail("Data set should have a row.");

    assertEquals(expectedInt, rs.getObject(1));
    assertEquals(expectedString, rs.getObject(2));
    assertEquals(DateUtils.truncate(expectedDate, Calendar.DATE),
            DateUtils.truncate(rs.getObject(3), Calendar.DATE));
}

From source file:com.clican.pluto.dataprocess.engine.processes.ForProcessor.java

public void process(ProcessorContext context) throws DataProcessException {
    try {//from   w  w w  .ja  v  a 2 s  .  co m
        Object startObj = null;
        Object endObj = null;
        String startChange = null;
        String endChange = null;
        if (StringUtils.isNotEmpty(start)) {
            if (start.contains("+")) {
                startObj = PropertyUtils.getNestedProperty(context.getMap(), start.split("\\+")[0].trim());
                startChange = start.split("\\+")[1].trim();
            } else if (start.contains("-")) {
                startObj = PropertyUtils.getNestedProperty(context.getMap(), start.split("\\-")[0].trim());
                startChange = "-" + start.split("\\-")[1].trim();
            } else {
                startObj = PropertyUtils.getNestedProperty(context.getMap(), start);
                if (startObj == null) {
                    startObj = start;
                }
            }

        }
        if (StringUtils.isNotEmpty(end)) {
            if (end.contains("+")) {
                endObj = PropertyUtils.getNestedProperty(context.getMap(), end.split("\\+")[0].trim());
                endChange = end.split("\\+")[1].trim();
            } else if (end.contains("-")) {
                endObj = PropertyUtils.getNestedProperty(context.getMap(), end.split("\\-")[0].trim());
                endChange = "-" + end.split("\\-")[1].trim();
            } else {
                endObj = PropertyUtils.getNestedProperty(context.getMap(), end);
                if (endObj == null) {
                    endObj = end;
                }
            }
        }

        if (startObj != null && endObj != null && NumberUtils.isNumber(startObj.toString())
                && NumberUtils.isNumber(endObj.toString()) && NumberUtils.isNumber(step)) {
            int s = Integer.parseInt(startObj.toString());
            if (startChange != null) {
                s = s + Integer.parseInt(startChange);
            }
            int e = Integer.parseInt(endObj.toString());
            if (endChange != null) {
                e = e + Integer.parseInt(endChange);
            }
            int p = Integer.parseInt(step);
            for (int i = s; i < e; i = i + p) {
                if (log.isDebugEnabled()) {
                    log.debug("ProcessorGroup[" + context.getProcessorGroupName() + "],?[" + i
                            + "/" + e + "]" + elementName + "=" + i);
                }
                context.setAttribute(elementName, i);
                for (DataProcessor iteratorProcessor : iteratorProcessors) {
                    if (stepCommit) {
                        dataProcessTransaction.doInCommit(iteratorProcessor, context);
                    } else {
                        doWithoutCommit(iteratorProcessor, context);
                    }
                }
            }
        } else if (startObj instanceof Date && (endObj instanceof Date || endObj == null)) {
            if (startChange != null) {
                startObj = DateUtils.add((Date) startObj, this.getField(startChange),
                        this.getChange(startChange));
            }
            int p = Integer.parseInt(step.replaceAll("day", "").replaceAll("month", "").replaceAll("year", ""));
            int field = -1;
            if (step.contains("day")) {
                field = Calendar.DAY_OF_MONTH;
            } else if (step.contains("month")) {
                field = Calendar.MONTH;
            } else if (step.contains("year")) {
                field = Calendar.YEAR;
            } else {
                throw new DataProcessException("?for");
            }
            if (endObj == null) {
                endObj = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
            } else if (endChange != null) {
                endObj = DateUtils.add((Date) endObj, this.getField(endChange), this.getChange(endChange));
            }
            for (Date i = (Date) startObj; i.compareTo((Date) endObj) < 0; i = DateUtils.add(i, field, p)) {
                // 1990041519910414?,
                // ?truncate,????
                i = DateUtils.truncate(i, field);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                ProcessorContext subContext;
                if (this.isCloneContext()) {
                    subContext = context.getCloneContext();
                } else {
                    subContext = context;
                }
                if (log.isDebugEnabled()) {

                    log.debug("ProcessorGroup[" + context.getProcessorGroupName() + "],?["
                            + sdf.format(i) + "/" + sdf.format((Date) endObj) + "]" + elementName + "="
                            + sdf.format(i));
                }
                subContext.setAttribute(elementName, i);
                for (DataProcessor iteratorProcessor : iteratorProcessors) {
                    if (stepCommit) {
                        dataProcessTransaction.doInCommit(iteratorProcessor, subContext);
                    } else {
                        doWithoutCommit(iteratorProcessor, subContext);
                    }
                }
                if (this.propagations != null && this.propagations.size() > 0) {
                    for (String propagation : propagations) {
                        context.setAttribute(propagation, subContext.getAttribute(propagation));
                    }
                }
            }
        } else {
            throw new DataProcessException("?for");
        }
    } catch (DataProcessException e) {
        throw e;
    } catch (Exception e) {
        throw new DataProcessException(e);
    }

}