@Test public void testBasic() { System.out.println(Year.now()); System.out.println(Year.of(2015)); System.out.println(Year.isLeap(2016)); Locale locale = Locale.getDefault(); System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL, locale)); System.out.println(Month.DECEMBER.getDisplayName(TextStyle.SHORT, locale)); System.out.println(Month.DECEMBER.getDisplayName(TextStyle.NARROW, locale)); System.out.println(Month.DECEMBER.getDisplayName(TextStyle.FULL_STANDALONE, locale)); System.out.println(Month.of(8).ordinal()); System.out.println(Month.AUGUST.minus(2)); System.out.println(YearMonth.now()); System.out.println(MonthDay.now()); System.out.println(DayOfWeek.FRIDAY.plus(2)); System.out.println(DayOfWeek.of(1)); System.out.println( DayOfWeek.from(LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()))); System.out.println(Period.between(Year.now().atDay(1), LocalDate.now())); System.out.println(ChronoUnit.DAYS.between(Year.now().atDay(1), LocalDate.now())); }
// @Test public void numberFunctions() throws IOException { ServiceLocator locator = container; DataContext db = locator.resolve(DataContext.class); LocalDate ld = LocalDate.now(); Clicked cl = new Clicked().setDate(ld); db.submit(cl); Query<Clicked> query = db.query(Clicked.class); String uri = cl.getURI(); // TODO: produces incorrect queries boolean found1 = query.anyMatch( it -> Long.valueOf(3).equals(it.getBigint()) && it.getEn() == En.A || it.getURI().toUpperCase().equals(uri)); boolean found2 = query.anyMatch( it -> 3L >= it.getBigint() && it.getDate() == LocalDate.now() || Integer.valueOf(it.getURI()).equals(Integer.valueOf(uri))); boolean found3 = query.anyMatch( it -> Long.valueOf(3).equals(it.getBigint()) && it.getEn() == En.B || it.getURI().toUpperCase().equals(uri)); En b = En.B; boolean found4 = query.anyMatch(it -> it.getEn() == b || it.getURI().toUpperCase().equals(uri)); Assert.assertTrue(found1); Assert.assertTrue(found2); Assert.assertTrue(found3); Assert.assertTrue(found4); }
/** * Initialises the collection of entity information from the ICAT into the Dashboard. */ private void initialiseEntityCollection() { LocalDate today = LocalDate.now(); LOG.info("Data Collection initiated for " + today.toString()); LocalDate earliestEntityImport = getNextImportDate("entity"); LocalDate earliestInstrumentImport = getNextImportDate("instrument"); LocalDate earliestInvestigationImport = getNextImportDate("investigation"); // Import data into Dashboard even if the import script has never been run if (earliestEntityImport == null && earliestInstrumentImport == null && earliestInvestigationImport == null) { LocalDate past = LocalDate.now().minusWeeks(1); counter.performEntityCountCollection(past, today); counter.performInstrumentMetaCollection(past, today); counter.performInvestigationMetaCollection(past, today); } // An actual import has happened. if (earliestEntityImport != null) { counter.performEntityCountCollection(earliestEntityImport, today); } if (earliestInstrumentImport != null) { counter.performInstrumentMetaCollection(earliestInstrumentImport, today); } if (earliestInvestigationImport != null) { counter.performInvestigationMetaCollection(earliestInvestigationImport, today); } LOG.info("Data collection completed for " + today.toString()); }
@Test public void test() { Cliente c1 = new Cliente(); c1.setStatus(1); c1.setTipopessoa(2); c1.setSexo(1); c1.setDatanascimento(LocalDate.now()); c1.setNomerazao(""); c1.setCpfcnpj(""); c1.setRgie(""); c1.setEndereco(""); c1.setNumero("54"); c1.setComplemento("10"); c1.setBairro(""); c1.setEstado(3); c1.setCidade(3); c1.setCep("3678000"); c1.setTel(""); c1.setCel(""); c1.setEmail("*****@*****.**"); c1.setSite("teste"); c1.setClientedesde(LocalDate.now()); c1.setObs("teste"); ClienteDao dao = new ClienteDao(); Boolean b = true; try { assertEquals(b, dao.inserir(c1)); } catch (Exception e) { // Todo Auto-generated catch block e.printStackTrace(); } }
@Test public void testLocalDate() { System.out.println(LocalDate.now()); System.out.println(LocalDate.ofYearDay(2015, 300)); System.out.println(LocalDate.now().atStartOfDay()); System.out.println(LocalDate.now().atTime(12, 20)); }
@Override public void saveAsExcel() { TableView<ItemPrice> itemTable = new ItemTable(this).getTable(); itemTable.setItems(item.list()); itemTable.setId(module + " List as of " + Util.formatDate(LocalDate.now())); new ExcelWriter( Arrays.asList(Arrays.asList(itemTable)), module, Util.dateToFileName(LocalDate.now())); }
@Test public void testRemoveOldPersistentTokens() { User admin = userRepository.findOneByLogin("admin").get(); int existingCount = persistentTokenRepository.findByUser(admin).size(); generateUserToken(admin, "1111-1111", LocalDate.now()); LocalDate now = LocalDate.now(); generateUserToken(admin, "2222-2222", now.minusDays(32)); assertThat(persistentTokenRepository.findByUser(admin)).hasSize(existingCount + 2); userService.removeOldPersistentTokens(); assertThat(persistentTokenRepository.findByUser(admin)).hasSize(existingCount + 1); }
private void moveCurrentCarToCarHistory(Employee employee) { Car currentCar = carRepository.findOne(employee.getCurrentCar().getId()); Set<Car> carHistory = employee.getCarHistory(); carHistory.add(employee.getCurrentCar()); if (currentCar.getEndLeasing().isAfter(LocalDate.now()) && !(currentCar.getEndLeasing().isEqual(LocalDate.now()))) { currentCar.setInThePool(true); } carRepository.save(currentCar); }
@Test public void testStartDateValidator() { // empty is invalid Assert.assertFalse(viewModel.startDateValidation().isValid()); viewModel.endDateProperty().set(LocalDate.now()); Assert.assertFalse(viewModel.startDateValidation().isValid()); viewModel.endDateProperty().set(null); viewModel.startDateProperty().setValue(LocalDate.now()); Assert.assertTrue(viewModel.startDateValidation().isValid()); viewModel.endDateProperty().setValue(LocalDate.now().minusDays(2)); Assert.assertFalse(viewModel.startDateValidation().isValid()); }
@Override public void afterPropertiesSet() throws Exception { repository.add( new Session("The Movie", LocalTime.NOON, LocalDate.now(), new BigDecimal("150.00"))); repository.add( new Session( "The Movie2", LocalTime.NOON, LocalDate.now().plus(1, ChronoUnit.DAYS), new BigDecimal("152.00"))); repository.add( new Session("The Movie3", LocalTime.NOON, LocalDate.now(), new BigDecimal("153.00"))); repository.add( new Session("The Movie4", LocalTime.NOON, LocalDate.now(), new BigDecimal("154.00"))); }
/** Validate the token and return it. */ private PersistentToken getPersistentToken(String[] cookieTokens) { if (cookieTokens.length != 2) { throw new InvalidCookieException( "Cookie token did not contain " + 2 + " tokens, but contained '" + Arrays.asList(cookieTokens) + "'"); } String presentedSeries = cookieTokens[0]; String presentedToken = cookieTokens[1]; PersistentToken token = persistentTokenRepository.findOne(presentedSeries); if (token == null) { // No series match, so we can't authenticate using this cookie throw new RememberMeAuthenticationException( "No persistent token found for series id: " + presentedSeries); } // We have a match for this user/series combination log.info("presentedToken={} / tokenValue={}", presentedToken, token.getTokenValue()); if (!presentedToken.equals(token.getTokenValue())) { // Token doesn't match series value. Delete this session and throw an exception. persistentTokenRepository.delete(token); throw new CookieTheftException( "Invalid remember-me token (Series/token) mismatch. Implies previous " + "cookie theft attack."); } if (token.getTokenDate().plusDays(TOKEN_VALIDITY_DAYS).isBefore(LocalDate.now())) { persistentTokenRepository.delete(token); throw new RememberMeAuthenticationException("Remember-me login has expired"); } return token; }
@Override protected void onLoginSuccess( HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { String login = successfulAuthentication.getName(); log.debug("Creating new persistent login for user {}", login); PersistentToken token = userRepository .findOneByLogin(login) .map( u -> { PersistentToken t = new PersistentToken(); t.setSeries(generateSeriesData()); t.setUser(u); t.setTokenValue(generateTokenData()); t.setTokenDate(LocalDate.now()); t.setIpAddress(request.getRemoteAddr()); t.setUserAgent(request.getHeader("User-Agent")); return t; }) .orElseThrow( () -> new UsernameNotFoundException( "User " + login + " was not found in the database")); try { persistentTokenRepository.saveAndFlush(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to save persistent token ", e); } }
@Test public void testGetNextFirstOrFifteenthOfTheMonthWithNullBaseDateReturnsValue() { LocalDate today = LocalDate.now(); LocalDate adjustmentDate = AmortizationCalculator.getNextFirstOrFifteenthOfTheMonth(null); long daysBetween = Period.between(today, adjustmentDate).getDays(); assertTrue("Adjustment date from the 1st should remain on the 1st", daysBetween <= 16); }
public void checkoutBook(String memberID, String bookCopyId) { // Get Library member's FULL object from file System LibraryMember lm = libraryMemberService.readLibraryMember(memberID); // CheckoutRecord checkoutRecord = lm.getRecord(); // Get BookCopy which we are trying to checkout BookCopy bookCopy = BookCopy.getBookCopy(bookCopyId); // Get the Book Object Book book = Book.get(bookCopy.getISBN()); // Current/ today's date LocalDate checkoutDate = LocalDate.now(); // Duedate = current date PLUS no of days to lend LocalDate dueDate = checkoutDate.plusDays(book.getDaysOfLend()); // Create a new checkout entry CheckoutEntry checkoutEntry = new CheckoutEntry(bookCopy, checkoutDate, dueDate, false); checkoutRecord.addEntry(checkoutEntry); lm.setRecord(checkoutRecord); lm.writeLibraryMember(lm); }
@Test public void testEndDateValidator() { Assert.assertFalse("Null end date is invalid", viewModel.endDateValidation().isValid()); viewModel.endDateProperty().set(LocalDate.now().plusDays(3)); viewModel.releaseProperty().set(new Release("", null, LocalDate.now().plusDays(2), "")); Assert.assertFalse( "End date must be before release date", viewModel.endDateValidation().isValid()); viewModel.endDateProperty().set(LocalDate.now().plusDays(2)); Assert.assertTrue( "End date same as release date is valid", viewModel.endDateValidation().isValid()); viewModel.releaseProperty().set(new Release("", null, LocalDate.now(), "")); Assert.assertFalse( "Release date must not be before end date", viewModel.endDateValidation().isValid()); }
/** * @author 'armen.mkrtchyan' * @version 1.0 */ public class VisitorClient { private static final List<SomeOtherTypeVisitable> someOtherTypeVisitables = Arrays.asList( new IntegerOtherTypeVisitable(10000000), new DateOtherTypeVisitable(LocalDate.now())); private static final List<SomeTypeVisitable> someTypeVisitables = Arrays.asList(new IntegerTypeVisitable(110000000), new DateTypeVisitable(LocalDate.now())); public static void main(String[] args) { OtherFormatterVisitor otherFormatterVisitor = new OtherFormatterVisitor(); someOtherTypeVisitables.forEach(v -> v.accept(otherFormatterVisitor)); FormatterVisitor formatterVisitor = new FormatterVisitor(); someTypeVisitables.forEach(v -> v.accept(formatterVisitor)); } }
@Override public void parse(Message m) { String target = m.param(); if (!m.param().startsWith("#")) target = m.sender(); if (m.trailing().equals("TIME")) { String time = String.format( "%s %02d:%02d:%02d ", LocalDate.now().toString(), LocalTime.now().getHour(), LocalTime.now().getMinute(), LocalTime.now().getSecond()); m.notice(m.sender(), String.format("TIME %s", time)); } if (m.command().equals("PRIVMSG")) { if (m.botCommand().equals("time")) { if (m.hasBotParams()) { for (int i = 0; i < m.botParamsArray().length; i++) { m.pm(m.botParamsArray()[i], "TIME"); requests.put(m.botParamsArray()[i], target); } } } } if (m.command().equals("NOTICE")) { if (requests.containsKey(m.sender())) { if (m.trailing().startsWith("TIME")) { String version = m.trailing().substring(5, m.trailing().length() - 1); Server.say(requests.get(m.sender()), "[" + m.sender() + "] Current Time: " + version); requests.remove(m.sender()); } } } }
@Override @Transactional protected UserDetails processAutoLoginCookie( String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) { PersistentToken token = getPersistentToken(cookieTokens); String login = token.getUser().getLogin(); // Token also matches, so login is valid. Update the token value, keeping the *same* series // number. log.debug( "Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries()); token.setTokenDate(LocalDate.now()); token.setTokenValue(generateTokenData()); token.setIpAddress(request.getRemoteAddr()); token.setUserAgent(request.getHeader("User-Agent")); try { persistentTokenRepository.saveAndFlush(token); addCookie(token, request, response); } catch (DataAccessException e) { log.error("Failed to update token: ", e); throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e); } return getUserDetailsService().loadUserByUsername(login); }
public boolean saveCheckOutRecord() { // save data into stream this.member.checkout(copy, LocalDate.now(), dateDue); DataAccess da = new DataAccessFacade(); da.updateMember(this.member); return true; }
@Override public void clearForm() { modTrans = null; amountField.setDecimal(BigDecimal.ZERO); reconciledButton.setDisable(false); reconciledButton.setSelected(false); reconciledButton.setIndeterminate(false); if (payeeTextField != null) { // transfer slips do not use the payee field payeeTextField.setEditable(true); payeeTextField.clear(); } datePicker.setEditable(true); if (!Options.rememberLastDateProperty().get()) { datePicker.setValue(LocalDate.now()); } memoTextField.clear(); numberComboBox.setValue(null); numberComboBox.setDisable(false); attachmentPane.clear(); }
/** * Modify a transaction before it is used to complete the panel for auto fill. The supplied * transaction must be a new or cloned transaction. It can't be a transaction that lives in the * map. The returned transaction can be the supplied reference or may be a new instance * * @param t The transaction to modify * @return the modified transaction */ private Transaction modifyTransactionForAutoComplete(final Transaction t) { // tweak the transaction t.setNumber(null); t.setReconciled(ReconciledState.NOT_RECONCILED); // clear both sides // set the last date as required if (!Options.rememberLastDateProperty().get()) { t.setDate(LocalDate.now()); } else { t.setDate(datePicker.getValue()); } // preserve any transaction entries that may have been entered first if (amountField.getLength() > 0) { Transaction newTrans = buildTransaction(); t.clearTransactionEntries(); t.addTransactionEntries(newTrans.getTransactionEntries()); } // preserve any preexisting memo field info if (memoTextField.getLength() > 0) { t.setMemo(memoTextField.getText()); } // Do not copy over attachments t.setAttachment(null); return t; }
/** * Tests if birth date is valid. Validation separate from getter method to allow validation before * assigning ramq. Assumes birthdate cannot be equal to or over 100 years ago. * * @param date the date portion of the Ramq * @returns birthDate the birthdate in LocalDate form * @throws IllegalArgumentException */ private LocalDate validateBirthdate(String date) throws IllegalArgumentException { LocalDate birthdate; int year = Integer.parseInt(date.substring(0, 2)); int month = Integer.parseInt(date.substring(2, 4)); int day = Integer.parseInt(date.substring(4)); // If Ramq belongs to a female, removes 50 from birth month if (month > 50) { month = month - 50; } // Checks for which century birthdate belongs in // Difference of less than 2000 demonstrates that birth was in 1900s int currentYear = LocalDate.now().getYear(); if ((currentYear - year) < 2000) { year = 1900 + year; } else { year = 2000 + year; } try { birthdate = LocalDate.of(year, month, day); } catch (DateTimeException dtpe) { throw new IllegalArgumentException( "Cannot identify date. " + "Ramq is invalid.\n" + dtpe.getMessage()); } return birthdate; }
@Test public void testGetFullAge4LocalDate() { int currentYear = LocalDate.now().getYear(); int birthYear = 2010; LocalDate birthDate = LocalDate.of(birthYear, 1, 1); Assert.assertEquals(currentYear - birthYear, AgeUtils.getFullAge(birthDate)); }
public static void main(String[] args) { LocalDate hoje = LocalDate.now(); System.out.println(hoje); LocalDate olimpiadasRio = LocalDate.of(2016, Month.JUNE, 5); System.out.println(olimpiadasRio); int dias = olimpiadasRio.getDayOfYear() - hoje.getDayOfYear(); System.out.println(dias + " dias para as Olímpiadas no Rio!"); Period periodo = Period.between(hoje, olimpiadasRio); System.out.println(periodo.getMonths() + " meses e " + periodo.getDays() + " dias."); DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String valorFormatado = olimpiadasRio.format(formatador); System.out.println(valorFormatado); System.out.println(" --- Medida de tempo ---"); DateTimeFormatter formatadorComHoras = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss"); LocalDateTime agora = LocalDateTime.now(); System.out.println(agora); System.out.println(agora.format(formatadorComHoras)); LocalTime intervalo = LocalTime.of(12, 30); System.out.println(intervalo); }
@Override public boolean checkoutBook(String memberId, String isbn) throws LibrarySystemException { Book currentBook = searchBook(isbn); BookCopy[] book = currentBook.getCopies(); for (BookCopy bc : book) { if (computeStatus(bc)) { DataAccessFacade dc = new DataAccessFacade(); LocalDate currentDate = LocalDate.now(); LocalDate dueDate = currentDate.plusDays(bc.getBook().getMaxCheckoutLength()); CheckoutRecordEntry newCheckoutRecordEntry = new CheckoutRecordEntry(currentDate, dueDate, bc); LibraryMember member = search(memberId); CheckoutRecord rc = member.getCheckoutRecord(); if (rc.getCheckoutRecordEntries() == null) { List<CheckoutRecordEntry> entries = new ArrayList<>(); entries.add(newCheckoutRecordEntry); member.getCheckoutRecord().setCheckoutRecordEntries(entries); } else { member.getCheckoutRecord().getCheckoutRecordEntries().add(newCheckoutRecordEntry); } bc.changeAvailability(); dc.updateMember(member); dc.saveNewBook(currentBook); return true; } } return false; }
public class DateComparisonUsingLocalDate { LocalDate now = LocalDate.now(); String beginningOfMonth = now.withDayOfMonth(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US)); String today = now.format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US)); String yesterday = now.minusDays(1).format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US)); SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy"); void checkIfSameDay() throws Exception { String startDateStr = "03/03/2011"; String endDateStr = "03/03/2011"; Date endDate = formatter.parse(endDateStr); boolean isSameDay; isSameDay = DateUtils.isSameDay(formatter.parse(beginningOfMonth), formatter.parse(startDateStr)); System.out.println("==1==" + isSameDay); isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate); System.out.println("==2==" + isSameDay); isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), formatter.parse(startDateStr)); System.out.println("==3==" + isSameDay); isSameDay = DateUtils.isSameDay(formatter.parse(yesterday), endDate); System.out.println("==4==" + isSameDay); } }
public static void main(String[] args) { // Current Date LocalDateTime today = LocalDateTime.now(); System.out.println("Current DateTime=" + today); // Current Date using LocalDate and LocalTime today = LocalDateTime.of(LocalDate.now(), LocalTime.now()); System.out.println("Current DateTime=" + today); // Creating LocalDateTime by providing input arguments LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30); System.out.println("Specific Date=" + specificDate); // Try creating date by providing invalid inputs // LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28, // 25,1,1); // Exception in thread "main" java.time.DateTimeException: // Invalid value for HourOfDay (valid values 0 - 23): 25 // Current date in "Asia/Kolkata", you can get it from ZoneId javadoc LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata")); System.out.println("Current Date in IST=" + todayKolkata); // java.time.zone.ZoneRulesException: Unknown time-zone ID: IST // LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST")); // Getting date from the base date i.e 01/01/1970 LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC); System.out.println("10000th second time from 01/01/1970= " + dateFromBase); }
@Test public void testGetTrackerDataDailyAgg() { List<TrackerData> trackerDataList = Arrays.asList( new TrackerData(Instant.now().minus(Duration.ofDays(2)), 9), new TrackerData(Instant.now(), 11), new TrackerData(Instant.now(), 12)); when(trackerDAO.findTrackerData()).thenReturn(trackerDataList); Map<LocalDate, Integer> expectedResult = new HashMap<>(); expectedResult.put(LocalDate.now().minusDays(2), 9); expectedResult.put(LocalDate.now(), 23); Map<LocalDate, Integer> result = trackerService.getTrackerDailyDataAgg(); assertEquals(2, result.size()); assertEquals(expectedResult, result); }
public Period calculateSeniority() { LocalDate hireDate = this.getHireDate(); if (hireDate == null) return null; LocalDate now = LocalDate.now(); return Period.between(hireDate, now); }
public static void main(String args[]) { LocalDate curDate = LocalDate.now(); System.out.println(curDate); LocalTime curTime = LocalTime.now(); System.out.println(curTime); }