Example usage for java.time ZonedDateTime plusMinutes

List of usage examples for java.time ZonedDateTime plusMinutes

Introduction

In this page you can find the example usage for java.time ZonedDateTime plusMinutes.

Prototype

public ZonedDateTime plusMinutes(long minutes) 

Source Link

Document

Returns a copy of this ZonedDateTime with the specified number of minutes added.

Usage

From source file:Main.java

public static void main(String[] args) {
    ZonedDateTime dateTime = ZonedDateTime.now();
    ZonedDateTime n = dateTime.plusMinutes(1234);
    System.out.println(n);/*  w ww.j  a  v a 2s  . c  om*/
}

From source file:io.stallion.jobs.JobInstanceDispatcher.java

@Override
public void run() {
    Log.info("Try to lock job for run {0}", definition.getName());
    boolean locked = JobStatusController.instance().lockJob(definition.getName());
    if (!locked) {
        Log.warn("Job is locked, skipping run command. {0}", definition.getName());
        return;//from  www.j  a  v a 2s  .  c  o m
    }
    if (JobStatusController.instance().isJobReadyToRun(definition, this.now)) {
        Log.warn("Job nextexecuteminutestamp time has not arrived. Not executing.");
        return;
    }
    Log.info("Job locked, execute now {0}", definition.getName());
    // Retrieve the status from the store to make sure we have the up-to-date version
    status = JobStatusController.instance().getOrCreateForName(definition.getName());
    status.setStartedAt(DateUtils.mils());
    JobStatusController.instance().save(status);

    try {
        // Run the job
        job.execute();
        status.setCompletedAt(DateUtils.mils());
        status.setFailedAt(0);
        status.setFailCount(0);
        status.setError("");
        ZonedDateTime nextRunAt = definition.getSchedule().nextAt(DateUtils.utcNow().plusMinutes(3));
        Long nextCompleteBy = nextRunAt.plusMinutes(definition.getAlertThresholdMinutes()).toInstant()
                .toEpochMilli();
        Log.info("Job Completed: {0} Threshold minutes: {1} next complete by: {2}", definition.getName(),
                definition.getAlertThresholdMinutes(), nextCompleteBy);
        status.setShouldSucceedBy(nextCompleteBy);
        JobStatusController.instance().save(status);
    } catch (Exception e) {
        Log.exception(e, "Error running job " + definition.getName());
        status.setFailCount(status.getFailCount() + 1);
        status.setError(e.toString() + ": " + e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
        status.setFailedAt(DateUtils.mils());
        if (HealthTracker.instance() != null) {
            HealthTracker.instance().logException(e);
        }
        JobStatusController.instance().save(status);
    } finally {
        JobStatusController.instance().resetLockAndNextRunAt(status, now.plusMinutes(1));
    }
}

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

@Test
public void addActivity_default_activityUpdateWithCorrectTimes() {
    ZonedDateTime t1 = now();
    ZonedDateTime t2 = t1.plusMinutes(2);

    service.addActivity(userAnonEntity, createPayload(t1, t2), GoalDto.createInstance(gamblingGoal),
            Optional.empty());//from  ww  w . j  a  va2s  .com

    List<WeekActivity> weekActivities = gamblingGoal.getWeekActivities();
    assertThat("One week activity present or created", weekActivities.size(), equalTo(1));
    List<DayActivity> dayActivities = weekActivities.get(0).getDayActivities();
    assertThat("One day activity present or created", dayActivities.size(), equalTo(1));
    List<Activity> activities = dayActivities.get(0).getActivities();
    assertThat("One activity present or created", activities.size(), equalTo(1));
    Activity activity = activities.get(0);
    assertThat("Expect right goal set to activity", activity.getActivityCategory(),
            equalTo(gamblingGoal.getActivityCategory()));
    assertThat(activity.getStartTimeAsZonedDateTime(), equalTo(t1));
    assertThat(activity.getEndTimeAsZonedDateTime(), equalTo(t2));
}

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

@Test
public void analyze_unorderedAppActivity_addedOrdered() {
    JUnitUtil.skipBefore("Skip shortly after midnignt", now(), 0, 10);
    String app = "Poker App";
    ZonedDateTime today = now().truncatedTo(ChronoUnit.DAYS);
    ZonedDateTime t1 = today.withHour(0).withMinute(0).withSecond(1);
    ZonedDateTime t2 = t1.plusSeconds(15);
    ZonedDateTime t3 = t2.plusSeconds(1);
    ZonedDateTime t4 = t3.plusMinutes(5);

    service.analyze(userAnonId, deviceAnonId, new AppActivitiesDto(now(), new AppActivitiesDto.Activity[] {
            new AppActivitiesDto.Activity(app, t3, t4), new AppActivitiesDto.Activity(app, t1, t2) }));

    ArgumentCaptor<ActivityPayload> activityPayloadCaptor = ArgumentCaptor.forClass(ActivityPayload.class);
    verify(mockActivityUpdater, times(2)).addActivity(any(), activityPayloadCaptor.capture(),
            eq(GoalDto.createInstance(gamblingGoal)), any());
    List<ActivityPayload> payloads = activityPayloadCaptor.getAllValues();
    assertThat(payloads.size(), equalTo(2));
    assertThat(payloads.get(0).startTime, equalTo(t1));
    assertThat(payloads.get(0).endTime, equalTo(t2));
    assertThat(payloads.get(1).startTime, equalTo(t3));
    assertThat(payloads.get(1).endTime, equalTo(t4));
    verify(mockActivityUpdater, never()).updateTimeExistingActivity(any(), any());
    verify(mockActivityUpdater, never()).updateTimeLastActivity(any(), any(), any());
}

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

@Test
public void analyze_appActivityCompletelyPrecedingLastCachedActivity_addActivity() {
    ZonedDateTime now = now();//from ww w .  j  av  a  2  s .  com
    JUnitUtil.skipBefore("Skip shortly after midnight", now, 0, 11);
    ZonedDateTime existingActivityStartTime = now.minusMinutes(4);
    ZonedDateTime existingActivityEndTime = existingActivityStartTime.plusMinutes(2);

    mockExistingActivity(gamblingGoal, existingActivityStartTime, existingActivityEndTime, "Poker App");

    ZonedDateTime startTime = now.minusMinutes(10);
    ZonedDateTime endTime = startTime.plusMinutes(5);

    service.analyze(userAnonId, deviceAnonId, createSingleAppActivity("Poker App", startTime, endTime));

    verify(mockActivityUpdater).addActivity(any(), any(), eq(GoalDto.createInstance(gamblingGoal)), any());
    verify(mockActivityUpdater, never()).updateTimeExistingActivity(any(), any());
    verify(mockActivityUpdater, never()).updateTimeLastActivity(any(), any(), any());
}

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

@Test
public void analyze_appActivityCompletelyPrecedingLastCachedActivityOverlappingExistingActivity_updateTimeExistingActivity() {
    ZonedDateTime now = now();//from   w  ww.jav  a2 s  . co  m
    JUnitUtil.skipBefore("Skip shortly after midnight", now, 0, 30);
    ZonedDateTime existingActivityTimeStartTime = now.minusMinutes(20);
    ZonedDateTime existingActivityTimeEndTime = existingActivityTimeStartTime.plusMinutes(10);

    Activity existingActivityOne = createActivity(existingActivityTimeStartTime, existingActivityTimeEndTime,
            "Poker App");
    Activity existingActivityTwo = createActivity(now, now, "Poker App");
    mockExistingActivities(gamblingGoal, existingActivityOne, existingActivityTwo);

    when(mockActivityRepository.findOverlappingOfSameApp(any(DayActivity.class), any(UUID.class),
            any(UUID.class), any(String.class), any(LocalDateTime.class), any(LocalDateTime.class)))
                    .thenAnswer(new Answer<List<Activity>>() {
                        @Override
                        public List<Activity> answer(InvocationOnMock invocation) throws Throwable {
                            return Arrays.asList(existingActivityOne);
                        }
                    });

    // Test an activity
    ZonedDateTime startTime = existingActivityTimeStartTime.plusMinutes(5);
    ZonedDateTime endTime = startTime.plusMinutes(7);

    service.analyze(userAnonId, deviceAnonId, createSingleAppActivity("Poker App", startTime, endTime));

    // Verify that a database lookup was done finding the existing DayActivity to update
    verify(mockDayActivityRepository).findOne(userAnonId, now.toLocalDate(), gamblingGoal.getId());
    verify(mockActivityUpdater).updateTimeExistingActivity(any(), any());
    verify(mockActivityUpdater, never()).addActivity(any(), any(), any(), any());
    verify(mockActivityUpdater, never()).updateTimeLastActivity(any(), any(), any());
}

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

@Test
public void analyze_appActivityPreviousDayPrecedingCachedDayActivity_addActivity() {
    ZonedDateTime now = now();//from   w  w  w . j ava2s .com
    ZonedDateTime yesterdayNoon = now.minusDays(1).withHour(12).withMinute(0).withSecond(0);

    mockExistingActivity(gamblingGoal, now);

    ZonedDateTime startTime = yesterdayNoon;
    ZonedDateTime endTime = yesterdayNoon.plusMinutes(10);

    service.analyze(userAnonId, deviceAnonId, createSingleAppActivity("Poker App", startTime, endTime));

    // Verify that a database lookup was done for yesterday
    verify(mockDayActivityRepository).findOne(userAnonId, yesterdayNoon.toLocalDate(), gamblingGoal.getId());

    verify(mockActivityUpdater).addActivity(any(), any(), eq(GoalDto.createInstance(gamblingGoal)), any());
    verify(mockActivityUpdater, never()).updateTimeExistingActivity(any(), any());
    verify(mockActivityUpdater, never()).updateTimeLastActivity(any(), any(), any());
}

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Intialize the database based on the passed in configuration object.
 * @param config//  ww  w  . ja v  a 2  s  .co  m
 */
public void initialize(DbConfig config) {
    try {
        dbImplementation = (DbImplementation) StallionClassLoader.loadClass(config.getImplementationClass())
                .newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    // Test out the connection. We do this directly, because if we test via the ComboPooledDataSource
    // exceptions will make the driver hang while retrying, and will also bury the underlying cause

    try {
        Driver driver = (Driver) StallionClassLoader.loadClass(config.getDriverClass()).newInstance();
        Properties props = new Properties();
        props.setProperty("user", config.getUsername());
        props.setProperty("password", config.getPassword());
        try (Connection conn = driver.connect(config.getUrl(), props)) {
            Statement st = conn.createStatement();
            ResultSet results = st.executeQuery("SELECT 1 AS oneCol");
            results.next();
            Long i = results.getLong("oneCol");
            assert i == 1L;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    /*
    try {
    try (Connection conn = cpds.getConnection()) {
        Statement st = conn.createStatement();
        ResultSet results = st.executeQuery("SELECT 1");
        Long i = results.getLong(0);
        assert i == 1L;
    }
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
            
    */
    try {
        cpds.setDriverClass(config.getDriverClass()); //loads the jdbc driver
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }

    String url = config.getUrl();
    if (!url.contains("?")) {
        url += "?";
    }
    // Assume the database server is in UTC
    if (!url.contains("&useLegacyDatetimeCode=")) {
        url += "&useLegacyDatetimeCode=false";
    }
    if (!url.contains("&serverTimezone=")) {
        url += "&serverTimezone=UTC";
    }
    //&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

    cpds.setJdbcUrl(url);
    cpds.setUser(config.getUsername());
    cpds.setPassword(config.getPassword());

    if (url.contains("utf8mb4_unicode_ci")) {
        cpds.setConnectionCustomizerClassName("io.stallion.dataAccess.db.mysql.Utf8InitCustomizer");
    }

    cpds.setAcquireRetryAttempts(10);
    cpds.setAcquireRetryDelay(200);
    //cpds.setCheckoutTimeout(1);
    // the settings below are optional -- c3p0 can work with defaults
    cpds.setMinPoolSize(5);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);
    cpds.setIdleConnectionTestPeriod(5000);
    cpds.setTestConnectionOnCheckin(true);

    this.dataSource = cpds;

    // Make sure the database server time is UTC and in sync with the local server time
    // or else stop execution to prevent nasty and insiduious errors.
    //Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    ZonedDateTime now = utcNow();
    ZonedDateTime dbTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("UTC"));

    //LocalDateTime now = utcNow().toLocalDateTime();
    ZonedDateTime max = now.plusMinutes(2);
    ZonedDateTime min = now.minusMinutes(2);

    //LocalDateTime dbTime = date.toLocalDateTime();
    if (dbTime.isAfter(max) || dbTime.isBefore(min)) {
        throw new ConfigException(
                "The database CURRENT_TIMESTAMP() is mismatched with the server time. Db time is " + dbTime
                        + ". Server time is " + now
                        + ". Make sure the database server is in UTC and that all your servers clocks are matched. ");
    }

    // Todo: why not lazy load converters???
    registerConverter(new JsonMapConverter());
    registerConverter(new JsonSetConverter());
    registerConverter(new JsonObjectConverter());
    registerConverter(new JsonListConverter());

    this.tickets = dbImplementation.initTicketsService(this);

}

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

@Test
public void addActivity_durationLessThanOneMinute_minimumDurationOneMinute() {
    ZonedDateTime t1 = now();
    ZonedDateTime t2 = t1.plusSeconds(59);

    service.addActivity(userAnonEntity, createPayload(t1, t2), GoalDto.createInstance(gamblingGoal),
            Optional.empty());//from  w w w .ja  v a  2  s .  c o m

    List<WeekActivity> weekActivities = gamblingGoal.getWeekActivities();
    assertThat("One week activity present or created", weekActivities.size(), equalTo(1));
    List<DayActivity> dayActivities = weekActivities.get(0).getDayActivities();
    assertThat("One day activity present or created", dayActivities.size(), equalTo(1));
    List<Activity> activities = dayActivities.get(0).getActivities();
    assertThat("One activity present or created", activities.size(), equalTo(1));
    Activity activity = activities.get(0);
    assertThat("Expect right goal set to activity", activity.getActivityCategory(),
            equalTo(gamblingGoal.getActivityCategory()));
    assertThat(activity.getStartTimeAsZonedDateTime(), equalTo(t1));
    assertThat(activity.getEndTimeAsZonedDateTime(), equalTo(t1.plusMinutes(1)));
}

From source file:org.eclipse.hawkbit.repository.test.util.AbstractIntegrationTest.java

/**
 * Gets a valid cron expression describing a schedule with a single
 * maintenance window, starting specified number of minutes after current
 * time./* www.  ja va2 s  .  co  m*/
 *
 * @param minutesToAdd
 *            is the number of minutes after the current time
 *
 * @return {@link String} containing a valid cron expression.
 */
protected static String getTestSchedule(final int minutesToAdd) {
    ZonedDateTime currentTime = ZonedDateTime.now();
    currentTime = currentTime.plusMinutes(minutesToAdd);
    return String.format("%d %d %d %d %d ? %d", currentTime.getSecond(), currentTime.getMinute(),
            currentTime.getHour(), currentTime.getDayOfMonth(), currentTime.getMonthValue(),
            currentTime.getYear());
}