Java Code Examples for org.joda.time.DateTime#isAfter()

The following examples show how to use org.joda.time.DateTime#isAfter() . 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: CpuTimeTask.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] getBytes() throws Exception {
    List<CpuTime> cpuTimes = Lists.newArrayList();

    DateTime time = start;
    while (!time.isAfter(end)) {
        String timestamp = DateUtils.TIME_FORMATTER.print(time);
        int cpuTime = getCpuTime(timestamp);
        if (cpuTime > 0) {
            cpuTimes.add(new CpuTime(timestamp, cpuTime));
        }
        time = time.plusMinutes(1);
    }

    Map<String, Object> map = Maps.newHashMap();

    map.put("type", "cpuTime");
    if (!Strings.isNullOrEmpty(threadId)) {
        map.put("threadId", threadId);
    }
    map.put("cpuTimes", cpuTimes);
    map.put("start", DateUtils.TIME_FORMATTER.print(start));
    map.put("end", DateUtils.TIME_FORMATTER.print(end));
    return JacksonSerializer.serializeToBytes(map);
}
 
Example 2
Source File: ThreadNumTask.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected byte[] getBytes() throws Exception {
    List<ThreadNum> threadNums = Lists.newArrayList();

    DateTime time = start;
    while (!time.isAfter(end)) {
        String timestamp = DateUtils.TIME_FORMATTER.print(time);
        int threadNum = getThreadNum(timestamp);
        if (threadNum > 0) {
            threadNums.add(new ThreadNum(timestamp, threadNum));
        }
        time = time.plusMinutes(1);
    }

    Map<String, Object> map = Maps.newHashMap();

    map.put("type", "threadNum");
    map.put("threadNums", threadNums);
    map.put("start", DateUtils.TIME_FORMATTER.print(start));
    map.put("end", DateUtils.TIME_FORMATTER.print(end));
    return JacksonSerializer.serializeToBytes(map);
}
 
Example 3
Source File: AggregatesAlertCondition.java    From graylog-plugin-aggregates with GNU General Public License v3.0 6 votes vote down vote up
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;
    } else {
        final DateTime limitedFrom = to.minus(config.queryTimeRangeLimit());
        from = limitedFrom.isAfter(originalFrom) ? limitedFrom : originalFrom;
    }

    return AbsoluteRange.create(from, to);
}
 
Example 4
Source File: SamlFederationResource.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Check that the current time is within the specified range.
 *
 * @param notBefore
 *            - can be null to skip before check
 * @param notOnOrAfter
 *            - can be null to skip after check
 *
 * @return true if in range, false otherwise
 */
private boolean isTimeInRange(String notBefore, String notOnOrAfter) {
    DateTime currentTime = new DateTime(DateTimeZone.UTC);

    if (notBefore != null) {
        DateTime calNotBefore = DateTime.parse(notBefore);
        if (currentTime.isBefore(calNotBefore)) {
            LOG.debug("{} is before {}.", currentTime, calNotBefore);
            return false;
        }
    }

    if (notOnOrAfter != null) {
        DateTime calNotOnOrAfter = DateTime.parse(notOnOrAfter);
        if (currentTime.isAfter(calNotOnOrAfter) || currentTime.isEqual(calNotOnOrAfter)) {
            LOG.debug("{} is on or after {}.", currentTime, calNotOnOrAfter);
            return false;
        }
    }
    return true;
}
 
Example 5
Source File: DeleteFolderServiceImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return EntityId of associated component if exists
 */
private Optional<EntityId> deleteAsset(final Repository repository,
                                       final EntityId assetId,
                                       final DateTime timestamp,
                                       final ComponentMaintenance componentMaintenance)
{
  EntityId componenetId = null;
  Asset asset = assetStore.getById(assetId);
  if (timestamp.isAfter(asset.blobCreated()) && canDeleteAsset(repository, asset)) {
    try {
      componentMaintenance.deleteAsset(assetId);
      componenetId = asset.componentId();
    }
    catch (Exception e) {
      log.error("Failed to delete an asset - skipping.", e);
    }
  }
  return Optional.ofNullable(componenetId);
}
 
Example 6
Source File: DateGroup.java    From AppStash with Apache License 2.0 5 votes vote down vote up
public static boolean isCacheable(DateGroup dateGroup) {
    if (dateGroup == null || dateGroup.getDate() == null) {
        return false;
    }
    DateTime now = nowWithGranularity(dateGroup.getChoice());
    return now.isAfter(dateGroup.getDate().getTime());
}
 
