Java Code Examples for java.time.ZonedDateTime#plusHours()

The following examples show how to use java.time.ZonedDateTime#plusHours() . 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: TimeFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void overnight() {
    final TimeFilter filter = new TimeFilter(LocalTime.of(23,0), LocalTime.of(1,0),
            ZoneId.of("America/Los_Angeles"), null, null, LocalDate.of(2020, 3, 10));
    filter.start();
    assertTrue(filter.isStarted());
    ZonedDateTime date = ZonedDateTime.of(2020, 3, 10, 23, 30, 30, 0, ZoneId.of("America/Los_Angeles")).withEarlierOffsetAtOverlap();
    CLOCKTIME = date.toInstant().toEpochMilli();
    LogEvent event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is not within range: " + filter.toString(), Filter.Result.NEUTRAL, filter.filter(event));
    date = date.plusHours(1);
    CLOCKTIME = date.toInstant().toEpochMilli();
    event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is not within range: " + filter.toString(), Filter.Result.NEUTRAL, filter.filter(event));
    date = date.plusHours(1);
    CLOCKTIME = date.toInstant().toEpochMilli();
    event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is within range: " + filter.toString(), Filter.Result.DENY, filter.filter(event));
    date = date.plusDays(1).withHour(0);
    CLOCKTIME = date.toInstant().toEpochMilli();
    event = Log4jLogEvent.newBuilder().setTimeMillis(CLOCKTIME).build();
    assertSame("Time " + CLOCKTIME + " is not within range: " + filter.toString(), Filter.Result.NEUTRAL, filter.filter(event));
}
 
Example 2
Source File: ExecutionTimeCron4jIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
/**
 * Issue #37: nextExecution not calculating correct time.
 */
@Test
public void testEvery2Hours() {
    ZonedDateTime lastRun = ZonedDateTime.now();
    final ExecutionTime executionTime = ExecutionTime.forCron(cron4jCronParser.parse(EVERY_2_HOURS));

    // iterate through the next 36 hours so we roll over the to the next day
    // and make sure the next run time is always in the future from the prior run time
    for (int i = 0; i < 36; i++) {

        final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(lastRun);
        if (nextExecution.isPresent()) {
            final ZonedDateTime nextRun = nextExecution.get();
            log.info(LOG_LAST_RUN, lastRun);
            log.info(LOG_NEXT_RUN, nextRun);

            assertTrue(String.format("Hour is %s", nextRun.getHour()), nextRun.getHour() % 2 == 0);
            assertTrue(String.format("Last run is before next one: %s", lastRun.isBefore(nextRun)), lastRun.isBefore(nextRun));
            lastRun = lastRun.plusHours(1);
        } else {
            fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
        }
    }
}
 
Example 3
Source File: ExecutionTimeCron4jIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testQuick() {
    ZonedDateTime lastRun = ZonedDateTime.of(2017, 3, 12, 0, 55, 50, 630, ZoneId.of("America/Los_Angeles"));
    final ExecutionTime executionTime = ExecutionTime.forCron(cron4jCronParser.parse(EVERY_2_HOURS));

    // iterate through the next 36 hours so we roll over the to the next day
    // and make sure the next run time is always in the future from the prior run time
    for (int i = 0; i < 1; i++) {

        final Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(lastRun);
        if (nextExecution.isPresent()) {
            final ZonedDateTime nextRun = nextExecution.get();
            log.info(LOG_LAST_RUN, lastRun);
            log.info(LOG_NEXT_RUN, nextRun);

            assertTrue(String.format("Hour is %s", nextRun.getHour()), nextRun.getHour() % 2 == 0);
            assertTrue(String.format("Last run is before next one: %s", lastRun.isBefore(nextRun)), lastRun.isBefore(nextRun));
            lastRun = lastRun.plusHours(1);
        } else {
            fail(NEXT_EXECUTION_NOT_PRESENT_ERROR);
        }
    }
}
 
