Example usage for org.joda.time DateTime minus

List of usage examples for org.joda.time DateTime minus

Introduction

In this page you can find the example usage for org.joda.time DateTime minus.

Prototype

public DateTime minus(ReadablePeriod period) 

Source Link

Document

Returns a copy of this datetime with the specified period taken away.

Usage

From source file:org.graylog2.dashboards.widgets.strategies.StatisticalCountWidgetStrategy.java

License:Open Source License

@Override
public ComputationResult compute() {
    try {/*from  w ww .  jav a2  s  . com*/
        final String filter;
        if (!isNullOrEmpty(streamId)) {
            filter = "streams:" + streamId;
        } else {
            filter = null;
        }

        final TimeRange timeRange = this.timeRange;

        boolean needsCardinality = statsFunction.equals(StatisticalFunction.CARDINALITY);
        boolean needsCount = statsFunction.equals(StatisticalFunction.COUNT);
        final FieldStatsResult fieldStatsResult = getSearches().fieldStats(field, query, filter, timeRange,
                needsCardinality, !(needsCount || needsCardinality), needsCount);
        if (trend && timeRange instanceof RelativeRange) {
            DateTime toPrevious = timeRange.getFrom();
            DateTime fromPrevious = toPrevious.minus(Seconds.seconds(((RelativeRange) timeRange).getRange()));
            TimeRange previousTimeRange = AbsoluteRange.create(fromPrevious, toPrevious);

            final FieldStatsResult previousFieldStatsResult = getSearches().fieldStats(field, query, filter,
                    previousTimeRange, needsCardinality, !(needsCount || needsCardinality), needsCount);
            Map<String, Object> results = Maps.newHashMap();
            results.put("now", getStatisticalValue(fieldStatsResult));
            results.put("previous", getStatisticalValue(previousFieldStatsResult));
            long tookMs = fieldStatsResult.took().millis() + previousFieldStatsResult.took().millis();

            return new ComputationResult(results, tookMs);
        } else {
            return new ComputationResult(getStatisticalValue(fieldStatsResult),
                    fieldStatsResult.took().millis());
        }
    } catch (Searches.FieldTypeException e) {
        log.warn("Invalid field provided, returning 'NaN'", e);
        return new ComputationResult(Double.NaN, 0);
    }
}

From source file:org.graylog2.rest.resources.search.SearchResource.java

License:Open Source License

protected org.graylog2.plugin.indexer.searches.timeranges.TimeRange restrictTimeRange(
        final org.graylog2.plugin.indexer.searches.timeranges.TimeRange timeRange) {
    final DateTime originalFrom = timeRange.getFrom();
    final DateTime to = timeRange.getTo();
    final DateTime from;

    final SearchesClusterConfig config = clusterConfigService.get(SearchesClusterConfig.class);

    if (config == null || Period.ZERO.equals(config.queryTimeRangeLimit())) {
        from = originalFrom;//w  ww. j av a 2 s.c o m
    } else {
        final DateTime limitedFrom = to.minus(config.queryTimeRangeLimit());
        from = limitedFrom.isAfter(originalFrom) ? limitedFrom : originalFrom;
    }

    return AbsoluteRange.create(from, to);
}

From source file:org.graylog2.system.traffic.TrafficCounterService.java

License:Open Source License

public TrafficHistogram clusterTrafficOfLastDays(Duration duration, Interval interval) {
    final ImmutableMap.Builder<DateTime, Long> inputBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<DateTime, Long> outputBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<DateTime, Long> decodedBuilder = ImmutableMap.builder();
    final DateTime to = getDayBucket(Tools.nowUTC());
    final DateTime from = to.minus(duration);

    final DBQuery.Query query = DBQuery.and(DBQuery.lessThanEquals(BUCKET, to),
            DBQuery.greaterThan(BUCKET, from));

    final DBCursor<TrafficDto> cursor = db.find(query);
    cursor.forEach(trafficDto -> {//from  w  w  w.j a va2 s .co  m
        inputBuilder.put(trafficDto.bucket(),
                trafficDto.input().values().stream().mapToLong(Long::valueOf).sum());
        outputBuilder.put(trafficDto.bucket(),
                trafficDto.output().values().stream().mapToLong(Long::valueOf).sum());
        decodedBuilder.put(trafficDto.bucket(),
                trafficDto.decoded().values().stream().mapToLong(Long::valueOf).sum());
    });
    Map<DateTime, Long> inputHistogram = inputBuilder.build();
    Map<DateTime, Long> outputHistogram = outputBuilder.build();
    Map<DateTime, Long> decodedHistogram = decodedBuilder.build();

    // we might need to aggregate the hourly database values to their UTC daily buckets
    if (interval == Interval.DAILY) {
        inputHistogram = aggregateToDaily(inputHistogram);
        outputHistogram = aggregateToDaily(outputHistogram);
        decodedHistogram = aggregateToDaily(decodedHistogram);
    }
    return TrafficHistogram.create(from, to, inputHistogram, outputHistogram, decodedHistogram);
}