Example 7
Source File: UserPersonalInfoValidator.java    From mamute with Apache License 2.0 5 votes vote down vote up
public boolean validate(UserPersonalInfo info) {
	brutalValidator.validate(info);
	if(validator.hasErrors()){
		return false;
	}
	
	if (info.getUser() == null) {
	    validator.add(messageFactory.build("error", "user.errors.wrong"));
	    return false;
	}
	
	if (!info.getUser().getEmail().equals(info.getEmail())){
		emailValidator.validate(info.getEmail());
	}
	
	if (info.getBirthDate() != null && info.getBirthDate().getYear() > DateTime.now().getYear()-12){
		validator.add(messageFactory.build("error", "user.errors.invalid_birth_date.min_age"));
	}

	if(!info.getUser().getName().equals(info.getName())){
		DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt();
		if (nameLastTouchedAt != null && nameLastTouchedAt.isAfter(new DateTime().minusDays(30))) {
			validator.add(messageFactory.build(
					"error", 
					"user.errors.name.min_time", 
					nameLastTouchedAt.plusDays(30).toString(DateTimeFormat.forPattern(bundle.getMessage("date.joda.simple.pattern")))
			));
		}
	}
	
	return !validator.hasErrors();
}
 
Example 8
Source File: SwingJideClockWidget.java    From atdl4j with MIT License 5 votes vote down vote up
/**
 * Used when applying Clock@initValue (xs:time)
 * @param aValue
 * @param @InitValueMode
 */
protected void setAndRenderInitValue( XMLGregorianCalendar aValue, int aInitValueMode )
{
	if ( aValue != null )
	{
		// -- Note that this will throw IllegalArgumentException if timezone ID
		// specified cannot be resolved --
		DateTimeZone tempLocalMktTz = getLocalMktTz();
		logger.debug( "control.getID(): " + control.getID() + " aValue: " + aValue + " getLocalMktTz(): " + tempLocalMktTz );

		// -- localMktTz is required when using/interpreting aValue --
		if ( tempLocalMktTz == null )
		{
			throw new IllegalArgumentException( "localMktTz is required when aValue (" + aValue + ") is specified. (Control.ID: "
					+ control.getID() + ")" );
		}

		DateTime tempNow = new DateTime( tempLocalMktTz );

		DateTime tempInit = new DateTime( 
				( showMonthYear && aValue.getYear() != DatatypeConstants.FIELD_UNDEFINED ) ? aValue.getYear() : tempNow.getYear(), 
				( showMonthYear && aValue.getMonth() != DatatypeConstants.FIELD_UNDEFINED ) ? aValue.getMonth() : tempNow.getMonthOfYear(), 
				( showMonthYear && aValue.getDay() != DatatypeConstants.FIELD_UNDEFINED ) ? aValue.getDay() : tempNow.getDayOfMonth(), 
				( showTime && aValue.getHour() != DatatypeConstants.FIELD_UNDEFINED ) ? aValue.getHour() : 0,
				( showTime && aValue.getMinute() != DatatypeConstants.FIELD_UNDEFINED ) ? aValue.getMinute() : 0,
				( showTime && aValue.getSecond() != DatatypeConstants.FIELD_UNDEFINED ) ? aValue.getSecond(): 0, 
				0,
				tempLocalMktTz );
		
		if ( ( aInitValueMode == Atdl4jConstants.CLOCK_INIT_VALUE_MODE_USE_CURRENT_TIME_IF_LATER ) &&
			  ( tempNow.isAfter( tempInit ) ) )
		{
			// -- Use current time --
			tempInit = tempNow;
		}
		
		// -- Make sure that the value is rendered on the display in local timezone --
		setValue( tempInit.withZone( DateTimeZone.getDefault() ) );
	}
}
 
Example 9
Source File: AcademicCalendarEntry.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void setTimeInterval(DateTime begin, DateTime end) {

        if (begin == null) {
            throw new DomainException("error.AcademicCalendarEntry.empty.begin.dateTime");
        }
        if (end == null) {
            throw new DomainException("error.AcademicCalendarEntry.empty.end.dateTime");
        }
        if (!end.isAfter(begin)) {
            throw new DomainException("error.begin.after.end");
        }

        super.setBegin(begin);
        super.setEnd(end);

        GenericPair<DateTime, DateTime> maxAndMinDateTimes = getChildMaxAndMinDateTimes();
        if (maxAndMinDateTimes != null
                && (getBegin().isAfter(maxAndMinDateTimes.getLeft()) || getEnd().isBefore(maxAndMinDateTimes.getRight()))) {
            throw new DomainException("error.AcademicCalendarEntry.out.of.bounds");
        }

        if (!getParentEntry().areIntersectionsPossible(this)) {
            for (AcademicCalendarEntry childEntry : getParentEntry().getChildEntriesWithTemplateEntries(getClass())) {
                if (!childEntry.equals(this) && childEntry.entriesTimeIntervalIntersection(begin, end)) {
                    throw new DomainException("error.AcademicCalendarEntry.dates.intersection");
                }
            }
        }

        refreshParentTimeInterval();
    }
 