Example 4
Source File: CronExpressionTest.java    From cron with Apache License 2.0 6 votes vote down vote up
@Test
public void check_hour_shall_run_25_times_in_DST_change_to_wintertime() throws Exception {
    CronExpression cron = new CronExpression("0 1 * * * *");
    ZonedDateTime start = ZonedDateTime.of(2011, 10, 30, 0, 0, 0, 0, zoneId);
    ZonedDateTime slutt = start.plusDays(1);
    ZonedDateTime tid = start;

    // throws: Unsupported unit: Seconds
    // assertEquals(25, Duration.between(start.toLocalDate(), slutt.toLocalDate()).toHours());

    int count = 0;
    ZonedDateTime lastTime = tid;
    while (tid.isBefore(slutt)) {
        ZonedDateTime nextTime = cron.nextTimeAfter(tid);
        assertTrue(nextTime.isAfter(lastTime));
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertEquals(25, count);
}
 
Example 5
Source File: CronExpressionTest.java    From cron with Apache License 2.0 6 votes vote down vote up
@Test
public void check_hour_shall_run_23_times_in_DST_change_to_summertime() throws Exception {
    CronExpression cron = new CronExpression("0 0 * * * *");
    ZonedDateTime start = ZonedDateTime.of(2011, 03, 27, 1, 0, 0, 0, zoneId);
    ZonedDateTime slutt = start.plusDays(1);
    ZonedDateTime tid = start;

    // throws: Unsupported unit: Seconds
    // assertEquals(23, Duration.between(start.toLocalDate(), slutt.toLocalDate()).toHours());

    int count = 0;
    ZonedDateTime lastTime = tid;
    while (tid.isBefore(slutt)) {
        ZonedDateTime nextTime = cron.nextTimeAfter(tid);
        assertTrue(nextTime.isAfter(lastTime));
        lastTime = nextTime;
        tid = tid.plusHours(1);
        count++;
    }
    assertEquals(23, count);
}
 
Example 6
Source File: InsightsUtils.java    From Insights with Apache License 2.0 4 votes vote down vote up
public static Long addTimeInHours(long inputTime, long hours) {
	ZonedDateTime fromInput = ZonedDateTime.ofInstant(Instant.ofEpochSecond(inputTime), zoneId);
	fromInput = fromInput.plusHours(hours);
	return fromInput.toEpochSecond();
}
 
Example 7
Source File: TemporalRoundingTest.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testDST()
{
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss (z, 'UTC' Z)");
    final ZoneId zone = ZoneId.of("America/New_York");

    // Switch into DST
    ZonedDateTime start = ZonedDateTime.of(2014, 3, 8, 23, 0, 0, 0, zone);
    ZonedDateTime time = start;

    assertThat(formatter.format(time), equalTo("2014-03-08 23:00:00 (EST, UTC -0500)"));
    ZonedDateTime rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-03-09 00:00:00 (EST, UTC -0500)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-03-09 00:00:00 (EST, UTC -0500)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-03-09 00:00:00 (EST, UTC -0500)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-03-09 01:00:00 (EST, UTC -0500)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-03-09 03:00:00 (EDT, UTC -0400)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-03-09 03:00:00 (EDT, UTC -0400)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-03-09 04:00:00 (EDT, UTC -0400)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-03-09 04:00:00 (EDT, UTC -0400)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-03-09 04:00:00 (EDT, UTC -0400)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-03-09 05:00:00 (EDT, UTC -0400)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-03-09 06:00:00 (EDT, UTC -0400)"));

    // Leave DST
    start = ZonedDateTime.of(2014, 11, 1, 23, 0, 0, 0, zone);
    time = start;

    assertThat(formatter.format(time), equalTo("2014-11-01 23:00:00 (EDT, UTC -0400)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-11-02 00:00:00 (EDT, UTC -0400)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-11-02 00:00:00 (EDT, UTC -0400)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-11-02 00:00:00 (EDT, UTC -0400)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-11-02 01:00:00 (EDT, UTC -0400)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-11-02 01:00:00 (EST, UTC -0500)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-11-02 01:00:00 (EST, UTC -0500)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-11-02 01:00:00 (EST, UTC -0500)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-11-02 02:00:00 (EST, UTC -0500)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-11-02 02:00:00 (EST, UTC -0500)"));

    time = time.plusHours(1);
    assertThat(formatter.format(time), equalTo("2014-11-02 03:00:00 (EST, UTC -0500)"));
    rd = time.with(zonedDateTimerRoundedToNextOrSame(ChronoUnit.HOURS, 2));
    assertThat(formatter.format(rd), equalTo("2014-11-02 04:00:00 (EST, UTC -0500)"));
}
 
Example 8
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test that no staging jobs are scheduled when scheduling action on a
 * traditional client
 *
 * @throws Exception when Taskomatic service is down
 */
public void testNoStagingJobsWhenTraditionalClient() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);

    UserFactory.save(user);
    Server s1 = ServerTestUtils.createTestSystem(user);
    s1.setOrg(user.getOrg());
    Server s2 = ServerTestUtils.createTestSystem(user);
    s2.setOrg(s2.getOrg());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "0");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "1");

    final ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    final ZonedDateTime executionTime = now.plusHours(24);

    Action action = ActionManager.createAction(user, ActionFactory.TYPE_PACKAGES_UPDATE,
            "test action", Date.from(now.toInstant()));
    ActionManager.scheduleForExecution(action,
            new HashSet<Long>(Arrays.asList(s1.getId(), s2.getId())));
    ActionFactory.save(action);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(s1.getId()),
                with(any(Date.class)));
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(s2.getId()),
                with(any(Date.class)));
    } });
    Map<Long, Map<Long, ZonedDateTime>> actionsDataMap =
            MinionActionManager.scheduleStagingJobsForMinions(Collections.singletonList(action), user);
    List<ZonedDateTime> scheduleTimes =
            actionsDataMap.values().stream().map(s -> new ArrayList<>(s.values()))
                    .flatMap(List::stream).collect(Collectors.toList());
    assertEquals(0,
            scheduleTimes.stream()
                .filter(scheduleTime -> scheduleTime.isAfter(now))
                .filter(scheduleTime -> scheduleTime.isBefore(executionTime))
                .collect(Collectors.toList()).size());
}
 
