private TimedEventRecord getEventRecordForJob(CallingContext context, String jobUri) { RaptureJob job = retrieveJob(context, jobUri); CronParser parser = MultiCronParser.create(job.getCronSpec()); DateTime midnight = DateMidnight.now().toDateTime(DateTimeZone.forID(job.getTimeZone())); DateTime nextRunDate = parser.nextRunDate(midnight); if (nextRunDate != null) { TimedEventRecord record = new TimedEventRecord(); record.setEventName(job.getDescription()); record.setEventContext(jobUri); record.setInfoContext(job.getActivated().toString()); record.setWhen(nextRunDate.toDate()); return record; } else { return null; } }
public GerritAuthorsAndReviewersList getCommitAuthors(final String changeStatus, String projectFilterString, final String projectFilterOutString, DateTime startDate, DateTime endDate) throws IOException, URISyntaxException { if(null == changeStatus || changeStatus.isEmpty()) { throw new RuntimeException("Error change status cannot be null"); } if(null == projectFilterString) { projectFilterString = ALL_REGEX; } if(null == startDate) { startDate = new DateTime(0); } if(null == endDate) { // Search far enough into future to offset any chance of incorrect // time syncs between servers. endDate = new DateMidnight().plusYears(CURRENT_TIME_OFFSET).toDateTime(); } return statisticsService.getCommitAuthors(changeStatus, projectFilterString, projectFilterOutString, startDate, endDate); }
public GerritReviewStats getReviewStatistics(final String changeStatus, String projectFilterString, String projectFilterOutString, DateTime startDate, DateTime endDate) throws IOException, URISyntaxException { if(null == changeStatus || changeStatus.isEmpty()) { throw new RuntimeException("Error change status cannot be null"); } if(null == projectFilterString) { projectFilterString = ALL_REGEX; } if(null == projectFilterOutString) { projectFilterOutString = ""; } if(null == startDate) { startDate = new DateTime(0); } if(null == endDate) { // Search far enough into future to offset any chance of incorrect // time syncs between servers. endDate = new DateMidnight().plusYears(CURRENT_TIME_OFFSET).toDateTime(); } return statisticsService.getReviewStatistics(changeStatus, projectFilterString, projectFilterOutString, startDate, endDate); }
/** * static method for calculating the current value of the "onlineSecondsToday" field. Usually returns the same value, unless * @param user * @return */ public static boolean shouldResetOnlineSecondsToday(User user) { DateTimeZone timeZone = null; try { timeZone = DateTimeZone.forID(user.getProfile().getTimeZoneId()); } catch (IllegalArgumentException ex) { logger.warn("No time zone found for ID=" + user.getProfile().getTimeZoneId()); // zone not found timeZone = DateTimeZone.UTC; } // if the last login is yesterday, set the secondsToday to zero if (new DateTime(user.getLastLogin(), DateTimeZone.forID("GMT")).isBefore(new DateMidnight(timeZone))) { return true; } return false; }
public void testBigHashtable() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); set.select(Boolean.class); set.select(Character.class); set.select(Byte.class); set.select(Short.class); set.select(Integer.class); set.select(Long.class); set.select(Float.class); set.select(Double.class); set.select(null); set.select(Calendar.class); set.select(GregorianCalendar.class); set.select(DateTime.class); set.select(DateMidnight.class); set.select(ReadableInstant.class); set.select(ReadableDateTime.class); set.select(ReadWritableInstant.class); // 16 set.select(ReadWritableDateTime.class); set.select(DateTime.class); assertEquals(4, set.size()); }
/** * @param companyId * @return * @throws SystemException */ private DateMidnight getMenorMes(long companyId) throws SystemException { Date menorDataMessage = buscaData( "select min(createDate) from MBMessage where companyId = ?", companyId); Date menorDataChat = buscaData( "select min(a.messageTS) from CDChat_ChatRoomMessage a " + "JOIN CDChat_ChatRoom b ON a.chatRoomId = b.roomId " + "JOIN Group_ c on b.groupId = c.groupId " + "WHERE a.messageType = 0 and a.messageStatus = 1 and c.companyId = ?", companyId); if (menorDataMessage == null) // Se não tiver nenhuma mensagem menorDataMessage = new Date(); if (menorDataChat == null) menorDataChat = new Date(); Date menorData = menorDataMessage.before(menorDataChat) ? menorDataMessage : menorDataChat; DateMidnight mes = new DateMidnight(menorData.getTime(), DateTimeZone.forTimeZone(TimeZoneUtil.getDefault())); mes = mes.withDayOfMonth(1); return mes; }
@SuppressWarnings("deprecation") @Test public void testIsSnapshotRequired() throws Exception { StreamService service = new StreamService(); Period period = Period.days(2); Collection<Snapshot> snapshots = new ArrayList<>(); snapshots.add(new Snapshot(0, new DateTime(2014, 1, 1, 0, 0), null)); snapshots.add(new Snapshot(0, new DateTime(2014, 1, 2, 0, 0), null)); snapshots.add(new Snapshot(0, new DateTime(2014, 1, 3, 0, 0), null)); assertThat(service.isSnapshotRequired( new DateMidnight(2014, 1, 3).toInstant(), period, snapshots), is(false)); assertThat(service.isSnapshotRequired( new DateMidnight(2014, 1, 4).toInstant(), period, snapshots), is(false)); assertThat(service.isSnapshotRequired( new DateMidnight(2014, 1, 5).toInstant(), period, snapshots), is(true)); }
public AbstractWeek(DateMidnight weekStart, DateMidnight weekEnd) { this.weekStart = weekStart; this.weekEnd = weekEnd; weekInterval = new Interval(weekStart, weekEnd); AbstractMonthView.logger.debug("Week interval: {}", weekInterval); AbstractMonthView.logger.debug("Initializing days"); days = createDaysArray(7); DateMidnight dayStart = weekStart; for (int i = 0; i < 7; i++) { DateMidnight dayEnd = dayStart.plusDays(1); days[i] = createDay(dayStart, dayEnd); dayStart = dayEnd; } }
public AbstractMonth(DateMidnight referenceDateMidnight) { logger.debug("Initializing month"); this.referenceDateMidnight = referenceDateMidnight; logger.debug("Reference date midnight: {}", referenceDateMidnight); monthStart = referenceDateMidnight.withDayOfMonth(1); monthEnd = monthStart.plusMonths(1); monthInterval = new Interval(monthStart, monthEnd); logger.debug("Month interval: {}", monthInterval); daysCount = Days.daysIn(monthInterval).getDays(); logger.debug("Initializing {} days", daysCount); days = createDaysArray(daysCount); DateMidnight dayStart = monthStart; for (int i = 0; i < daysCount; i++) { DateMidnight dayEnd = dayStart.plusDays(1); days[i] = createDay(dayStart, dayEnd); // advance to next day dayStart = dayEnd; } }
public GetProbeDataCommand(String probeID, String token, ZibaseDeviceConfiguration configuration, CloseableHttpAsyncClient httpClient, ObjectMapper mapper, DateMidnight... date) { super(Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("Zibase")) .andCommandKey(HystrixCommandKey.Factory.asKey("GetProbeData")) ); this.probeID = probeID; if (date.length == 1) { DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy").withLocale(Locale.FRENCH); String dateString = formatter.print(date[0]); this.requestURL = String.format("%s?zibase=%s&token=%s&service=get&target=probe&id=%s&historic=%s", configuration.getUrl(), configuration.getZibaseID(), token, probeID, dateString); } else { this.requestURL = String.format("%s?zibase=%s&token=%s&service=get&target=probe&id=%s", configuration.getUrl(), configuration.getZibaseID(), token, probeID); } this.httpClient = httpClient; this.mapper = mapper; }
@Test public void testConvertFromString() { Date date = new DateMidnight(2013, 12, 11).toDate(); Date seconds = new DateTime(2013, 12, 11, 5, 35, 22).toDate(); Date minutes = new DateTime(2013, 12, 11, 5, 35).toDate(); assertThat(dateConverter.fromString("2013-12-11 5:35")).isEqualTo(minutes); assertThat(dateConverter.fromString("2013-12-11 05:35:22")).isEqualTo(seconds); assertThat(dateConverter.fromString("2013-12-11T05:35:22")).isEqualTo(seconds); assertThat(dateConverter.fromString("2013-12-11")).isEqualTo(date); assertThat(dateConverter.fromString("11/12/2013")).isEqualTo(date); assertThat(dateConverter.fromString("20131211053522")).isEqualTo(seconds); assertThat(dateConverter.fromString("Wed Dec 11 05:35:22 2013")).isEqualTo(seconds); // ASCTIME assertThat(dateConverter.fromString(null)).isNull(); }
@Test public void testSerialization() throws Exception { RestJsonMapper mapper = new RestJsonMapper(); DatesAndTimesTo to = new DatesAndTimesTo(); to.setDate(new Date(114 /*+1900 = 2014*/, 1 /* this is februari */, 14, 10, 11, 12)); to.setLocalDate(LocalDate.of(2014, 2, 14)); to.setLocalDateTime(LocalDateTime.of(2014, 2, 14, 10, 11, 12)); to.setJodaDateTime(new DateTime(2014, 2, 14, 10, 11, 12)); to.setJodaDate(new DateMidnight(2014, 2, 14)); String res = mapper.writeValueAsString(to); System.out.println(res); assertThat(res).contains("\"date\":\"2014-02-14T10:11:12\""); assertThat(res).contains("\"localDate\":\"2014-02-14\""); assertThat(res).contains("\"localDateTime\":\"2014-02-14T10:11:12\""); assertThat(res).contains("\"jodaDateTime\":\"2014-02-14T"); // ignore time as this changes with timezone assertThat(res).contains("\"jodaDate\":\"2014-02-"); // ignore date as this is the date after conversion to GMT }
@Test public void ensureWorkingTimeConfigurationMustExistForPeriodOfSickNote() { DateMidnight startDate = new DateMidnight(2015, DateTimeConstants.MARCH, 1); DateMidnight endDate = new DateMidnight(2015, DateTimeConstants.MARCH, 10); sickNote.setStartDate(startDate); sickNote.setEndDate(endDate); Mockito.when(workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(Mockito.any(Person.class), Mockito.any(DateMidnight.class))) .thenReturn(Optional.empty()); validator.validate(sickNote, errors); Mockito.verify(workingTimeService).getByPersonAndValidityDateEqualsOrMinorDate(sickNote.getPerson(), startDate); Mockito.verify(errors).reject("sicknote.error.noValidWorkingTime"); }
@Test public void ensureCorrectConversionOfVacations() throws Exception { Application vacation1 = TestDataCreator.createApplication(TestDataCreator.createPerson("foo"), new DateMidnight(2016, 5, 19), new DateMidnight(2016, 5, 20), DayLength.FULL); vacation1.setStatus(ApplicationStatus.ALLOWED); Application vacation2 = TestDataCreator.createApplication(TestDataCreator.createPerson("bar"), new DateMidnight(2016, 4, 5), new DateMidnight(2016, 4, 10), DayLength.FULL); Mockito.when(applicationServiceMock.getApplicationsForACertainPeriodAndState(Mockito.any(DateMidnight.class), Mockito.any(DateMidnight.class), Mockito.any(ApplicationStatus.class))) .thenReturn(Arrays.asList(vacation1, vacation2)); mockMvc.perform(get("/api/vacations").param("from", "2016-01-01").param("to", "2016-12-31")) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.response").exists()) .andExpect(jsonPath("$.response.vacations").exists()) .andExpect(jsonPath("$.response.vacations", hasSize(2))) .andExpect(jsonPath("$.response.vacations[0].from", is("2016-05-19"))) .andExpect(jsonPath("$.response.vacations[0].to", is("2016-05-20"))) .andExpect(jsonPath("$.response.vacations[0].person").exists()) .andExpect(jsonPath("$.response.vacations[0].person.ldapName", is("foo"))); }
@Before public void setUp() throws IOException { applicationService = Mockito.mock(ApplicationService.class); nowService = Mockito.mock(NowService.class); WorkingTimeService workingTimeService = Mockito.mock(WorkingTimeService.class); // create working time object (MON-FRI) WorkingTime workingTime = new WorkingTime(); List<Integer> workingDays = Arrays.asList(DateTimeConstants.MONDAY, DateTimeConstants.TUESDAY, DateTimeConstants.WEDNESDAY, DateTimeConstants.THURSDAY, DateTimeConstants.FRIDAY); workingTime.setWorkingDays(workingDays, DayLength.FULL); Mockito.when(workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(Mockito.any(Person.class), Mockito.any(DateMidnight.class))) .thenReturn(Optional.of(workingTime)); SettingsService settingsService = Mockito.mock(SettingsService.class); Mockito.when(settingsService.getSettings()).thenReturn(new Settings()); WorkDaysService calendarService = new WorkDaysService(new PublicHolidaysService(settingsService), workingTimeService, settingsService); vacationDaysService = new VacationDaysService(calendarService, nowService, applicationService); }
public void testGetPriceForDate() { SortedMap<Date, PriceModelDTO> prices = new TreeMap<Date, PriceModelDTO>(); prices.put(CommonConstants.EPOCH_DATE, new PriceModelDTO(PriceModelStrategy.METERED, new BigDecimal("0.10"), null)); prices.put(new DateMidnight(2011, 6, 1).toDate(), new PriceModelDTO(PriceModelStrategy.METERED, new BigDecimal("0.20"), null)); prices.put(new DateMidnight(2011, 8, 1).toDate(), new PriceModelDTO(PriceModelStrategy.METERED, new BigDecimal("0.30"), null)); // a price sometime after 1970-1-1 (epoch) PriceModelDTO model = PriceModelBL.getPriceForDate(prices, new DateMidnight(1985, 2, 4).toDate()); assertEquals("should get epoch pricing", new BigDecimal("0.10"), model.getRate()); // price model the day before the june price takes effect model = PriceModelBL.getPriceForDate(prices, new DateMidnight(2011, 5, 31).toDate()); assertEquals("should get epoch pricing", new BigDecimal("0.10"), model.getRate()); // price model on the day that the june price takes effect (date/times equal) model = PriceModelBL.getPriceForDate(prices, new DateMidnight(2011, 6, 1).toDate()); assertEquals("should get june pricing", new BigDecimal("0.20"), model.getRate()); // price model some day in august model = PriceModelBL.getPriceForDate(prices, new DateMidnight(2011, 8, 15).toDate()); assertEquals("should get august pricing", new BigDecimal("0.30"), model.getRate()); }
@Override public void sendSuccessfullyUpdatedAccountsNotification(List<Account> updatedAccounts) { Map<String, Object> model = new HashMap<>(); model.put("accounts", updatedAccounts); model.put("year", DateMidnight.now().getYear()); String text = mailBuilder.buildMailBody("updated_accounts", model); // send email to office for printing statistic mailSender.sendEmail(getMailSettings(), RecipientUtil.getMailAddresses( recipientService.getRecipientsWithNotificationType(MailNotification.NOTIFICATION_OFFICE)), getTranslation("subject.account.updatedRemainingDays"), text); // send email to manager to notify about update of accounts sendTechnicalNotification(getTranslation("subject.account.updatedRemainingDays"), text); }
@Test public void ensureCancellingNotYetAllowedApplicationForLeaveChangesStateAndOtherAttributesButSendsNoEmail() { Person person = TestDataCreator.createPerson(); Optional<String> comment = Optional.of("Foo"); Application applicationForLeave = getDummyApplication(person); applicationForLeave.setStatus(ApplicationStatus.WAITING); service.cancel(applicationForLeave, person, comment); Assert.assertEquals("Wrong state", ApplicationStatus.REVOKED, applicationForLeave.getStatus()); Assert.assertEquals("Wrong person", person, applicationForLeave.getPerson()); Assert.assertEquals("Wrong canceller", person, applicationForLeave.getCanceller()); Assert.assertEquals("Wrong cancelled date", DateMidnight.now(), applicationForLeave.getCancelDate()); Assert.assertFalse("Must not be formerly allowed", applicationForLeave.isFormerlyAllowed()); Mockito.verify(applicationService).save(applicationForLeave); Mockito.verify(commentService) .create(eq(applicationForLeave), eq(ApplicationAction.REVOKED), eq(comment), eq(person)); Mockito.verifyZeroInteractions(mailService); }
@Test public void convertToString() { final PFUserDO user = new PFUserDO(); user.setTimeZone(DateHelper.EUROPE_BERLIN); user.setLocale(Locale.GERMAN); user.setDateFormat("dd.MM.yyyy"); PFUserContext.setUser(user); JodaDateConverter conv = new JodaDateConverter(); DateMidnight testDate = createDate(1970, DateTimeConstants.NOVEMBER, 21, EUROPE_BERLIN); assertEquals("21.11.1970", conv.convertToString(testDate, Locale.GERMAN)); user.setLocale(Locale.ENGLISH); user.setDateFormat("MM/dd/yyyy"); conv = new JodaDateConverter(); assertEquals("11/21/1970", conv.convertToString(testDate, Locale.GERMAN)); user.setLocale(Locale.GERMAN); user.setDateFormat("dd.MM.yyyy"); conv = new JodaDateConverter(); testDate = createDate(2009, DateTimeConstants.FEBRUARY, 1, EUROPE_BERLIN); assertEquals("01.02.2009", conv.convertToString(testDate, Locale.GERMAN)); user.setLocale(Locale.ENGLISH); user.setDateFormat("MM/dd/yyyy"); conv = new JodaDateConverter(); assertEquals("02/01/2009", conv.convertToString(testDate, Locale.GERMAN)); }
@Test public void testGetTotalVacationDaysForThisYearBeforeApril() { Mockito.when(nowService.now()).thenReturn(new DateMidnight(2015, 3, 2)); initCustomService("4", "1"); Account account = new Account(); account.setValidFrom(new DateMidnight(2015, 1, 1)); account.setAnnualVacationDays(new BigDecimal("30")); account.setVacationDays(new BigDecimal("30")); account.setRemainingVacationDays(new BigDecimal("7")); account.setRemainingVacationDaysNotExpiring(new BigDecimal("3")); BigDecimal leftDays = vacationDaysService.calculateTotalLeftVacationDays(account); Assert.assertNotNull("Should not be null", leftDays); // total number = left vacation days + left remaining vacation days // 32 = 30 + 2 Assert.assertEquals("Wrong number of total vacation days", new BigDecimal("32"), leftDays); }
@Override public Application remind(Application application) throws RemindAlreadySentException, ImpatientAboutApplicationForLeaveProcessException { DateMidnight remindDate = application.getRemindDate(); if (remindDate == null) { DateMidnight minDateForNotification = application.getApplicationDate() .plusDays(MIN_DAYS_LEFT_BEFORE_REMINDING_IS_POSSIBLE); if (minDateForNotification.isAfterNow()) { throw new ImpatientAboutApplicationForLeaveProcessException("It's too early to remind the bosses!"); } } if (remindDate != null && remindDate.isEqual(DateMidnight.now())) { throw new RemindAlreadySentException("Reminding is possible maximum one time per day!"); } mailService.sendRemindBossNotification(application); application.setRemindDate(DateMidnight.now()); applicationService.save(application); return application; }
Person createTestPerson(String login, String password, String firstName, String lastName, String email, Role... roles) throws NoSuchAlgorithmException { List<Role> permissions = Arrays.asList(roles); List<MailNotification> notifications = getNotificationsForRoles(permissions); Person person = personService.create(login, lastName, firstName, email, notifications, permissions); // workaround for non generated password person.setPassword(CryptoUtil.encodePassword(password)); personService.save(person); int currentYear = DateMidnight.now().getYear(); workingTimeService.touch( Arrays.asList(WeekDay.MONDAY.getDayOfWeek(), WeekDay.TUESDAY.getDayOfWeek(), WeekDay.WEDNESDAY.getDayOfWeek(), WeekDay.THURSDAY.getDayOfWeek(), WeekDay.FRIDAY.getDayOfWeek()), Optional.empty(), new DateMidnight(currentYear - 1, 1, 1), person); accountInteractionService.createHolidaysAccount(person, DateUtil.getFirstDayOfYear(currentYear), DateUtil.getLastDayOfYear(currentYear), new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("5"), BigDecimal.ZERO, null); return person; }
@Test public void ensureCalculatesLeftVacationDaysAndLeftOvertimeCorrectly() { DateMidnight from = new DateMidnight(2015, 1, 1); DateMidnight to = new DateMidnight(2015, 12, 31); Person person = Mockito.mock(Person.class); Account account = Mockito.mock(Account.class); Mockito.when(accountService.getHolidaysAccount(2015, person)).thenReturn(Optional.of(account)); Mockito.when(overtimeService.getLeftOvertimeForPerson(person)).thenReturn(new BigDecimal("6.5")); Mockito.when(vacationDaysService.calculateTotalLeftVacationDays(account)).thenReturn(new BigDecimal("8.5")); ApplicationForLeaveStatistics statistics = builder.build(person, from, to); Assert.assertEquals("Wrong left overtime", new BigDecimal("6.5"), statistics.getLeftOvertime()); Assert.assertEquals("Wrong left vacation days", new BigDecimal("8.5"), statistics.getLeftVacationDays()); Mockito.verify(overtimeService).getLeftOvertimeForPerson(person); Mockito.verify(vacationDaysService).calculateTotalLeftVacationDays(account); }
@Test public void ensureCorrectConversionOfSickNotes() throws Exception { SickNote sickNote1 = TestDataCreator.createSickNote(TestDataCreator.createPerson("foo"), new DateMidnight(2016, 5, 19), new DateMidnight(2016, 5, 20), DayLength.FULL); SickNote sickNote2 = TestDataCreator.createSickNote(TestDataCreator.createPerson("bar")); SickNote sickNote3 = TestDataCreator.createSickNote(TestDataCreator.createPerson("baz")); Mockito.when(sickNoteServiceMock.getByPeriod(Mockito.any(DateMidnight.class), Mockito.any(DateMidnight.class))) .thenReturn(Arrays.asList(sickNote1, sickNote2, sickNote3)); mockMvc.perform(get("/api/sicknotes").param("from", "2016-01-01").param("to", "2016-12-31")) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.response").exists()) .andExpect(jsonPath("$.response.sickNotes").exists()) .andExpect(jsonPath("$.response.sickNotes", hasSize(3))) .andExpect(jsonPath("$.response.sickNotes[0].from", is("2016-05-19"))) .andExpect(jsonPath("$.response.sickNotes[0].to", is("2016-05-20"))) .andExpect(jsonPath("$.response.sickNotes[0].person").exists()) .andExpect(jsonPath("$.response.sickNotes[0].person.ldapName", is("foo"))); }
@Test public void ensureRejectingApplicationForLeaveChangesStateAndOtherAttributesAndSavesTheApplicationForLeave() { Person person = TestDataCreator.createPerson("muster"); Person boss = TestDataCreator.createPerson("boss"); Optional<String> comment = Optional.of("Foo"); Application applicationForLeave = getDummyApplication(person); applicationForLeave.setStatus(ApplicationStatus.WAITING); service.reject(applicationForLeave, boss, comment); Assert.assertEquals("Wrong state", ApplicationStatus.REJECTED, applicationForLeave.getStatus()); Assert.assertEquals("Wrong person", person, applicationForLeave.getPerson()); Assert.assertEquals("Wrong boss", boss, applicationForLeave.getBoss()); Assert.assertEquals("Wrong edited date", DateMidnight.now(), applicationForLeave.getEditedDate()); Mockito.verify(applicationService).save(applicationForLeave); Mockito.verify(commentService) .create(eq(applicationForLeave), eq(ApplicationAction.REJECTED), eq(comment), eq(boss)); }
@Test public void ensureConvertedSickNoteIsPersisted() { Application applicationForLeave = new Application(); applicationForLeave.setStartDate(DateMidnight.now()); applicationForLeave.setEndDate(DateMidnight.now()); applicationForLeave.setStatus(ApplicationStatus.ALLOWED); applicationForLeave.setDayLength(DayLength.FULL); applicationForLeave.setPerson(TestDataCreator.createPerson()); SickNote convertedSickNote = sickNoteInteractionService.convert(sickNote, applicationForLeave, person); // assert sick note correctly updated Mockito.verify(sickNoteService).save(sickNote); Mockito.verify(commentService) .create(sickNote, SickNoteAction.CONVERTED_TO_VACATION, Optional.<String>empty(), person); Assert.assertNotNull("Should not be null", convertedSickNote); Assert.assertNotNull("Last edited date should be set", convertedSickNote.getLastEdited()); Assert.assertEquals("Wrong status", SickNoteStatus.CONVERTED_TO_VACATION, convertedSickNote.getStatus()); // assert application for leave correctly created Mockito.verify(applicationInteractionService).createFromConvertedSickNote(applicationForLeave, person); }
/** * Check if there are any overlapping applications for leave or sick notes for the given sick note. * * @param sickNote to be checked if there are any overlaps * * @return {@link OverlapCase} - none, partly, fully */ public OverlapCase checkOverlap(final SickNote sickNote) { Person person = sickNote.getPerson(); DateMidnight startDate = sickNote.getStartDate(); DateMidnight endDate = sickNote.getEndDate(); List<Application> applications = getRelevantApplicationsForLeave(person, startDate, endDate, sickNote.getDayLength()); List<SickNote> sickNotes = getRelevantSickNotes(person, startDate, endDate); if (!sickNote.isNew()) { sickNotes = FluentIterable.from(sickNotes).filter(new Predicate<SickNote>() { @Override public boolean apply(SickNote input) { // the same sick note should not be recognized as overlapping return input.getId() != null && !input.getId().equals(sickNote.getId()); } }).toList(); } return getOverlapCase(startDate, endDate, applications, sickNotes); }
@Test public void ensureCallingOnUpdateChangesLastModificationDate() throws IllegalAccessException { Person person = TestDataCreator.createPerson(); DateMidnight now = DateMidnight.now(); Overtime overtime = new Overtime(person, now.minusDays(2), now, BigDecimal.ONE); // Simulate that the overtime record has been created to an earlier time Field lastModificationDateField = ReflectionUtils.findField(Overtime.class, "lastModificationDate"); lastModificationDateField.setAccessible(true); lastModificationDateField.set(overtime, now.minusDays(3).toDate()); Assert.assertEquals("Wrong initial last modification date", now.minusDays(3), overtime.getLastModificationDate()); overtime.onUpdate(); Assert.assertEquals("Last modification date should be set to now", now, overtime.getLastModificationDate()); }
private Optional<TimedAbsence> checkForHolidays(DateMidnight currentDay, Person person) { BigDecimal expectedWorkingDuration = publicHolidaysService.getWorkingDurationOfDate(currentDay, getFederalState(currentDay, person)); boolean fullDayHoliday = expectedWorkingDuration.compareTo(DayLength.ZERO.getDuration()) == 0; boolean halfDayHoliday = expectedWorkingDuration.compareTo(DayLength.NOON.getDuration()) == 0; TimedAbsence absence = null; if (fullDayHoliday) { absence = new TimedAbsence(DayLength.FULL, TimedAbsence.Type.HOLIDAY); } else if (halfDayHoliday) { absence = new TimedAbsence(DayLength.NOON, TimedAbsence.Type.HOLIDAY); } return Optional.ofNullable(absence); }
@Override public Application reject(Application application, Person privilegedUser, Optional<String> comment) { application.setStatus(ApplicationStatus.REJECTED); application.setBoss(privilegedUser); application.setEditedDate(DateMidnight.now()); applicationService.save(application); LOG.info("Rejected application for leave: " + application.toString()); ApplicationComment createdComment = commentService.create(application, ApplicationAction.REJECTED, comment, privilegedUser); mailService.sendRejectedNotification(application, createdComment); Optional<AbsenceMapping> absenceMapping = absenceMappingService.getAbsenceByIdAndType(application.getId(), AbsenceType.VACATION); if (absenceMapping.isPresent()) { calendarSyncService.deleteAbsence(absenceMapping.get().getEventId()); absenceMappingService.delete(absenceMapping.get()); } return application; }
/** * test issue 109 */ public void test109() { Date someDate = new DateMidnight(9, 2, 21, DateTimeZone.forID("Europe/Amsterdam")).toDate(); Yaml yaml = new Yaml(); String timestamp = yaml.dump(someDate); assertEquals("0009-02-22T23:40:28Z\n", timestamp); // System.out.println(timestamp); Object o = yaml.load(timestamp); assertEquals(someDate, o); }
@Test public void testExtractDocumentAttributes() throws ParseException { //Filling in a random document type name... Revisit String documentTypeName = "SearchDocType"; String key = "givenname"; String value = "jack"; assertExtractDocumentAttributes(documentTypeName, "XMLSearchableAttribute", key, value, "<putWhateverWordsIwantInsideThisTag>" + "<" + key + ">" + "<value>" + value + "</value>" + "</" + key+ ">" + "</putWhateverWordsIwantInsideThisTag>"); // test general operation key = "testLongKey"; value = "123458"; assertExtractDocumentAttributes(documentTypeName, "XMLSearchableAttributeStdLong", key, new BigInteger(value), "<putWhateverWordsIwantInsideThisTag>" + "<" + key + ">" + "<value>" + value + "</value>" + "</" + key+ ">" + "</putWhateverWordsIwantInsideThisTag>"); // test operation with leading and trailing spaces in xml doc content assertExtractDocumentAttributes(documentTypeName, "XMLSearchableAttributeStdLong", key, new BigInteger(value), "<putWhateverWordsIwantInsideThisTag>" + "<" + key + ">" + "<value>" + " " + value + " " + "</value>" + "</" + key + ">" + "</putWhateverWordsIwantInsideThisTag>"); key = "testFloatKey"; value = "2568.204154796"; assertExtractDocumentAttributes(documentTypeName, "XMLSearchableAttributeStdFloat", key, new BigDecimal(value), "<putWhateverWordsIwantInsideThisTag>" + "<" + key+ ">" + "<value>" + value + "</value>" + "</" + key + ">" + "</putWhateverWordsIwantInsideThisTag>"); key = "testDateTimeKey"; value = DocumentSearchInternalUtils.getDisplayValueWithDateOnly(TestXMLSearchableAttributeDateTime.SEARCH_STORAGE_VALUE); // value is coerced to Date without time DateMidnight expected = TestXMLSearchableAttributeDateTime.SEARCH_STORAGE_VALUE.toDateMidnight(); assertExtractDocumentAttributes(documentTypeName, "XMLSearchableAttributeStdDateTime", key, expected, "<putWhateverWordsIwantInsideThisTag>" + "<" + key + ">" + "<value>" + value + "</value>" + "</" + key + ">" + "</putWhateverWordsIwantInsideThisTag>"); // test for kuali xstream formatted dates value = "02/20/2007"; String returnValue = "02/20/2007"; // value is coerced to Date without time Date d = RiceConstants.getDefaultDateFormat().parse(returnValue); expected = new DateTime(d.getTime()).toDateMidnight(); assertExtractDocumentAttributes(documentTypeName, "XMLSearchableAttributeStdDateTime", key, expected, "<putWhateverWordsIwantInsideThisTag>" + "<" + key + ">" + "<value>" + value + "</value>" + "</" + key + ">" + "</putWhateverWordsIwantInsideThisTag>"); }
/** * Transforma duas datas textuais (ex: "2008-06-14") em um objeto Interval, * que representa um intervalo de tempo. */ private Interval getIntervalFromParams(String start_date_str, String end_date_str) { DateTimeFormatter formatter = DateTimeFormat.forPattern("y-M-d"); // DateMidnight e um DateTime onde a hora e sempre 00:00. DateMidnight start_date = new DateMidnight( formatter.parseDateTime(start_date_str)); DateMidnight end_date = new DateMidnight( formatter.parseDateTime(end_date_str)); return new Interval(start_date, end_date); }
@Override protected Collection<String> computeLiteralClassNames() { // we completely define the content ourselves, but need the collection // instance from the super class as it is a private field Collection<String> literalClassNames = super.getLiteralClassNames(); if(literalClassNames==null) { literalClassNames = super.computeLiteralClassNames(); } literalClassNames.clear(); // add all actions that are contributed as OSGi services Object[] services = ScriptActivator.actionServiceTracker.getServices(); if(services!=null) { for(Object service : services) { ActionService actionService = (ActionService) service; literalClassNames.add(actionService.getActionClassName()); } } literalClassNames.add(CollectionLiterals.class.getName()); literalClassNames.add(InputOutput.class.getName()); literalClassNames.add(BusEvent.class.getCanonicalName()); literalClassNames.add(ScriptExecution.class.getCanonicalName()); literalClassNames.add(LogAction.class.getCanonicalName()); // jodatime static functions literalClassNames.add(DateTime.class.getCanonicalName()); literalClassNames.add(DateMidnight.class.getCanonicalName()); return literalClassNames; }
@Test public void testHistoricState() { HistoricItem historicItem = PersistenceExtensions.historicState(item, new DateMidnight(2012, 1, 1), "test"); assertEquals("2012", historicItem.getState().toString()); historicItem = PersistenceExtensions.historicState(item, new DateMidnight(2011, 12, 31), "test"); assertEquals("2011", historicItem.getState().toString()); historicItem = PersistenceExtensions.historicState(item, new DateMidnight(2011, 1, 1), "test"); assertEquals("2011", historicItem.getState().toString()); historicItem = PersistenceExtensions.historicState(item, new DateMidnight(2000, 1, 1), "test"); assertEquals("2000", historicItem.getState().toString()); }
@Test public void testMinimumSince() { item.setState(new DecimalType(5000)); HistoricItem historicItem = PersistenceExtensions.minimumSince(item, new DateMidnight(1940, 1, 1), "test"); assertNotNull(historicItem); assertEquals("5000", historicItem.getState().toString()); historicItem = PersistenceExtensions.minimumSince(item, new DateMidnight(2005, 1, 1), "test"); assertEquals("2005", historicItem.getState().toString()); assertEquals(new DateMidnight(2005, 1, 1).toDate(), historicItem.getTimestamp()); }
@Test public void testMaximumSince() { item.setState(new DecimalType(1)); HistoricItem historicItem = PersistenceExtensions.maximumSince(item, new DateMidnight(2012, 1, 1), "test"); assertNotNull(historicItem); assertEquals("1", historicItem.getState().toString()); historicItem = PersistenceExtensions.maximumSince(item, new DateMidnight(2005, 1, 1), "test"); assertEquals("2012", historicItem.getState().toString()); assertEquals(new DateMidnight(2012, 1, 1).toDate(), historicItem.getTimestamp()); }
@Test public void testCurrentDate() throws Exception { // current date is the time at midnight in the session time zone DateMidnight dateMidnight = new DateMidnight(session.getStartTime(), DATE_TIME_ZONE); int days = (int) TimeUnit.MILLISECONDS.toDays(dateMidnight.getMillis()); assertFunction("CURRENT_DATE", DateType.DATE, new SqlDate(days)); }