Example 10
Source File: MobilityApplicationProcess.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkParameters(final ExecutionInterval executionInterval, final DateTime start, final DateTime end) {
    if (executionInterval == null) {
        throw new DomainException("error.SecondCycleCandidacyProcess.invalid.executionInterval");
    }

    if (start == null || end == null || start.isAfter(end)) {
        throw new DomainException("error.SecondCycleCandidacyProcess.invalid.interval");
    }
}
 
Example 11
Source File: LessonSpaceOccupation.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean isOccupiedByExecutionCourse(final ExecutionCourse executionCourse, final DateTime start, final DateTime end) {
    final Lesson lesson = getLesson();
    if (lesson.getExecutionCourse() == executionCourse) {
        final List<Interval> intervals =
                getEventSpaceOccupationIntervals(start.toYearMonthDay(), end.toYearMonthDay().plusDays(1));
        for (final Interval interval : intervals) {
            if (start.isBefore(interval.getEnd()) && end.isAfter(interval.getStart())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 12
Source File: CompactionTimeRangeVerifier.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public Result verify (FileSystemDataset dataset) {
  final DateTime earliest;
  final DateTime latest;
  try {
    CompactionPathParser.CompactionParserResult result = new CompactionPathParser(state).parse(dataset);
    DateTime folderTime = result.getTime();
    DateTimeZone timeZone = DateTimeZone.forID(this.state.getProp(MRCompactor.COMPACTION_TIMEZONE, MRCompactor.DEFAULT_COMPACTION_TIMEZONE));
    DateTime compactionStartTime = new DateTime(this.state.getPropAsLong(CompactionSource.COMPACTION_INIT_TIME), timeZone);
    PeriodFormatter formatter = new PeriodFormatterBuilder().appendMonths().appendSuffix("m").appendDays().appendSuffix("d").appendHours()
            .appendSuffix("h").toFormatter();

    // Dataset name is like 'Identity/MemberAccount' or 'PageViewEvent'
    String datasetName = result.getDatasetName();

    // get earliest time
    String maxTimeAgoStrList = this.state.getProp(TimeBasedSubDirDatasetsFinder.COMPACTION_TIMEBASED_MAX_TIME_AGO, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MAX_TIME_AGO);
    String maxTimeAgoStr = getMachedLookbackTime(datasetName, maxTimeAgoStrList, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MAX_TIME_AGO);
    Period maxTimeAgo = formatter.parsePeriod(maxTimeAgoStr);
    earliest = compactionStartTime.minus(maxTimeAgo);

    // get latest time
    String minTimeAgoStrList = this.state.getProp(TimeBasedSubDirDatasetsFinder.COMPACTION_TIMEBASED_MIN_TIME_AGO, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MIN_TIME_AGO);
    String minTimeAgoStr = getMachedLookbackTime(datasetName, minTimeAgoStrList, TimeBasedSubDirDatasetsFinder.DEFAULT_COMPACTION_TIMEBASED_MIN_TIME_AGO);
    Period minTimeAgo = formatter.parsePeriod(minTimeAgoStr);
    latest = compactionStartTime.minus(minTimeAgo);

    if (earliest.isBefore(folderTime) && latest.isAfter(folderTime)) {
      log.debug("{} falls in the user defined time range", dataset.datasetRoot());
      return new Result(true, "");
    }
  } catch (Exception e) {
    log.error("{} cannot be verified because of {}", dataset.datasetRoot(), ExceptionUtils.getFullStackTrace(e));
    return new Result(false, e.toString());
  }
  return new Result(false, dataset.datasetRoot() + " is not in between " + earliest + " and " + latest);
}
 
Example 13
Source File: Person.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean getCanValidateContacts() {
    final DateTime now = new DateTime();
    final DateTime requestDate = getLastValidationRequestDate();
    if (requestDate == null || getNumberOfValidationRequests() == null) {
        return true;
    }
    final DateTime plus30 = requestDate.plusDays(30);
    if (now.isAfter(plus30) || now.isEqual(plus30)) {
        setNumberOfValidationRequests(0);
    }
    return getNumberOfValidationRequests() <= MAX_VALIDATION_REQUESTS;
}
 
Example 14
Source File: DegreeTransferCandidacyProcess.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void checkParameters(final ExecutionInterval executionInterval, final DateTime start, final DateTime end) {
    if (executionInterval == null) {
        throw new DomainException("error.DegreeTransferCandidacyProcess.invalid.executionInterval");
    }

    if (start == null || end == null || start.isAfter(end)) {
        throw new DomainException("error.DegreeTransferCandidacyProcess.invalid.interval");
    }
}
 
Example 15
Source File: HoraireComparator.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(IHoraireRows lhs, IHoraireRows rhs) {
    DateTimeFormatter formatter = null;
    DateTime eventDay1 = null;
    DateTime eventDay2 = null;

    if(lhs.getClass().equals(Event.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        eventDay1 = formatter.parseDateTime(lhs.getDateDebut());
    }
    if(rhs.getClass().equals(Event.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        eventDay2 = formatter.parseDateTime(rhs.getDateDebut());
    }

    if (lhs.getClass().equals(Seances.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
        eventDay1 = formatter.parseDateTime(lhs.getDateDebut());
    }
    if (rhs.getClass().equals(Seances.class)){
        formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
        eventDay2 = formatter.parseDateTime(rhs.getDateDebut());
    }

    if (eventDay1.isAfter(eventDay2)) {
        return 1;
    }
    else if(eventDay1.isBefore(eventDay2)){
        return -1;
    }
    else if(eventDay1.isEqual(eventDay2)){
        return 0;
    }
    return 0;
}
 
Example 16
Source File: EntityDateHelper.java    From secure-data-service with Apache License 2.0 4 votes vote down vote up
private static boolean isBeforeOrEqualDate(String begin, DateTime upToDate) {
    DateTime beginDate = (begin == null) ? DateTime.now().toDateMidnight().toDateTime() : DateTime.parse(begin, DateHelper.getDateTimeFormat());
    return !beginDate.isAfter(upToDate.toDateMidnight().toDateTime());
}
 
Example 17
Source File: ComposerHostedMetadataFacetImpl.java    From nexus-repository-composer with Eclipse Public License 1.0 4 votes vote down vote up
private boolean hasBlobBeenUpdated(final AssetUpdatedEvent updated) {
  DateTime blobUpdated = updated.getAsset().blobUpdated();
  DateTime oneMinuteAgo = now().minusMinutes(1);
  return blobUpdated == null || blobUpdated.isAfter(oneMinuteAgo);
}
 
Example 18
Source File: DateUtil.java    From narrate-android with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if a given date is anytime this month.
 *
 * @param   date Date to inspect
 * @return  True if the date is sometime this month, false if not
 */
public static boolean isCurrentMonth(DateTime date) {
    DateTime firstDayOfMonthMidnight = DateTime.now(DateTimeZone.getDefault()).withDayOfMonth(Calendar.getInstance(Locale.getDefault()).getMinimum(Calendar.DAY_OF_MONTH)).withTimeAtStartOfDay();
    DateTime firstDayOfNextMonth = firstDayOfMonthMidnight.plusMonths(1);
    return ((firstDayOfMonthMidnight.isEqual(date.getMillis())) || firstDayOfMonthMidnight.isBefore(date.getMillis())) && firstDayOfNextMonth.isAfter(date.getMillis());
}
 
Example 19
Source File: DateUtil.java    From narrate-android with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if a given date is anytime prior to today
 *
 * @param   date Date to inspect
 * @return  True if the date is some time prior to midnight today, false otherwise
 */
public static boolean isHistoricalDay(DateTime date) {
    DateTime todayMidnight = new DateTime().withTimeAtStartOfDay();
    return todayMidnight.isAfter(date.getMillis());
}
 
Example 20
Source File: DateUtil.java    From narrate-android with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if a given date is anytime yesterday
 *
 * @param   date Date to inspect
 * @return  True if the date is sometime yesterday, false if not
 */
public static boolean isYesterday(DateTime date) {
    DateTime todayMidnight = new DateTime().withTimeAtStartOfDay();
    DateTime yesterdayMidnight = new DateTime().minusDays(1).withTimeAtStartOfDay();
    return (yesterdayMidnight.getMillis() == date.getMillis()) || (yesterdayMidnight.isBefore(date.getMillis()) && todayMidnight.isAfter(date.getMillis()));
}