Example 9
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test that no staging jobs are scheduled when staging
 * window is zero hours length
 *
 * @throws Exception when Taskomatic service is down
 */
public void testNoStagingJobsWhenWindowIsZeroLength() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);

    UserFactory.save(user);
    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setOrg(user.getOrg());
    MinionServer minion2 = MinionServerFactoryTest.createTestMinionServer(user);
    minion2.setOrg(user.getOrg());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "0");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "1");

    final ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    final ZonedDateTime executionTime = now.plusHours(24);

    Action action = ActionManager.createAction(user, ActionFactory.TYPE_PACKAGES_UPDATE,
            "test action", Date.from(now.toInstant()));
    ActionManager.scheduleForExecution(action,
            new HashSet<Long>(Arrays.asList(minion1.getId(), minion2.getId())));
    ActionFactory.save(action);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion1.getId()),
                with(any(Date.class)));
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion2.getId()),
                with(any(Date.class)));
    } });

    Map<Long, Map<Long, ZonedDateTime>> actionsDataMap =
            MinionActionManager.scheduleStagingJobsForMinions(Collections.singletonList(action), user);
    List<ZonedDateTime> scheduleTimes =
            actionsDataMap.values().stream().map(s -> new ArrayList<>(s.values()))
                    .flatMap(List::stream).collect(Collectors.toList());
    assertEquals(0,
            scheduleTimes.stream()
                .filter(scheduleTime -> scheduleTime.isAfter(now))
                .filter(scheduleTime -> scheduleTime.isBefore(executionTime))
                .collect(Collectors.toList()).size());
}
 
Example 10
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test that no staging jobs are scheduled when the staging
 * window has zero hours in advance to start
 *
 * @throws Exception when Taskomatic service is down
 */
