Example usage for java.time.temporal ChronoUnit DAYS

List of usage examples for java.time.temporal ChronoUnit DAYS

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit DAYS.

Prototype

ChronoUnit DAYS

To view the source code for java.time.temporal ChronoUnit DAYS.

Click Source Link

Document

Unit that represents the concept of a day.

Usage

From source file:alfio.model.Event.java

public boolean expiredSince(int days) {
    return ZonedDateTime.now(getZoneId()).truncatedTo(ChronoUnit.DAYS).minusDays(days)
            .isAfter(getEnd().truncatedTo(ChronoUnit.DAYS));
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepositoryTest.java

@Test
public void getRegistrationTest()
        throws URISyntaxException, RegistrationPersistenceException, EmptyResultDataAccessException {
    RegisterContext registerContext = createRegisterContextTemperature();
    registerContext.setRegistrationId("12345");
    Instant expirationDate = Instant.now().plus(1, ChronoUnit.DAYS);
    Registration registration = new Registration(expirationDate, registerContext);
    registrationsRepository.saveRegistration(registration);
    Registration foundRegistration = registrationsRepository.getRegistration("12345");
    Assert.assertNotNull(foundRegistration);
    Assert.assertEquals(expirationDate, foundRegistration.getExpirationDate());
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepositoryTest.java

@Test
public void getRegistrationWithExceptionTest()
        throws URISyntaxException, RegistrationPersistenceException, EmptyResultDataAccessException {
    thrown.expect(RegistrationPersistenceException.class);
    Instant expirationDate = Instant.now().plus(1, ChronoUnit.DAYS);
    jdbcTemplate.update("insert into t_registrations(id,expirationDate,registerContext) values(?,?,?)", "12345",
            expirationDate.toString(), "aaaaaa");
    Registration foundRegistration = registrationsRepository.getRegistration("12345");
}

From source file:com.netflix.genie.web.tasks.job.JobMonitorTest.java

/**
 * Make sure that a timed out process sends event.
 * @throws Exception in case of error/* www . ja va2 s.c  o m*/
 */
@Test
public void canTryToKillTimedOutProcess() throws Exception {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);

    // Set timeout to yesterday to force timeout when check happens
    final Instant yesterday = Instant.now().minus(1, ChronoUnit.DAYS);
    this.jobExecution = new JobExecution.Builder(UUID.randomUUID().toString()).withProcessId(3808)
            .withCheckDelay(DELAY).withTimeout(yesterday).withId(UUID.randomUUID().toString()).build();
    this.monitor = new JobMonitor(this.jobExecution, this.stdOut, this.stdErr, this.genieEventBus,
            this.registry, JobsProperties.getJobsPropertiesDefaults(), processChecker);

    Mockito.doThrow(new GenieTimeoutException("...")).when(processChecker).checkProcess();

    this.monitor.run();

    final ArgumentCaptor<KillJobEvent> captor = ArgumentCaptor.forClass(KillJobEvent.class);
    Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(captor.capture());

    Assert.assertNotNull(captor.getValue());
    final String jobId = this.jobExecution.getId().orElseThrow(IllegalArgumentException::new);
    Assert.assertThat(captor.getValue().getId(), Matchers.is(jobId));
    Assert.assertThat(captor.getValue().getReason(), Matchers.is(JobStatusMessages.JOB_EXCEEDED_TIMEOUT));
    Assert.assertThat(captor.getValue().getSource(), Matchers.is(this.monitor));
    Mockito.verify(this.timeoutRate, Mockito.times(1)).increment();
}

From source file:com.simiacryptus.util.Util.java

/**
 * Cvt temporal unit.// w  w  w  .  j  a v a  2s  .c  o m
 *
 * @param units the units
 * @return the temporal unit
 */
@javax.annotation.Nonnull
public static TemporalUnit cvt(@javax.annotation.Nonnull final TimeUnit units) {
    switch (units) {
    case DAYS:
        return ChronoUnit.DAYS;
    case HOURS:
        return ChronoUnit.HOURS;
    case MINUTES:
        return ChronoUnit.MINUTES;
    case SECONDS:
        return ChronoUnit.SECONDS;
    case NANOSECONDS:
        return ChronoUnit.NANOS;
    case MICROSECONDS:
        return ChronoUnit.MICROS;
    case MILLISECONDS:
        return ChronoUnit.MILLIS;
    default:
        throw new IllegalArgumentException(units.toString());
    }
}

From source file:com.example.app.profile.model.company.CompanyModelExtension.java

/**
 * Add image./*from ww w  . j  a v a 2  s  .  c  o m*/
 *
 * @param imageParams the image params.
 */
public static void addImage(ImageParams imageParams) {
    EntityRetriever er = EntityRetriever.getInstance();
    imageParams.getDmb().addChild(imageParams.getDomainModelName(), String.class)
            .setUsageInstructions(IMAGE_USAGE_INSTRUCTIONS())
            .addDataResolver(String.class, (domainModelContext, domainModel, arguments) -> {
                final FileEntity image = er.reattachIfNecessary((FileEntity) imageParams.getImageResolver()
                        .resolve(domainModelContext, domainModel, arguments));
                FactoryResourceConfiguration config = null;
                if (image != null && !image.isEntityTrashed()) {
                    try {
                        if (imageParams.getDimension() != null) {
                            int width = imageParams.getDimension().getWidthMetric().intValue();
                            int height = imageParams.getDimension().getHeightMetric().intValue();
                            final Dimension scaledDimension = getScaledDimension(getDimension(image), width,
                                    height);
                            final String resourceId = imageParams.getImageResourceFactory()
                                    .getPersistentResourceId(image, scaledDimension.getWidthMetric().intValue(),
                                            scaledDimension.getHeightMetric().intValue());
                            config = new FactoryResourceConfiguration(
                                    imageParams.getImageResourceFactory().getFactoryId(), resourceId);
                        }
                    } catch (IOException ioe) {
                        _logger.debug("Unable to get scaled image.", ioe);
                    }
                    if (config == null) {
                        config = new FactoryResourceConfiguration(
                                imageParams.getFileResourceFactory().getFactoryId(),
                                imageParams.getFileResourceFactory().getPersistentResourceId(image));
                    }
                    config.setExpireInterval(4, ChronoUnit.HOURS);
                } else {
                    config = new FactoryResourceConfiguration(imageParams.getAppUtil().getDefaultUserImage());
                    config.setExpireInterval(30, ChronoUnit.DAYS);
                }
                imageParams.getUrlGenerator().setHostname(domainModelContext.getSite().getDefaultHostname());
                return imageParams.getUrlGenerator().createURL(config).getLink().getURIAsString();
            });
}

From source file:com.netflix.spinnaker.igor.travis.TravisBuildMonitor.java

private List<Repo> filterOutOldBuilds(List<Repo> repos) {
    /*/*from  w w  w. ja va2  s .com*/
    BUILD_STARTED_AT_THRESHOLD is here because the builds can be picked up by igor before lastBuildStartedAt is
    set. This means the TTL can be set in the BuildCache before lastBuildStartedAt, if that happens we need a
    grace threshold so that we don't resend the event to echo. The value of the threshold assumes that travis
    will set the lastBuildStartedAt within 30 seconds.
    */
    final Instant threshold = Instant.now().minus(travisProperties.getCachedJobTTLDays(), ChronoUnit.DAYS)
            .plusMillis(BUILD_STARTED_AT_THRESHOLD);
    return repos.stream().filter(
            repo -> repo.getLastBuildStartedAt() != null && repo.getLastBuildStartedAt().isAfter(threshold))
            .collect(Collectors.toList());
}

From source file:jenkins.security.apitoken.ApiTokenStatsTest.java

@Test
public void testDayDifference() throws Exception {
    final String ID = UUID.randomUUID().toString();
    ApiTokenStats tokenStats = new ApiTokenStats();
    tokenStats.setParent(tmp.getRoot());
    ApiTokenStats.SingleTokenStats stats = tokenStats.updateUsageForId(ID);
    assertThat(stats.getNumDaysUse(), lessThan(1L));

    Field field = ApiTokenStats.SingleTokenStats.class.getDeclaredField("lastUseDate");
    field.setAccessible(true);//from w w w . j  a v a  2 s. c  om
    field.set(stats, new Date(new Date().toInstant().minus(2, ChronoUnit.DAYS)
            // to ensure we have more than 2 days
            .minus(5, ChronoUnit.MINUTES).toEpochMilli()));

    assertThat(stats.getNumDaysUse(), greaterThanOrEqualTo(2L));
}

From source file:nu.yona.server.analysis.service.ActivityService.java

@Transactional
public Page<DayActivityOverviewDto<DayActivityWithBuddiesDto>> getUserDayActivityOverviewsWithBuddies(
        UUID userId, Pageable pageable) {
    UUID userAnonymizedId = userService.getUserAnonymizedId(userId);
    UserAnonymizedDto userAnonymized = userAnonymizedService.getUserAnonymized(userAnonymizedId);

    Interval interval = getInterval(getCurrentDayDate(userAnonymized), pageable, ChronoUnit.DAYS);
    Set<BuddyDto> buddies = buddyService.getBuddiesOfUserThatAcceptedSending(userId);
    List<DayActivityOverviewDto<DayActivityWithBuddiesDto>> dayActivityOverviews = getUserDayActivityOverviewsWithBuddies(
            userAnonymizedId, interval, buddies);
    return new PageImpl<>(dayActivityOverviews, pageable, getTotalPageableItems(buddies, ChronoUnit.DAYS));
}

From source file:nu.yona.server.analysis.service.ActivityUpdateServiceTest.java

@Test
public void addActivity_appActivityOnNewDay_newDayActivityButNoGoalConflictMessageCreated() {
    ZonedDateTime today = now().truncatedTo(ChronoUnit.DAYS);
    // mock earlier activity at yesterday 23:59:58,
    // add new activity at today 00:00:01
    ZonedDateTime existingActivityTime = today.minusDays(1).withHour(23).withMinute(59).withSecond(58);

    DayActivity existingDayActivity = mockExistingActivity(gamblingGoal, existingActivityTime);
    ActivityDto lastRegisteredActivity = ActivityDto.createInstance(existingDayActivity.getActivities().get(0));

    ZonedDateTime startTime = today.withHour(0).withMinute(0).withSecond(1);
    ZonedDateTime endTime = today.withHour(0).withMinute(10);

    service.addActivity(userAnonEntity, createPayload(startTime, endTime), GoalDto.createInstance(gamblingGoal),
            Optional.of(lastRegisteredActivity));

    verifyNoGoalConflictMessagesCreated();

    // Verify there are now two day activities
    verify(mockUserAnonymizedService, atLeastOnce()).updateUserAnonymized(userAnonEntity);
    List<WeekActivity> weekActivities = gamblingGoal.getWeekActivities();
    assertThat("One week activity created", weekActivities.size(), equalTo(1));
    List<DayActivity> dayActivities = weekActivities.get(0).getDayActivities();
    assertThat("Two day activities created", dayActivities.size(), equalTo(2));
    DayActivity yesterdaysDayActivity;//from  w w  w  .  j a  v a 2 s.c  o m
    DayActivity todaysDayActivity;
    if (dayActivities.get(0).getStartDate().isBefore(dayActivities.get(1).getStartDate())) {
        yesterdaysDayActivity = dayActivities.get(0);
        todaysDayActivity = dayActivities.get(1);
    } else {
        yesterdaysDayActivity = dayActivities.get(1);
        todaysDayActivity = dayActivities.get(0);
    }

    // Double check yesterday's activity
    List<Activity> yesterdaysActivities = yesterdaysDayActivity.getActivities();
    assertThat("One activity created for yesterday", yesterdaysActivities.size(), equalTo(1));
    Activity yesterdaysActivity = yesterdaysActivities.get(0);
    assertThat("Expect right goal set to yesterday's activity", yesterdaysActivity.getActivityCategory(),
            equalTo(gamblingGoal.getActivityCategory()));

    // Verify one activity was created, with the right goal
    List<Activity> activities = todaysDayActivity.getActivities();
    assertThat("One activity created", activities.size(), equalTo(1));
    Activity activity = activities.get(0);
    assertThat("Expect right goal set to activity", activity.getActivityCategory(),
            equalTo(gamblingGoal.getActivityCategory()));

    assertThat("Expect new day", todaysDayActivity, not(equalTo(existingDayActivity)));
    assertThat("Expect right date", todaysDayActivity.getStartDate(), equalTo(today.toLocalDate()));
    assertThat("Expect activity added", todaysDayActivity.getLastActivity(deviceAnonId), notNullValue());
    assertThat("Expect matching start time", todaysDayActivity.getLastActivity(deviceAnonId).getStartTime(),
            equalTo(startTime.toLocalDateTime()));
    assertThat("Expect matching end time", todaysDayActivity.getLastActivity(deviceAnonId).getEndTime(),
            equalTo(endTime.toLocalDateTime()));

    // Verify that there is an activity cached
    verify(mockAnalysisEngineCacheService, atLeastOnce()).updateLastActivityForUser(eq(userAnonId),
            eq(deviceAnonId), eq(gamblingGoal.getId()), any());
}