public Hoodlum loadHoodlum(UUID uuid) { CustomConfig config = gangs.getHoodlumConfig(); String uuidString = uuid.toString(); Hoodlum hoodlum = new Hoodlum(uuid); if (config.getConfig().contains(uuidString)) { hoodlum.setPower(config.get(uuidString + "." + HoodlumConfig.POWER, Integer.class)); hoodlum.setMaxPower(config.get(uuidString + "." + HoodlumConfig.MAX_POWER, Integer.class)); if (config.has(uuidString + "." + HoodlumConfig.GANG_UUID)) { hoodlum.setGangUUID( UUID.fromString(config.get(uuidString + "." + HoodlumConfig.GANG_UUID, String.class))); } hoodlum.setGang(gangs.getGangCoordinator().getGang(hoodlum.getGangUUID())); hoodlum.setRole( GangRole.valueOf(config.get(uuidString + "." + HoodlumConfig.GANG_ROLE, String.class))); hoodlum.setLastLogon( LocalDateTime.parse( config.get(uuidString + "." + HoodlumConfig.LAST_ONLINE, String.class))); hoodlum.setLastLogoff( LocalDateTime.parse( config.get(uuidString + "." + HoodlumConfig.LAST_OFFLINE, String.class))); if (config.has(uuidString + "." + HoodlumConfig.MESSAGES)) { hoodlum.loadNotices( config.getConfig().getStringList(uuidString + "." + HoodlumConfig.MESSAGES)); } } hoodlumMap.put(uuid, hoodlum); return hoodlum; }
static LocalDateTime parse(String endDateTimeString) { String endDateString = null; String endTimeString = null; Pattern pattern = Pattern.compile(DATE_TIME_PATTERN); Matcher matcher = pattern.matcher(endDateTimeString); matcher.find(); endDateString = matcher.group(1); endTimeString = matcher.group(2); if (endDateString == null) { endDateString = "today"; } if (endTimeString == null) { endTimeString = END_TIME_DEFAULT; } LocalDate endDate = DateParser.parse(endDateString); LocalTime endTime = TimeParser.parse(endTimeString); LocalDateTime endDateTime = endDate.atTime(endTime); if (endDateTime.isBefore(LocalDateTime.now())) { endDateTime = endDateTime.plusDays(1); } return endDateTime; }
@Test public void timeout() { Jcl jcl = JclFactory.compileJcl( JOB + "## run at 2016-2-10 18:24 timeout 1 minute\n" + "## run at 2016/2/10 18:24 timeout 1 hour\n" + "## run every minute timeout minute\n" + "## run every 10 minutes timeout 5 minutes\n"); test(jcl); System.out.println(jcl.getSchedule().replace("><", ">\n<")); assertSame(JclType.SCHEDULABLE, jcl.getType()); LocalDateTime dt = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES); String now = dt.toLocalDate().toString() + " " + dt.toLocalTime().toString(); assertEquals( "Schedule", "<schedule>" + "<once at=\"2016-02-10 18:24\" timeout=\"1 minute\"/>" + "<once at=\"2016-02-10 18:24\" timeout=\"1 hour\"/>" + "<repeat next=\"" + now + "\" step=\"1 minute\" timeout=\"1 minute\"/>" + "<repeat next=\"" + now + "\" step=\"10 minute\" timeout=\"5 minute\"/>" + "</schedule>", jcl.getSchedule()); }
@RequestMapping(value = "/{templateName}/{cmsName}", method = POST) public String sendEmail( DownloadRequest downloadRequest, @PathVariable String templateName, @PathVariable String cmsName) { downloadRequest.setTemplateName(templateName); downloadRequest.setCms(cmsName); downloadRequest.setCreated(LocalDateTime.now()); logger.info("New download request: {}", downloadRequest); downloadRequest = downloadRequestRepository.save(downloadRequest); long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC); String hash = downloadRequestParamsHasher.getHash( Template.valueOf(templateName).getDownloadName(), Cms.valueOf(cmsName).getNamePl(), timestamp); HtmlEmailMessage htmlEmailMessage = new HtmlEmailMessage( "*****@*****.**", downloadRequest.getAdministrativeEmail(), "Szablon CMS ze strony PWD", getEmailMessageTemplate(), getEmailMessageModelMap( templateName, Template.valueOf(templateName).getDownloadName(), Cms.valueOf(cmsName).getNamePl(), hash, timestamp)); if (mailgunClient.sendEmail(htmlEmailMessage)) { return "email_download"; } return "error"; }
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); }
public boolean overlap(TimeInterval other) { if (end.isEqual(other.start)) return false; if (end.isBefore(other.start)) return false; if (start.isEqual(other.end)) return false; if (start.isAfter(other.end)) return false; return true; }
/** * RFC 2616 allows three different date-formats: * * <ul> * <li>RFC 1123 * <li>RFC 1036 * <li>ASCI-Time * </ul> * * @param headerValue value transmitted from client * @return the parsed DateTime * @see <a href= "http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3">RFC 2616</a> */ private LocalDateTime convertIfModifiedSinceToDate(String headerValue) { LocalDateTime time = null; try { time = LocalDateTime.parse(headerValue, DateTimeFormatter.RFC_1123_DATE_TIME); } catch (DateTimeParseException e) { logger.trace("could not parse date with RFC-1123. Will try RFC-1036 format..."); } if (time == null) { try { final String PATTERN_RFC1036 = "EEE, dd-MMM-yy HH:mm:ss zzz"; time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_RFC1036)); } catch (DateTimeParseException e) { logger.trace("could not parse date with RFC-1036. Will try ASCITIME format..."); } } if (time == null) { try { final String PATTERN_ASCITIME = "EEE MMM d HH:mm:ss yyyy"; time = LocalDateTime.parse(headerValue, DateTimeFormatter.ofPattern(PATTERN_ASCITIME)); } catch (DateTimeParseException e) { logger.trace("could not parse date with ASCITIME."); } } if (time == null) { logger.error("Could not parse given if-modified-since header with value '{}'", headerValue); } return time; }
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); }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Ordering ordering = (Ordering) o; if (id != ordering.id) return false; if (amountOfPeople != ordering.amountOfPeople) return false; if (Double.compare(ordering.advancePayment, advancePayment) != 0) return false; if (dateOrderCreated != null ? !dateOrderCreated.equals(ordering.dateOrderCreated) : ordering.dateOrderCreated != null) return false; if (dateClientsCome != null ? !dateClientsCome.equals(ordering.dateClientsCome) : ordering.dateClientsCome != null) return false; if (description != null ? !description.equals(ordering.description) : ordering.description != null) return false; if (whoTakenOrder != null ? !whoTakenOrder.equals(ordering.whoTakenOrder) : ordering.whoTakenOrder != null) return false; if (whoServesOrder != null ? !whoServesOrder.equals(ordering.whoServesOrder) : ordering.whoServesOrder != null) return false; if (fund != null ? !fund.equals(ordering.fund) : ordering.fund != null) return false; if (type != ordering.type) return false; return !(denominations != null ? !denominations.equals(ordering.denominations) : ordering.denominations != null); }
@Override public String convert(LocalDateTime dateTime) { LocalDateTime now = LocalDateTime.now(); Duration duration = Duration.between(dateTime, now); Period period = Period.between(dateTime.toLocalDate(), now.toLocalDate()); if (duration.toMinutes() < 1) { return String.format("%s secs ago", duration.getSeconds()); } if (duration.toHours() < 1) { return String.format("%s mins ago", duration.toMinutes()); } if (duration.toDays() < 1) { return String.format("%s hrs ago", duration.toHours()); } if (period.getYears() > 0) { return DateTimeFormatter.ISO_LOCAL_DATE.format(dateTime); } if (period.getMonths() > 0) { return String.format("%s months ago", period.getMonths()); } return String.format("%s days ago", period.getDays()); }
@Test public void testCookieBuilder() { // given LocalDateTime now = LocalDateTime.now(); // when Cookie cookie = CookieBuilder.create() .name("foo") .value("bar") .path("/foobar") .domain("www.foo.com") .maxAge(1223) .expires(now) .discard(true) .secure(true) .httpOnly(true) .build(); // then assertThat(cookie, not(nullValue())); assertThat("foo", equalTo(cookie.getName())); assertThat("bar", equalTo(cookie.getValue())); assertThat("/foobar", equalTo(cookie.getPath())); assertThat("www.foo.com", equalTo(cookie.getDomain())); assertThat( Date.from(now.atZone(ZoneId.systemDefault()).toInstant()), equalTo(cookie.getExpires())); assertThat(cookie.getMaxAge(), equalTo(1223)); assertThat(cookie.isDiscard(), equalTo(true)); assertThat(cookie.isSecure(), equalTo(true)); assertThat(cookie.isHttpOnly(), equalTo(true)); }
public static void main(String[] args) { LocalDateTime lDT = LocalDateTime.of(LocalDate.of(2016, 01, 17), LocalTime.of(23, 11, 25)); System.out.println("The date and time is : " + lDT.toString()); System.out.println("The strict date is :" + lDT.toLocalDate().toString()); System.out.println("The strict time is :" + lDT.toLocalTime().toString()); }
@Test @WithMockUser(roles = "Tutor") public void currentMonthBalanceMultipleAppointments() throws Exception { Appointment testAppointment1 = new Appointment(); Appointment testAppointment2 = new Appointment(); LocalDateTime dateTime = LocalDateTime.now(); testAppointment1.setAvailability(Availability.ARRANGED); testAppointment1.setTutor(TestUtility.testUser); testAppointment1.setStudent(TestUtility.testUserTwo); testAppointment1.setWage(BigDecimal.TEN); testAppointment1.setDay(dateTime.getDayOfWeek()); testAppointment1.setTimestamp(Timestamp.valueOf(dateTime)); appointmentDao.save(testAppointment1); testAppointment2.setAvailability(Availability.ARRANGED); testAppointment2.setTutor(TestUtility.testUser); testAppointment2.setStudent(TestUtility.testUserTwo); testAppointment2.setWage(BigDecimal.TEN); testAppointment2.setDay(dateTime.getDayOfWeek()); testAppointment2.setTimestamp(Timestamp.valueOf(dateTime.minusHours(1))); appointmentDao.save(testAppointment2); BigDecimal reference = BigDecimal.TEN.multiply(ConstantVariables.PERCENTAGE); reference = reference.add(BigDecimal.TEN.multiply(ConstantVariables.PERCENTAGE)); mockMvc .perform(get("/bill").principal(this.authUser)) .andExpect(model().attribute("balance", reference.setScale(2))); }
// ----------------------------------------------------------------------- // isSupportedBy(TemporalAccessor temporal) and getFrom(TemporalAccessor temporal) // ----------------------------------------------------------------------- @DataProvider(name = "fieldAndAccessor") Object[][] data_fieldAndAccessor() { return new Object[][] { {YEAR, LocalDate.of(2000, 2, 29), true, 2000}, {YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 2000}, {MONTH_OF_YEAR, LocalDate.of(2000, 2, 29), true, 2}, {MONTH_OF_YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 2}, {DAY_OF_MONTH, LocalDate.of(2000, 2, 29), true, 29}, {DAY_OF_MONTH, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 29}, {DAY_OF_YEAR, LocalDate.of(2000, 2, 29), true, 60}, {DAY_OF_YEAR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 60}, {HOUR_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5}, {HOUR_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5}, {MINUTE_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5 * 60 + 4}, {MINUTE_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5 * 60 + 4}, {MINUTE_OF_HOUR, LocalTime.of(5, 4, 3, 200), true, 4}, {MINUTE_OF_HOUR, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 4}, {SECOND_OF_DAY, LocalTime.of(5, 4, 3, 200), true, 5 * 3600 + 4 * 60 + 3}, {SECOND_OF_DAY, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 5 * 3600 + 4 * 60 + 3}, {SECOND_OF_MINUTE, LocalTime.of(5, 4, 3, 200), true, 3}, {SECOND_OF_MINUTE, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 3}, {NANO_OF_SECOND, LocalTime.of(5, 4, 3, 200), true, 200}, {NANO_OF_SECOND, LocalDateTime.of(2000, 2, 29, 5, 4, 3, 200), true, 200}, {YEAR, LocalTime.of(5, 4, 3, 200), false, -1}, {MONTH_OF_YEAR, LocalTime.of(5, 4, 3, 200), false, -1}, {DAY_OF_MONTH, LocalTime.of(5, 4, 3, 200), false, -1}, {DAY_OF_YEAR, LocalTime.of(5, 4, 3, 200), false, -1}, {HOUR_OF_DAY, LocalDate.of(2000, 2, 29), false, -1}, {MINUTE_OF_DAY, LocalDate.of(2000, 2, 29), false, -1}, {MINUTE_OF_HOUR, LocalDate.of(2000, 2, 29), false, -1}, {SECOND_OF_DAY, LocalDate.of(2000, 2, 29), false, -1}, {SECOND_OF_MINUTE, LocalDate.of(2000, 2, 29), false, -1}, {NANO_OF_SECOND, LocalDate.of(2000, 2, 29), false, -1}, }; }
List<String> convert( List<String> inputData, Function<LatLng, Optional<TimeZone>> latLngToTimezone) { return inputData .stream() .map( input -> { final String[] split = input.split(","); String dateTime = split[0]; Double lat = Double.valueOf(split[1]); Double lng = Double.valueOf(split[2]); LatLng latLng = new LatLng(lat, lng); Optional<TimeZone> timeZone = latLngToTimezone.apply(latLng); if (!timeZone.isPresent()) { return "Invalid input"; } LocalDateTime localDateTime = getLocalDateFromUtc(dateTime); String formattedLocalDateTime = localDateTime.toString().replace("T", " "); final String output = input .concat(",") .concat(timeZone.get().getID()) .concat(",") .concat(formattedLocalDateTime); return output; }) .collect(Collectors.toList()); }
@Override public List<Notice> list(String status, LocalDate fromDate, LocalDate toDate, String dongName) throws OperationalException { try { List<Criterion> criteriaList = new ArrayList<>(); if (!StringUtils.isBlank(status) && !status.equalsIgnoreCase(ALL)) { criteriaList.add(Restrictions.eq(STATUS, status)); } if (!StringUtils.isBlank(dongName) && !dongName.equalsIgnoreCase(ALL)) { criteriaList.add(Restrictions.eq("dongName", dongName)); } if (fromDate != null) { LocalTime time = LocalTime.MIDNIGHT; LocalDateTime fromtime = LocalDateTime.of(fromDate, time); criteriaList.add(Restrictions.ge(CREATIONDATE, fromtime)); } if (toDate != null) { LocalTime time = LocalTime.of(23, 59, 59); LocalDateTime totime = LocalDateTime.of(toDate, time); criteriaList.add(Restrictions.le(CREATIONDATE, totime)); } criteriaList.add(Restrictions.ne(STATUS, NoticeStatus.DELETED.name())); return super.findByCriteria(Notice.class, criteriaList, Order.desc(CREATIONDATE)); } catch (Exception e) { LOGGER.error("list: Exception ", e); throw new OperationalException( HttpConstants.INTERNAL_SERVER_ERROR, ResponseConstants.ERROR_FETCHING_FROM_DB, HttpStatus.INTERNAL_SERVER_ERROR); } }
public void localDateTimeTest() { LocalDateTime currentTime = LocalDateTime.now(); System.out.println(currentTime); System.out.println(currentTime.format(formatter)); }
@Test public void testCreerUneSemaineAPartirDe() { PeriodDateHeure unJour = PeriodDateHeure.creerUneSemaineAPartirDe(LocalDateTime.parse("2000-01-01T00:00:00")); Assert.assertEquals(LocalDateTime.parse("2000-01-08T00:00:00"), unJour.getFin()); Assert.assertEquals(LocalDateTime.parse("2000-01-01T00:00:00"), unJour.getDebut()); }
@Test public void startOnHourIncludesThatHour() { assertExpectedSlots( LocalDateTime.of(2015, Month.AUGUST, 27, 9, 0), LocalDateTime.of(2015, Month.AUGUST, 27, 10, 0), 27, 9); }
@Test public void skipsMornings() { assertExpectedSlots( LocalDateTime.of(2015, Month.AUGUST, 28, 8, 0), LocalDateTime.of(2015, Month.AUGUST, 28, 10, 0), 28, 9); }
@Test public void shouldRetrunFalseWhenTimelapseIsEqual() { objectUnderTest = new TimeServiceImpl(1l, TimeUnit.NANOSECONDS); LocalDateTime now = LocalDateTime.now(); LocalDateTime after1Nano = now.plusNanos(1); final boolean timelapseTooHigh = objectUnderTest.isTimelapseTooHigh(now, after1Nano); Assert.assertThat(timelapseTooHigh, CoreMatchers.is(Boolean.FALSE)); }
private String[] setCustomTime(String requestUid, String userInput, User user) { LocalDateTime parsedTime = eventUtil.parseDateTime(userInput); userLogger.recordUserInputtedDateTime( user.getUid(), userInput, "vote-custom", UserInterfaceType.USSD); eventRequestBroker.updateEventDateTime(user.getUid(), requestUid, parsedTime); final String dateTimePrompt = "at " + parsedTime.format(dateTimeFormat); return new String[] {eventRequestBroker.load(requestUid).getName(), dateTimePrompt}; }
private boolean isInSuggestedChangeRange(Event e) { LocalDateTime max = LocalDateTime.now() .minusHours(LocalDateTime.now().getHour()) .plusDays(ServiceVariables.SUGGESTED_CHANGE_RANGE_DAYS_BEFORE_START + 1); return e.getStart().isBefore(max); }
@Test public void testDureeEnMinute() { LocalDateTime debut = LocalDateTime.parse("2000-01-01T14:00:00"); LocalDateTime fin = LocalDateTime.parse("2000-01-01T16:00:00"); PeriodDateHeure periode1 = new PeriodDateHeure(debut, fin); Assert.assertEquals(120.0, periode1.dureeEnMinute(), 0.01); }
private static int timestamp(final LocalDateTime time) { return ((((((((((time.getYear() - 2015) & 3)) << 4) | time.getMonthValue()) << 5) | time.getDayOfMonth()) << 5) | time.getHour()) << 4) | (time.getMinute() / 4); }
public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) { User user = userRepository.findByEmail(request.getEmail()); if (user == null) { throw new EmailNotFoundException(); } LocalDateTime now = LocalDateTime.now(); PasswordResetToken passwordResetToken = new PasswordResetToken(); passwordResetToken.setUser(user); passwordResetToken.setEmail(user.getEmail()); passwordResetToken.setExpiredAt(now.plusHours(24)); passwordResetToken.setCreatedAt(now); passwordResetToken.setCreatedBy(user.toString()); passwordResetToken.setUpdatedAt(now); passwordResetToken.setUpdatedBy(user.toString()); passwordResetToken = passwordResetTokenRepository.saveAndFlush(passwordResetToken); try { Blog blog = blogService.readBlogById(Blog.DEFAULT_ID); String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage()); ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath(); if (blog.isMultiLanguage()) { builder.path("/{language}"); } builder.path("/password-reset"); builder.path("/{token}"); Map<String, Object> urlVariables = new LinkedHashMap<>(); urlVariables.put("language", request.getLanguage()); urlVariables.put("token", passwordResetToken.getToken()); String resetLink = builder.buildAndExpand(urlVariables).toString(); Context ctx = new Context(LocaleContextHolder.getLocale()); ctx.setVariable("passwordResetToken", passwordResetToken); ctx.setVariable("resetLink", resetLink); MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart message.setSubject( MessageFormat.format( messageSourceAccessor.getMessage( "PasswordResetSubject", LocaleContextHolder.getLocale()), blogTitle)); message.setFrom(mailProperties.getProperties().get("mail.from")); message.setTo(passwordResetToken.getEmail()); String htmlContent = templateEngine.process("password-reset", ctx); message.setText(htmlContent, true); // true = isHtml mailSender.send(mimeMessage); } catch (MessagingException e) { throw new ServiceException(e); } return passwordResetToken; }
@CacheEvict(value = "users", allEntries = true) public List<UserInvitation> inviteUsers( UserInvitationCreateRequest form, BindingResult result, AuthorizedUser authorizedUser) throws MessagingException { String[] recipients = StringUtils.commaDelimitedListToStringArray(form.getInvitees()); LocalDateTime now = LocalDateTime.now(); List<UserInvitation> invitations = new ArrayList<>(); for (String recipient : recipients) { UserInvitation invitation = new UserInvitation(); invitation.setEmail(recipient); invitation.setMessage(form.getMessage()); invitation.setExpiredAt(now.plusHours(72)); invitation.setCreatedAt(now); invitation.setCreatedBy(authorizedUser.toString()); invitation.setUpdatedAt(now); invitation.setUpdatedBy(authorizedUser.toString()); invitation = userInvitationRepository.saveAndFlush(invitation); invitations.add(invitation); } Blog blog = blogService.readBlogById(Blog.DEFAULT_ID); for (UserInvitation invitation : invitations) { String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage()); String signupLink = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/_admin/signup") .queryParam("token", invitation.getToken()) .buildAndExpand() .toString(); final Context ctx = new Context(LocaleContextHolder.getLocale()); ctx.setVariable("websiteTitle", websiteTitle); ctx.setVariable("authorizedUser", authorizedUser); ctx.setVariable("signupLink", signupLink); ctx.setVariable("invitation", invitation); final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart message.setSubject( MessageFormat.format( messageSourceAccessor.getMessage( "InvitationMessageTitle", LocaleContextHolder.getLocale()), authorizedUser.toString(), websiteTitle)); message.setFrom(authorizedUser.getEmail()); message.setTo(invitation.getEmail()); final String htmlContent = templateEngine.process("user-invite", ctx); message.setText(htmlContent, true); // true = isHtml mailSender.send(mimeMessage); } return invitations; }
public static void main(String[] args) { LocalDateTime localDateTime = LocalDateTime.of(2016, 3, 27, 1, 20); localDateTime = localDateTime.plusHours(1); System.out.println(localDateTime); ZoneId zoneId = ZoneId.of("Europe/Warsaw"); ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId); System.out.println(zonedDateTime); }
@DataProvider(name = "parseWithoutZoneWithoutOffset") Object[][] data_parse_WithoutOffset_WithoutZone() { return new Object[][] { {"1966-12-31T00:01:10", LocalDateTime.of(1966, 12, 31, 0, 1, 10)}, {"1970-01-01T00:00:00", LocalDateTime.of(1970, 1, 1, 0, 0, 0)}, {"2004-02-29T00:30:00", LocalDateTime.of(2004, 2, 29, 0, 30, 0)}, {"2015-12-31T23:59:59", LocalDateTime.of(2015, 12, 31, 23, 59, 59)} }; }
@Override public void generateToken(VerificationToken verificationToken) { verificationToken.setExpiredTime( LocalDateTime.now().plusSeconds(VerificationToken.EXPIRED_PERIOD)); String unhashedToken = verificationToken.getEmail() + verificationToken.getType() + LocalDateTime.now(); String token = VerificationTokenUtil.getHash(unhashedToken, VerificationTokenUtil.SHA_256); verificationToken.setToken(token); }