From source file:org.ireas.mediawiki.DefaultMediaWiki.java

License:Open Source License

private Map<String, String> getContribCountArguments(final String user, final int limit,
        final Set<Namespace> namespaces, final DateTime endDate, final Period period) {
    Map<String, String> arguments = getContribCountArguments(user, limit, namespaces, endDate);
    arguments.put(ApiConstants.UC_START, MediaWikiUtils.formatApiDate(endDate.minus(period)));
    return arguments;
}

From source file:org.isisaddons.module.fakedata.dom.JodaDateTimes.java

License:Apache License

@Programmatic
public DateTime before(final Period period) {
    final DateTime now = fake.clockService.nowAsDateTime();
    return now.minus(period);
}

From source file:org.jasig.cas.client.validation.Saml11TicketValidator.java

License:Apache License

private boolean isValidAssertion(final org.opensaml.saml1.core.Assertion assertion) {
    final DateTime notBefore = assertion.getConditions().getNotBefore();
    final DateTime notOnOrAfter = assertion.getConditions().getNotOnOrAfter();

    if (notBefore == null || notOnOrAfter == null) {
        logger.debug("Assertion has no bounding dates. Will not process.");
        return false;
    }//  w  ww .ja  va2s  .  c o  m

    final DateTime currentTime = new DateTime(DateTimeZone.UTC);
    final Interval validityRange = new Interval(notBefore.minus(this.tolerance),
            notOnOrAfter.plus(this.tolerance));

    if (validityRange.contains(currentTime)) {
        logger.debug("Current time is within the interval validity.");
        return true;
    }

    if (currentTime.isBefore(validityRange.getStart())) {
        logger.debug("skipping assertion that's not yet valid...");
        return false;
    }

    logger.debug("skipping expired assertion...");
    return false;
}

From source file:org.jasig.portal.events.aggr.PortalEventAggregationManagerImpl.java

License:Apache License

void doPopulateDateDimensions() {
    final DateTime now = getNow();

    final AggregationIntervalInfo startIntervalInfo;
    final DateTime oldestPortalEventTimestamp = this.portalEventDao.getOldestPortalEventTimestamp();
    if (oldestPortalEventTimestamp == null || now.isBefore(oldestPortalEventTimestamp)) {
        startIntervalInfo = this.intervalHelper.getIntervalInfo(AggregationInterval.YEAR,
                now.minus(this.dimensionBuffer));
    } else {//from  ww w  .  ja  va2  s.c o  m
        startIntervalInfo = this.intervalHelper.getIntervalInfo(AggregationInterval.YEAR,
                oldestPortalEventTimestamp.minus(this.dimensionBuffer));
    }

    final AggregationIntervalInfo endIntervalInfo;
    final DateTime newestPortalEventTimestamp = this.portalEventDao.getNewestPortalEventTimestamp();
    if (newestPortalEventTimestamp == null || now.isAfter(newestPortalEventTimestamp)) {
        endIntervalInfo = this.intervalHelper.getIntervalInfo(AggregationInterval.YEAR,
                now.plus(this.dimensionBuffer));
    } else {
        endIntervalInfo = this.intervalHelper.getIntervalInfo(AggregationInterval.YEAR,
                newestPortalEventTimestamp.plus(this.dimensionBuffer));
    }

    final DateMidnight start = startIntervalInfo.getStart().toDateMidnight();
    final DateMidnight end = endIntervalInfo.getEnd().toDateMidnight();

    doPopulateDateDimensions(start, end);
}

From source file:org.jasig.portal.events.aggr.PortalEventAggregationManagerImpl.java

License:Apache License

void doPurgeRawEvents() {
    final IEventAggregatorStatus eventPurgerStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(ProcessingType.PURGING, true);

    //Update status with current server name
    final String serverName = this.portalInfoProvider.getServerName();
    eventPurgerStatus.setServerName(serverName);
    eventPurgerStatus.setLastStart(new DateTime());

    //Determine date of most recently aggregated data
    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(ProcessingType.AGGREGATION, false);
    if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) {
        //Nothing has been aggregated, skip purging

        eventPurgerStatus.setLastEnd(new DateTime());
        eventAggregationManagementDao.updateEventAggregatorStatus(eventPurgerStatus);

        return;/*  w ww.j a va 2 s .  com*/
    }

    //Calculate purge end date from most recent aggregation minus the purge delay
    final DateTime lastAggregated = eventAggregatorStatus.getLastEventDate();
    final DateTime purgeEnd = lastAggregated.minus(this.purgeDelay);

    //Purge events
    logger.debug("Starting purge of events before {}", purgeEnd);
    final long start = System.nanoTime();
    final int events = portalEventDao.deletePortalEventsBefore(purgeEnd);
    logger.debug("Purged {} events before {} in {}ms",
            new Object[] { events, purgeEnd, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) });

    //Update the status object and store it
    eventPurgerStatus.setLastEventDate(purgeEnd.minusMillis(1)); //decrement by 1ms since deletePortalEventsBefore uses lessThan and not lessThanEqualTo 
    eventPurgerStatus.setLastEnd(new DateTime());
    eventAggregationManagementDao.updateEventAggregatorStatus(eventPurgerStatus);
}