public void testNoStagingJobsWhenWindowIsZeroAdvance() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);

    UserFactory.save(user);
    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setOrg(user.getOrg());
    MinionServer minion2 = MinionServerFactoryTest.createTestMinionServer(user);
    minion2.setOrg(user.getOrg());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "1");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "0");

    final ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    final ZonedDateTime executionTime = now.plusHours(24);

    Action action = ActionManager.createAction(user, ActionFactory.TYPE_PACKAGES_UPDATE,
            "test action", Date.from(now.toInstant()));
    ActionManager.scheduleForExecution(action,
            new HashSet<Long>(Arrays.asList(minion1.getId(), minion2.getId())));
    ActionFactory.save(action);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion1.getId()),
                with(any(Date.class)));
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion2.getId()),
                with(any(Date.class)));
    } });

    Map<Long, Map<Long, ZonedDateTime>> actionsDataMap =
            MinionActionManager.scheduleStagingJobsForMinions(Collections.singletonList(action), user);
    List<ZonedDateTime> scheduleTimes =
            actionsDataMap.values().stream().map(s -> new ArrayList<>(s.values()))
                    .flatMap(List::stream).collect(Collectors.toList());
    assertEquals(0,
            scheduleTimes.stream()
                .filter(scheduleTime -> scheduleTime.isAfter(now))
                .filter(scheduleTime -> scheduleTime.isBefore(executionTime))
                .collect(Collectors.toList()).size());
}
 
Example 11
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test that no staging jobs are scheduled when config parameters
 * are scheduled to design a staging window in which start equals
 * end
 *
 * @throws Exception when Taskomatic service is down
 */
public void testNoStagingJobsWhenWindowStartEqualsFinish() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);

    UserFactory.save(user);
    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setOrg(user.getOrg());
    MinionServer minion2 = MinionServerFactoryTest.createTestMinionServer(user);
    minion2.setOrg(user.getOrg());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "0");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "0");

    final ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    final ZonedDateTime executionTime = now.plusHours(24);

    Action action = ActionManager.createAction(user, ActionFactory.TYPE_PACKAGES_UPDATE,
            "test action", Date.from(now.toInstant()));
    ActionManager.scheduleForExecution(action,
            new HashSet<Long>(Arrays.asList(minion1.getId(), minion2.getId())));
    ActionFactory.save(action);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion1.getId()),
                with(any(Date.class)));
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion2.getId()),
                with(any(Date.class)));
    } });

    Map<Long, Map<Long, ZonedDateTime>> actionsDataMap =
            MinionActionManager.scheduleStagingJobsForMinions(Collections.singletonList(action), user);
    List<ZonedDateTime> scheduleTimes =
            actionsDataMap.values().stream().map(s -> new ArrayList<>(s.values()))
                    .flatMap(List::stream).collect(Collectors.toList());

    assertEquals(0,
            scheduleTimes.stream()
                .filter(scheduleTime -> scheduleTime.isAfter(now))
                .filter(scheduleTime -> scheduleTime.isBefore(executionTime))
                .collect(Collectors.toList()).size());
}
 
Example 12
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test schedule time of staging jobs when staging window is already
 * passed
 *
 * @throws Exception when Taskomatic service is down
 */
