Example usage for java.time ZonedDateTime minusMinutes

List of usage examples for java.time ZonedDateTime minusMinutes

Introduction

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

Prototype

public ZonedDateTime minusMinutes(long minutes) 

Source Link

Document

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

Usage

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

@Test
public void analyze_appActivityCompletelyPrecedingLastCachedActivityOverlappingExistingActivity_updateTimeExistingActivity() {
    ZonedDateTime now = now();
    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);
                        }/*from  ww  w.  j  ava2s. c o m*/
                    });

    // 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_appActivityCompletelyPrecedingLastCachedActivityOverlappingMultipleExistingActivities_updateTimeExistingActivityOnFirstActivityAndLogsWarning() {
    ZonedDateTime now = now();
    JUnitUtil.skipBefore("Skip shortly after midnight", now, 0, 10);
    DayActivity existingDayActivity = mockExistingActivities(gamblingGoal,
            createActivity(now.minusMinutes(10), now.minusMinutes(8), "Lotto App"),
            createActivity(now.minusMinutes(7), now.minusMinutes(5), "Lotto App"),
            createActivity(now, now, "Lotto App"));
    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 existingDayActivity.getActivities().stream().collect(Collectors.toList());
                        }/*from  w ww  .  j  a va  2  s .c om*/
                    });
    String expectedWarnMessage = MessageFormat.format(
            "Multiple overlapping app activities of ''Lotto App'' found. The payload has start time {0} and end time {1}. The day activity ID is {2} and the activity category ID is {3}. The overlapping activities are: {4}, {5}, {6}.",
            now.minusMinutes(9).toLocalDateTime(), now.minusMinutes(2).toLocalDateTime(),
            existingDayActivity.getId(), gamblingGoal.getActivityCategory().getId(),
            existingDayActivity.getActivities().get(0), existingDayActivity.getActivities().get(1),
            existingDayActivity.getActivities().get(2));

    service.analyze(userAnonId, deviceAnonId,
            createSingleAppActivity("Lotto App", now.minusMinutes(9), now.minusMinutes(2)));

    verify(mockActivityUpdater).updateTimeExistingActivity(any(), any());
    verify(mockActivityUpdater, never()).addActivity(any(), any(), any(), any());
    verify(mockActivityUpdater, never()).updateTimeLastActivity(any(), any(), any());

    ArgumentCaptor<ILoggingEvent> logEventCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    verify(mockLogAppender).doAppend(logEventCaptor.capture());
    assertThat(logEventCaptor.getValue().getLevel(), equalTo(Level.WARN));
    assertThat(logEventCaptor.getValue().getFormattedMessage(), equalTo(expectedWarnMessage));
}

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

@Test
public void analyze_networkActivityCompletelyPrecedingLastCachedActivityOverlappingMultipleExistingActivities_updateTimeExistingActivityOnFirstActivityAndLogsWarning() {
    ZonedDateTime now = now();
    JUnitUtil.skipBefore("Skip shortly after midnight", now, 0, 11);
    DayActivity existingDayActivity = mockExistingActivities(gamblingGoal,
            createActivity(now.minusMinutes(10), now.minusMinutes(8)),
            createActivity(now.minusMinutes(1), now));
    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 existingDayActivity.getActivities().stream().collect(Collectors.toList());
                        }/*  w w  w.j  av a2  s.co m*/
                    });
    String expectedWarnMessage = MessageFormat.format(
            "Multiple overlapping network activities found. The payload has start time {0} and end time {1}. The day activity ID is {2} and the activity category ID is {3}. The overlapping activities are: {4}, {5}.",
            now.minusMinutes(9).toLocalDateTime(), now.minusMinutes(9).toLocalDateTime(),
            existingDayActivity.getId(), gamblingGoal.getActivityCategory().getId(),
            existingDayActivity.getActivities().get(0), existingDayActivity.getActivities().get(1));

    service.analyze(userAnonId, createNetworkActivityForCategories(now.minusMinutes(9), "poker"));

    verify(mockActivityUpdater).updateTimeExistingActivity(any(), any());
    verify(mockActivityUpdater, never()).addActivity(any(), any(), any(), any());
    verify(mockActivityUpdater, never()).updateTimeLastActivity(any(), any(), any());

    List<Activity> activities = existingDayActivity.getActivities();
    assertThat(activities.size(), equalTo(2));
    assertThat(activities.get(0).getApp(), equalTo(Optional.empty()));
    assertThat(activities.get(0).getStartTimeAsZonedDateTime(), equalTo(now.minusMinutes(10)));
    assertThat(activities.get(0).getEndTimeAsZonedDateTime(), equalTo(now.minusMinutes(8)));
    assertThat(activities.get(1).getApp(), equalTo(Optional.empty()));
    assertThat(activities.get(1).getStartTimeAsZonedDateTime(), equalTo(now.minusMinutes(1)));
    assertThat(activities.get(1).getEndTimeAsZonedDateTime(), equalTo(now));

    ArgumentCaptor<ILoggingEvent> logEventCaptor = ArgumentCaptor.forClass(ILoggingEvent.class);
    verify(mockLogAppender).doAppend(logEventCaptor.capture());
    assertThat(logEventCaptor.getValue().getLevel(), equalTo(Level.WARN));
    assertThat(logEventCaptor.getValue().getFormattedMessage(), equalTo(expectedWarnMessage));
}

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

@Test
public void analyze_appActivityAfterNetworkActivityWithinConflictInterval_addActivity() {
    ZonedDateTime now = now();
    JUnitUtil.skipBefore("Skip shortly after midnight", now, 0, 5);
    mockExistingActivity(gamblingGoal, now);

    service.analyze(userAnonId, deviceAnonId,
            createSingleAppActivity("Lotto App", now.minusMinutes(4), now.minusMinutes(2)));

    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/*from  w w w. ja  v  a2  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);

}