From source file:org.jasig.portal.events.aggr.PortalEventPurgerImpl.java

License:Apache License

@AggrEventsTransactional
public EventProcessingResult doPurgeRawEvents() {
    if (!this.clusterLockService.isLockOwner(PURGE_RAW_EVENTS_LOCK_NAME)) {
        throw new IllegalStateException("The cluster lock " + PURGE_RAW_EVENTS_LOCK_NAME
                + " must be owned by the current thread and server");
    }/*from   w  w  w  .j  a v a2s  .co m*/

    final IEventAggregatorStatus eventPurgerStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(ProcessingType.PURGING, true);

    //Update status with current server name
    final String serverName = this.portalInfoProvider.getUniqueServerName();
    eventPurgerStatus.setServerName(serverName);
    eventPurgerStatus.setLastStart(new DateTime());

    //Determine date of most recently aggregated data
    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(ProcessingType.AGGREGATION, false);
    if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) {
        //Nothing has been aggregated, skip purging

        eventPurgerStatus.setLastEnd(new DateTime());
        eventAggregationManagementDao.updateEventAggregatorStatus(eventPurgerStatus);

        return new EventProcessingResult(0, null, null, true);
    }
    boolean complete = true;

    //Calculate purge end date from most recent aggregation minus the purge delay
    final DateTime lastAggregated = eventAggregatorStatus.getLastEventDate();
    DateTime purgeEnd = lastAggregated.minus(this.purgeDelay);

    //Determine the DateTime of the oldest event
    DateTime oldestEventDate = eventPurgerStatus.getLastEventDate();
    if (oldestEventDate == null) {
        oldestEventDate = this.portalEventDao.getOldestPortalEventTimestamp();
    }

    //Make sure purgeEnd is no more than 1 hour after the oldest event date to limit delete scope
    final DateTime purgeEndLimit = oldestEventDate.plusHours(1);
    if (purgeEndLimit.isBefore(purgeEnd)) {
        purgeEnd = purgeEndLimit;
        complete = false;
    }

    final Thread currentThread = Thread.currentThread();
    final String currentName = currentThread.getName();
    final int events;
    try {
        currentThread.setName(currentName + "-" + purgeEnd);

        //Purge events
        logger.debug("Starting purge of events before {}", purgeEnd);
        events = portalEventDao.deletePortalEventsBefore(purgeEnd);
    } finally {
        currentThread.setName(currentName);
    }

    //Update the status object and store it
    purgeEnd = purgeEnd.minusMillis(100); //decrement by 100ms since deletePortalEventsBefore uses lessThan and not lessThanEqualTo
    eventPurgerStatus.setLastEventDate(purgeEnd);
    eventPurgerStatus.setLastEnd(new DateTime());
    eventAggregationManagementDao.updateEventAggregatorStatus(eventPurgerStatus);

    return new EventProcessingResult(events, oldestEventDate, purgeEnd, complete);
}

From source file:org.jasig.portal.events.aggr.PortalEventSessionPurgerImpl.java

License:Apache License

@Override
@AggrEventsTransactional/*from w  w  w  . ja  va 2s . co m*/
public EventProcessingResult doPurgeEventSessions() {
    if (!this.clusterLockService.isLockOwner(PURGE_EVENT_SESSION_LOCK_NAME)) {
        throw new IllegalStateException("The cluster lock " + PURGE_EVENT_SESSION_LOCK_NAME
                + " must be owned by the current thread and server");
    }

    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(ProcessingType.AGGREGATION, false);
    if (eventAggregatorStatus == null || eventAggregatorStatus.getLastEventDate() == null) {
        return new EventProcessingResult(0, null, null, true);
    }

    final DateTime lastEventDate = eventAggregatorStatus.getLastEventDate();
    final DateTime sessionPurgeDate = lastEventDate.minus(eventSessionDuration);
    final int purgeCount = eventSessionDao.purgeEventSessionsBefore(sessionPurgeDate);

    return new EventProcessingResult(purgeCount, null, sessionPurgeDate, true);
}