public void testStagingJobsScheduleTimeOutsideWindow() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);

    UserFactory.save(user);
    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setOrg(user.getOrg());
    MinionServer minion2 = MinionServerFactoryTest.createTestMinionServer(user);
    minion2.setOrg(user.getOrg());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "1");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "48");

    final ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    final ZonedDateTime executionTime = now.plusHours(24);

    Action action = ActionManager.createAction(user, ActionFactory.TYPE_PACKAGES_UPDATE,
            "test action", Date.from(executionTime.toInstant()));
    ActionManager.scheduleForExecution(action,
            new HashSet<Long>(Arrays.asList(minion1.getId(), minion2.getId())));
    ActionFactory.save(action);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion1.getId()),
                with(any(Date.class)));
        never(taskomaticMock).scheduleStagingJob(with(action.getId()),
                with(minion2.getId()),
                with(any(Date.class)));
    } });
    Map<Long, Map<Long, ZonedDateTime>> actionsDataMap =
            MinionActionManager.scheduleStagingJobsForMinions(Collections.singletonList(action), user);
    List<ZonedDateTime> scheduleTimes =
            actionsDataMap.values().stream().map(s -> new ArrayList<>(s.values()))
                    .flatMap(List::stream).collect(Collectors.toList());

    assertEquals(0,
            scheduleTimes.stream()
                .filter(scheduleTime -> scheduleTime.isAfter(now))
                .filter(scheduleTime -> scheduleTime.isBefore(executionTime))
                .collect(Collectors.toList()).size());
}
 
Example 13
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test patch/errata install without staging
 * @throws Exception when Taskomatic service is down
 */
public void testPatchInstallWithoutStaging() throws Exception {
    Channel channel1 = ChannelFactoryTest.createTestChannel(user);
    final String updateTag = "SLE-SERVER";
    channel1.setUpdateTag(updateTag);

    Server server1 = MinionServerFactoryTest.createTestMinionServer(user);
    server1.setOrg(user.getOrg());

    // server 1 has an errata for package1 available
    com.redhat.rhn.domain.rhnpackage.Package package1 =
            createTestPackage(user, channel1, "noarch");
    createTestInstalledPackage(package1, server1);

    Errata e1 = ErrataFactoryTest.createTestPublishedErrata(user.getId());
    channel1.addErrata(e1);
    e1.setAdvisoryName("SUSE-2016-1234");
    e1.getPackages().add(createTestPackage(user, channel1, "noarch"));

    ChannelFactory.save(channel1);
    ErrataCacheManager.insertNeededErrataCache(
            server1.getId(), e1.getId(), package1.getId());

    List<Long> errataIds = new ArrayList<Long>();
    errataIds.add(e1.getId());

    List<Long> serverIds = new ArrayList<Long>();
    serverIds.add(server1.getId());

    user.getOrg().getOrgConfig().setStagingContentEnabled(false);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "1");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "48");

    ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    ZonedDateTime scheduledActionTime = now.plusHours(24);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    ErrataManager.setTaskomaticApi(taskomaticMock);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        exactly(1).of(taskomaticMock)
                .scheduleMinionActionExecutions(with(any(List.class)), with(any(Boolean.class)));
        never(taskomaticMock).scheduleStagingJob(with(any(Long.class)),
                with(server1.getId()),
                with(any(Date.class)));
    } });
    HibernateFactory.getSession().flush();
    ErrataManager.applyErrata(user, errataIds,
            Date.from(scheduledActionTime.toInstant()), serverIds);
}
 
Example 14
Source File: TopicPartitionRecordGrouperTest.java    From aiven-kafka-connect-gcs with GNU Affero General Public License v3.0 4 votes vote down vote up
@Test
void rotateKeysHourly() {
    final Template filenameTemplate =
        Template.of(
            "{{topic}}-"
                + "{{partition}}-"
                + "{{start_offset}}-"
                + "{{timestamp:unit=YYYY}}"
                + "{{timestamp:unit=MM}}"
                + "{{timestamp:unit=dd}}"
                + "{{timestamp:unit=HH}}"
        );
    final TimestampSource timestampSourceMock = mock(TimestampSource.class);

    final ZonedDateTime firstHourTime = ZonedDateTime.now();
    final ZonedDateTime secondHourTime = firstHourTime.plusHours(1);
    final String firstHourTs =
        firstHourTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("MM"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("dd"))
            + firstHourTime.format(DateTimeFormatter.ofPattern("HH"));
    final String secondHourTs =
        secondHourTime.format(DateTimeFormatter.ofPattern("YYYY"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("MM"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("dd"))
            + secondHourTime.format(DateTimeFormatter.ofPattern("HH"));

    when(timestampSourceMock.time()).thenReturn(firstHourTime);
    final TopicPartitionRecordGrouper grouper =
        new TopicPartitionRecordGrouper(
            filenameTemplate,
            null,
            timestampSourceMock
        );

    grouper.put(T0P0R1);
    grouper.put(T0P0R2);
    grouper.put(T0P0R3);

    when(timestampSourceMock.time()).thenReturn(secondHourTime);

    grouper.put(T0P0R4);
    grouper.put(T0P0R5);

    final Map<String, List<SinkRecord>> records = grouper.records();

    assertEquals(2, records.size());

    assertThat(
        records.keySet(),
        containsInAnyOrder(
            "topic0-0-1-" + firstHourTs,
            "topic0-0-1-" + secondHourTs
        )
    );
    assertThat(
        records.get("topic0-0-1-" + firstHourTs),
        contains(T0P0R1, T0P0R2, T0P0R3)
    );
    assertThat(
        records.get("topic0-0-1-" + secondHourTs),
        contains(T0P0R4, T0P0R5)
    );
}
 
Example 15
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test patch/errata install with staging before entering the staging window
 * @throws Exception when Taskomatic service is down
 */
public void testPatchInstallWithStagingBeforeWindow() throws Exception {
    Channel channel1 = ChannelFactoryTest.createTestChannel(user);
    final String updateTag = "SLE-SERVER";
    channel1.setUpdateTag(updateTag);

    Server server1 = MinionServerFactoryTest.createTestMinionServer(user);
    server1.setOrg(user.getOrg());
    server1.addChannel(channel1);

    // server 1 has an errata for package1 available
    com.redhat.rhn.domain.rhnpackage.Package package1 =
            createTestPackage(user, channel1, "noarch");
    createTestInstalledPackage(package1, server1);

    Errata e1 = ErrataFactoryTest.createTestPublishedErrata(user.getId());
    channel1.addErrata(e1);
    e1.setAdvisoryName("SUSE-2016-1234");
    e1.getPackages().add(createTestPackage(user, channel1, "noarch"));

    ChannelFactory.save(channel1);
    ErrataCacheManager.insertNeededErrataCache(
            server1.getId(), e1.getId(), package1.getId());

    List<Long> errataIds = new ArrayList<Long>();
    errataIds.add(e1.getId());

    List<Long> serverIds = new ArrayList<Long>();
    serverIds.add(server1.getId());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "2");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "1");

    ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    ZonedDateTime scheduledActionTime = now.plusHours(24);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    ErrataManager.setTaskomaticApi(taskomaticMock);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        Matcher<Map<Long, ZonedDateTime>> minionMatcher =
                AllOf.allOf(IsMapContaining.hasKey(server1.getId()));
        Matcher<Map<Long, Map<Long, ZonedDateTime>>> actionsMatcher =
                AllOf.allOf(IsMapContaining.hasEntry(any(Long.class), minionMatcher));
        exactly(1).of(taskomaticMock)
                .scheduleMinionActionExecutions(with(any(List.class)),with(any(Boolean.class)));
        exactly(1).of(taskomaticMock).scheduleStagingJobs(with(actionsMatcher));
    } });
    HibernateFactory.getSession().flush();
    ErrataManager.applyErrata(user, errataIds,
            Date.from(scheduledActionTime.toInstant()), serverIds);
}
 
Example 16
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test patch/errata install with staging when inside the staging window
 * @throws Exception when Taskomatic service is down
 */
public void testPatchInstallWithStagingInsideWindow() throws Exception {
    Channel channel1 = ChannelFactoryTest.createTestChannel(user);
    final String updateTag = "SLE-SERVER";
    channel1.setUpdateTag(updateTag);

    Server server1 = MinionServerFactoryTest.createTestMinionServer(user);
    server1.setOrg(user.getOrg());
    server1.addChannel(channel1);

    // server 1 has an errata for package1 available
    com.redhat.rhn.domain.rhnpackage.Package package1 =
            createTestPackage(user, channel1, "noarch");
    createTestInstalledPackage(package1, server1);

    Errata e1 = ErrataFactoryTest.createTestPublishedErrata(user.getId());
    channel1.addErrata(e1);
    e1.setAdvisoryName("SUSE-2016-1234");
    e1.getPackages().add(createTestPackage(user, channel1, "noarch"));

    ChannelFactory.save(channel1);

    ErrataCacheManager.insertNeededErrataCache(
            server1.getId(), e1.getId(), package1.getId());

    List<Long> errataIds = new ArrayList<Long>();
    errataIds.add(e1.getId());

    List<Long> serverIds = new ArrayList<Long>();
    serverIds.add(server1.getId());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "48");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "48");

    ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    ZonedDateTime scheduledActionTime = now.plusHours(24);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    ErrataManager.setTaskomaticApi(taskomaticMock);
    MinionActionManager.setTaskomaticApi(taskomaticMock);
    context().checking(new Expectations() { {
        Matcher<Map<Long, ZonedDateTime>> minionMatcher =
                AllOf.allOf(IsMapContaining.hasKey(server1.getId()));
        Matcher<Map<Long, Map<Long, ZonedDateTime>>> actionsMatcher =
                AllOf.allOf(IsMapContaining.hasEntry(any(Long.class), minionMatcher));
        exactly(1).of(taskomaticMock)
                .scheduleMinionActionExecutions(with(any(List.class)),with(any(Boolean.class)));
        exactly(1).of(taskomaticMock).scheduleStagingJobs(with(actionsMatcher));
    } });
    HibernateFactory.getSession().flush();
    ErrataManager.applyErrata(user, errataIds,
            Date.from(scheduledActionTime.toInstant()), serverIds);
}
 
Example 17
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test Action chain package install with staging when inside the staging window
 * @throws Exception when Taskomatic service is down
 */
public void testChainPackageInstallWithStagingInsideWindow() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);

    UserFactory.save(user);
    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setOrg(user.getOrg());
    MinionServer minion2 = MinionServerFactoryTest.createTestMinionServer(user);
    minion2.setOrg(user.getOrg());

    Package pkg1 = PackageTest.createTestPackage(user.getOrg());
    List packageIds = new LinkedList();
    packageIds.add(pkg1.getId().intValue());

    Package pkg2 = PackageTest.createTestPackage(user.getOrg());
    packageIds.add(pkg2.getId().intValue());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "0.5");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "1");

    ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    ZonedDateTime scheduledActionTime = now.plusHours(1);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    ActionChainManager.setTaskomaticApi(taskomaticMock);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    context().checking(new Expectations() { {
        Matcher<Map<Long, ZonedDateTime>> minionMatcher =
                AllOf.allOf(IsMapContaining.hasKey(minion1.getId()), IsMapContaining.hasKey(minion2.getId()));
        Matcher<Map<Long, Map<Long, ZonedDateTime>>> actionsMatcher =
                AllOf.allOf(IsMapContaining.hasEntry(any(Long.class), minionMatcher));
        exactly(1).of(taskomaticMock)
                .scheduleActionExecution(with(any(Action.class)));
        exactly(1).of(taskomaticMock).scheduleStagingJobs(with(actionsMatcher));
   } });

    ActionChainManager.schedulePackageInstalls(user,
            Arrays.asList(minion1.getId(), minion2.getId()), null,
            Date.from(scheduledActionTime.toInstant()), null);
}
 
Example 18
Source File: AddHoursToDate.java    From tutorials with MIT License 4 votes vote down vote up
public ZonedDateTime addHoursToZonedDateTime(ZonedDateTime zonedDateTime, int hours) {
    return zonedDateTime.plusHours(hours);
}
 
Example 19
Source File: ConsolePane.java    From dm3270 with Apache License 2.0 4 votes vote down vote up
public ConsolePane (Screen screen, Site server, PluginsStage pluginsStage)
{
  this.screen = screen;
  this.telnetState = screen.getTelnetState ();
  this.server = server;

  this.fontManager = screen.getFontManager ();
  pluginsStage.setConsolePane (this);

  screen.setConsolePane (this);
  screen.getScreenCursor ().addFieldChangeListener (this);
  screen.getScreenCursor ().addCursorMoveListener (this);

  setMargin (screen, new Insets (MARGIN, MARGIN, 0, MARGIN));

  menuBar.getMenus ().addAll (getCommandsMenu (), fontManager.getFontMenu ());

  // allow null for replay testing
  if (server == null || server.getPlugins ())
    menuBar.getMenus ().add (pluginsStage.getMenu (server));

  setTop (menuBar);
  setCenter (screen);
  setBottom (statusPane = getStatusBar ());
  menuBar.setUseSystemMenuBar (SYSTEM_MENUBAR);

  setHistoryBar ();

  if (server != null)
  {
    Optional<SiteParameters> sp = parameters.getSiteParameters (server.getName ());
    System.out.println (server.getName ());
    if (sp.isPresent ())
    {
      String offset = sp.get ().getParameter ("offset");
      if (!offset.isEmpty () && offset.length () > 4)
      {
        char direction = offset.charAt (3);
        int value = Integer.parseInt (offset.substring (4));
        System.out.printf ("Time offset : %s %d%n", direction, value);
        ZonedDateTime now = ZonedDateTime.now (ZoneOffset.UTC);
        System.out.println ("UTC         : " + now);
        if (direction == '+')
          now = now.plusHours (value);
        else
          now = now.minusHours (value);
        System.out.println ("Site        : " + now);
        System.out.println ();
      }
    }
  }

  screen.requestFocus ();
}
 
Example 20
Source File: MinionActionManagerTest.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test package install with staging when inside the staging window
 * @throws Exception when Taskomatic service is down
 */
public void testPackageInstallWithStagingInsideWindow() throws Exception {
    user.addPermanentRole(RoleFactory.ORG_ADMIN);
    UserFactory.save(user);

    MinionServer minion1 = MinionServerFactoryTest.createTestMinionServer(user);
    minion1.setOrg(user.getOrg());

    Package pkg = PackageTest.createTestPackage(user.getOrg());
    List packageIds = new LinkedList();
    packageIds.add(pkg.getId().intValue());

    user.getOrg().getOrgConfig().setStagingContentEnabled(true);
    Config.get().setString(SALT_CONTENT_STAGING_WINDOW, "48");
    Config.get().setString(SALT_CONTENT_STAGING_ADVANCE, "48");

    ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
    ZonedDateTime scheduledActionTime = now.plusHours(24);

    TaskomaticApi taskomaticMock = mock(TaskomaticApi.class);
    ActionManager.setTaskomaticApi(taskomaticMock);
    MinionActionManager.setTaskomaticApi(taskomaticMock);

    SystemHandler handler = new SystemHandler(taskomaticMock, xmlRpcSystemHelper, systemEntitlementManager,
            systemManager);
    context().checking(new Expectations() { {
        Matcher<Map<Long, ZonedDateTime>> minionMatcher =
                AllOf.allOf(IsMapContaining.hasKey(minion1.getId()));
        Matcher<Map<Long, Map<Long, ZonedDateTime>>> actionsMatcher =
                AllOf.allOf(IsMapContaining.hasEntry(any(Long.class), minionMatcher));
        exactly(1).of(taskomaticMock)
                .scheduleActionExecution(with(any(Action.class)));
        exactly(1).of(taskomaticMock).scheduleStagingJobs(with(actionsMatcher));
    } });

    DataResult dr = ActionManager.recentlyScheduledActions(user, null, 30);
    int preScheduleSize = dr.size();

    handler.schedulePackageInstall(user, minion1.getId().intValue(), packageIds,
            Date.from(scheduledActionTime.toInstant()));

    dr = ActionManager.recentlyScheduledActions(user, null, 30);
    assertEquals(1, dr.size() - preScheduleSize);
    assertEquals("Package Install", ((ScheduledAction)dr.get(0)).getTypeName());
}