Example usage for java.time ZonedDateTime now

List of usage examples for java.time ZonedDateTime now

Introduction

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

Prototype

public static ZonedDateTime now(Clock clock) 

Source Link

Document

Obtains the current date-time from the specified clock.

Usage

From source file:alfio.manager.CheckInManager.java

private TicketAndCheckInResult extractStatus(Optional<Event> maybeEvent, Optional<Ticket> maybeTicket,
        String ticketIdentifier, Optional<String> ticketCode) {

    if (!maybeEvent.isPresent()) {
        return new TicketAndCheckInResult(null, new DefaultCheckInResult(EVENT_NOT_FOUND, "Event not found"));
    }/*w w w . ja v  a2s  . co m*/

    if (!maybeTicket.isPresent()) {
        return new TicketAndCheckInResult(null, new DefaultCheckInResult(TICKET_NOT_FOUND,
                "Ticket with uuid " + ticketIdentifier + " not found"));
    }

    if (!ticketCode.filter(StringUtils::isNotEmpty).isPresent()) {
        return new TicketAndCheckInResult(null,
                new DefaultCheckInResult(EMPTY_TICKET_CODE, "Missing ticket code"));
    }

    Ticket ticket = maybeTicket.get();
    Event event = maybeEvent.get();
    String code = ticketCode.get();

    TicketCategory tc = ticketCategoryRepository.getById(ticket.getCategoryId());

    ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    if (!tc.hasValidCheckIn(now, event.getZoneId())) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm");
        String from = tc.getValidCheckInFrom() == null ? ".."
                : formatter.format(tc.getValidCheckInFrom(event.getZoneId()));
        String to = tc.getValidCheckInTo() == null ? ".."
                : formatter.format(tc.getValidCheckInTo(event.getZoneId()));
        String formattedNow = formatter.format(now);
        return new TicketAndCheckInResult(ticket,
                new DefaultCheckInResult(INVALID_TICKET_CATEGORY_CHECK_IN_DATE, String.format(
                        "Invalid check-in date: valid range for category %s is from %s to %s, current time is: %s",
                        tc.getName(), from, to, formattedNow)));
    }

    log.trace("scanned code is {}", code);
    log.trace("true code    is {}", ticket.ticketCode(event.getPrivateKey()));

    if (!code.equals(ticket.ticketCode(event.getPrivateKey()))) {
        return new TicketAndCheckInResult(null,
                new DefaultCheckInResult(INVALID_TICKET_CODE, "Ticket qr code does not match"));
    }

    final TicketStatus ticketStatus = ticket.getStatus();

    if (ticketStatus == TicketStatus.TO_BE_PAID) {
        return new TicketAndCheckInResult(ticket, new OnSitePaymentResult(MUST_PAY, "Must pay for ticket",
                MonetaryUtil.centsToUnit(ticket.getFinalPriceCts()), event.getCurrency()));
    }

    if (ticketStatus == TicketStatus.CHECKED_IN) {
        return new TicketAndCheckInResult(ticket,
                new DefaultCheckInResult(ALREADY_CHECK_IN, "Error: already checked in"));
    }

    if (ticket.getStatus() != TicketStatus.ACQUIRED) {
        return new TicketAndCheckInResult(ticket, new DefaultCheckInResult(INVALID_TICKET_STATE,
                "Invalid ticket state, expected ACQUIRED state, received " + ticket.getStatus()));
    }

    return new TicketAndCheckInResult(ticket,
            new DefaultCheckInResult(OK_READY_TO_BE_CHECKED_IN, "Ready to be checked in"));
}

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

@Test
public void getUserWeekActivityOverviews_activityPresent_resultsWithActivity() {
    ZonedDateTime today = getDayStartTime(ZonedDateTime.now(userAnonZone));

    // gambling goal was created 2 weeks ago, see above
    // mock some activity in previous week on Saturday 19:10-19:55
    WeekActivity previousWeekRecordedActivity = WeekActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, getWeekStartTime(today.minusWeeks(1)).toLocalDate());
    ZonedDateTime saturdayStartOfDay = getWeekStartTime(today).minusDays(1);
    DayActivity previousWeekSaturdayRecordedActivity = DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, saturdayStartOfDay.toLocalDate());
    Activity recordedActivity = Activity.createInstance(userAnonZone,
            saturdayStartOfDay.plusHours(19).plusMinutes(10).toLocalDateTime(),
            saturdayStartOfDay.plusHours(19).plusMinutes(55).toLocalDateTime(), Optional.empty());
    previousWeekSaturdayRecordedActivity.addActivity(recordedActivity);
    previousWeekRecordedActivity.addDayActivity(DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, getWeekStartTime(today).minusDays(7).toLocalDate()));
    previousWeekRecordedActivity.addDayActivity(DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, getWeekStartTime(today).minusDays(6).toLocalDate()));
    previousWeekRecordedActivity.addDayActivity(DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, getWeekStartTime(today).minusDays(5).toLocalDate()));
    previousWeekRecordedActivity.addDayActivity(DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, getWeekStartTime(today).minusDays(4).toLocalDate()));
    previousWeekRecordedActivity.addDayActivity(DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, getWeekStartTime(today).minusDays(3).toLocalDate()));
    previousWeekRecordedActivity.addDayActivity(DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, getWeekStartTime(today).minusDays(2).toLocalDate()));
    previousWeekRecordedActivity.addDayActivity(previousWeekSaturdayRecordedActivity);

    when(mockWeekActivityRepository.findAll(userAnonId, getWeekStartTime(today.minusWeeks(4)).toLocalDate(),
            getWeekStartTime(today).plusWeeks(1).toLocalDate()))
                    .thenReturn(new HashSet<>(Arrays.asList(previousWeekRecordedActivity)));

    Page<WeekActivityOverviewDto> weekOverviews = service.getUserWeekActivityOverviews(userId,
            new PageRequest(0, 5));

    // assert that the right retrieve from database was done
    verify(mockWeekActivityRepository, times(1)).findAll(userAnonId,
            getWeekStartTime(today.minusWeeks(4)).toLocalDate(),
            getWeekStartTime(today).plusWeeks(1).toLocalDate());

    // because the gambling goal was added with creation date two weeks ago, there are multiple weeks
    assertThat(weekOverviews.getNumberOfElements(), equalTo(3));

    // get the current week (first item)
    WeekActivityOverviewDto weekOverview = weekOverviews.getContent().get(0);
    assertThat(weekOverview.getWeekActivities().size(), equalTo(userAnonEntity.getGoals().size()));
    WeekActivityDto weekActivityForGambling = weekOverview.getWeekActivities().stream()
            .filter(a -> a.getGoalId().equals(gamblingGoal.getId())).findAny().get();
    assertThat(weekActivityForGambling.getStartTime(), equalTo(getWeekStartTime(today)));
    // TODO: mock day activity in this week?
    // int thisWeekNumberOfWeekDaysPast = today.getDayOfWeek() == DayOfWeek.SUNDAY ? 0 : today.getDayOfWeek().getValue();
    // assertThat(weekActivityForGambling.getDayActivities().size(), equalTo(1 + thisWeekNumberOfWeekDaysPast));
    //// always contains Sunday because it is the first day of the week
    // assertThat(weekActivityForGambling.getDayActivities(), hasKey(DayOfWeek.SUNDAY));

    // get the previous week, with recorded activity
    weekOverview = weekOverviews.getContent().get(1);
    assertThat(weekOverview.getWeekActivities().size(), equalTo(1));
    weekActivityForGambling = weekOverview.getWeekActivities().stream()
            .filter(a -> a.getGoalId().equals(gamblingGoal.getId())).findAny().get();
    assertThat(weekActivityForGambling.getStartTime(), equalTo(getWeekStartTime(today.minusWeeks(1))));
    assertThat(weekActivityForGambling.getDayActivities().size(), equalTo(7));
    DayActivityDto previousWeekSaturdayActivity = weekActivityForGambling.getDayActivities()
            .get(DayOfWeek.SATURDAY);
    assertThat(previousWeekSaturdayActivity.getTotalActivityDurationMinutes().get(), equalTo(45));
    assertThat(previousWeekSaturdayActivity.getTotalMinutesBeyondGoal(), equalTo(45));
    DayActivityDto previousWeekFridayActivity = weekActivityForGambling.getDayActivities()
            .get(DayOfWeek.FRIDAY);
    assertThat(previousWeekFridayActivity.getTotalActivityDurationMinutes().get(), equalTo(0));

    // get the week the gambling goal was created
    weekOverview = weekOverviews.getContent().get(2);
    assertThat(weekOverview.getWeekActivities().size(), equalTo(1));
    weekActivityForGambling = weekOverview.getWeekActivities().stream()
            .filter(a -> a.getGoalId().equals(gamblingGoal.getId())).findAny().get();
    assertThat(weekActivityForGambling.getStartTime(), equalTo(getWeekStartTime(today.minusWeeks(2))));
    // TODO: mock day activity in this week?
    // int expectedNumberOfWeekDaysRecorded = gamblingGoal.getCreationTime().getDayOfWeek() == DayOfWeek.SUNDAY ? 7
    // : 7 - gamblingGoal.getCreationTime().getDayOfWeek().getValue();
    // assertThat(weekActivityForGambling.getDayActivities().size(), equalTo(expectedNumberOfWeekDaysRecorded));
    //// always contains Saturday because it is the last day of the week
    // assertThat(weekActivityForGambling.getDayActivities(), hasKey(DayOfWeek.SATURDAY));
}

From source file:alfio.manager.NotificationManager.java

public void sendTicketByEmail(Ticket ticket, Event event, Locale locale, PartialTicketTextGenerator textBuilder,
        TicketReservation reservation, TicketCategory ticketCategory) throws IOException {

    Organization organization = organizationRepository.getById(event.getOrganizationId());

    List<Mailer.Attachment> attachments = new ArrayList<>();
    attachments.add(/*from   w w w .ja v  a 2  s  .c  om*/
            CustomMessageManager.generateTicketAttachment(ticket, reservation, ticketCategory, organization));

    String encodedAttachments = encodeAttachments(
            attachments.toArray(new Mailer.Attachment[attachments.size()]));
    String subject = messageSource.getMessage("ticket-email-subject", new Object[] { event.getDisplayName() },
            locale);
    String text = textBuilder.generate(ticket);
    String checksum = calculateChecksum(ticket.getEmail(), encodedAttachments, subject, text);
    String recipient = ticket.getEmail();
    //TODO handle HTML
    tx.execute(status -> emailMessageRepository.insert(event.getId(), recipient, null, subject, text,
            encodedAttachments, checksum, ZonedDateTime.now(UTC)));
}

From source file:com.example.app.profile.model.ProfileDAO.java

/**
 * Create an save a ProfileDatedRecord for the given Profile, category, and subcategory.
 * Uses LocalDateTime.now() for the date, at UTC.
 *
 * @param profile the Profile/*from w  w  w .ja v  a  2s.  c  om*/
 * @param category the category
 * @param subCategory the subcategory
 *
 * @return the new ProfileDatedRecord
 */
public ProfileDatedRecord createProfileDatedRecord(Profile profile, String category,
        @Nullable String subCategory) {
    ProfileDatedRecord pdr = new ProfileDatedRecord();
    pdr.setProfile(profile);
    pdr.setDate(convertForPersistence(ZonedDateTime.now(ZoneOffset.UTC)));
    pdr.setCategory(category);
    pdr.setSubCategory(subCategory);
    saveProfileDatedRecord(pdr);
    return pdr;
}

From source file:com.example.app.profile.ui.user.UserPropertyEditor.java

@SuppressWarnings("Duplicates")
@Override/*from   w  ww  .ja  va  2 s .  com*/
public void init() {
    super.init();

    NavigationAction saveAction = CommonActions.SAVE.navAction();
    saveAction.onCondition(input -> persist(user -> {
        assert user != null : "User should not be null if you are persisting!";
        UserValueEditor editor = getValueEditor();
        User currentUser = _userDAO.getAssertedCurrentUser();
        _sessionHelper.beginTransaction();
        boolean success = false;
        try {
            if (Objects.equals(currentUser.getId(), user.getId())) {
                user.setPreferredContactMethod(editor.commitValuePreferredContactMethod());

                final Link link = editor.commitValueLoginLandingPage();
                if (link != null) {
                    Preferences userPref = Preferences.userRoot().node(User.LOGIN_PREF_NODE);
                    userPref.put(User.LOGIN_PREF_NODE_LANDING_PAGE, link.getURIAsString());
                }
            }

            user = _userDAO.mergeUser(user);
            try {
                boolean result = true;
                EmailAddress emailAddress = ContactUtil
                        .getEmailAddress(user.getPrincipal().getContact(), ContactDataCategory.values())
                        .orElseThrow(() -> new IllegalStateException(
                                "Email Address was null on PrincipalValueEditor.  This should not happen."));
                if (user.getPrincipal().getPasswordCredentials() == null) {
                    String randomPassword = UUID.randomUUID().toString();

                    List<Notification> notifications = new ArrayList<>();

                    result = _principalDAO.setNewPassword(user.getPrincipal(), emailAddress.getEmail(),
                            notifications, randomPassword);

                    if (result) {
                        user.setPrincipal(_er.reattachIfNecessary(user.getPrincipal()));

                        user.getPrincipal().getCredentials().forEach(cred -> {
                            if (_er.narrowProxyIfPossible(cred) instanceof PasswordCredentials) {
                                Calendar cal = Calendar.getInstance();
                                cal.add(Calendar.DAY_OF_YEAR, -10);
                                cred.setExpireDate(cal.getTime());
                            }
                        });

                        _principalDAO.savePrincipal(user.getPrincipal());
                    } else {
                        final Notifiable notifiable = getNotifiable();
                        notifications.forEach(notifiable::sendNotification);
                    }
                } else {
                    PasswordCredentials creds = user.getPrincipal().getPasswordCredentials();
                    creds.setUsername(emailAddress.getEmail());
                    _principalDAO.savePrincipal(user.getPrincipal());
                }
                if (!_principalDAO.getAllRoles(user.getPrincipal())
                        .contains(_appUtil.getFrontEndAccessRole())) {
                    user.getPrincipal().getChildren().add(_appUtil.getFrontEndAccessRole());
                    _principalDAO.savePrincipal(user.getPrincipal());
                }
                user = _userDAO.mergeUser(user);
                Company userProfile = _uiPreferences.getSelectedCompany();
                if (userProfile != null && !userProfile.getUsers().contains(user) && _newUser) {
                    _companyDAO.addUserToCompany(userProfile, user);

                    List<MembershipType> coachingMemTypes = editor.commitValueCoachingMemType();
                    final User finalUser = user;
                    coachingMemTypes.forEach(coachingMemType -> _profileDAO.saveMembership(
                            _profileDAO.createMembership(userProfile, finalUser, coachingMemType,
                                    ZonedDateTime.now(getSession().getTimeZone().toZoneId()), true)));
                }

                if (editor.getPictureEditor().getModificationState().isModified()) {
                    _userDAO.saveUserImage(user, editor.getPictureEditor().commitValue());
                }

                success = result;
                if (success) {
                    setSaved(user);
                }
            } catch (NonUniqueCredentialsException e) {
                _logger.error("Unable to persist changes to the Principal.", e);
                getNotifiable().sendNotification(error(ERROR_MESSAGE_USERNAME_EXISTS_FMT(USER())));
            }
            _sessionHelper.commitTransaction();
        } finally {
            if (!success)
                _sessionHelper.recoverableRollbackTransaction();
        }
        if (success) {
            _uiPreferences.addMessage(
                    new NotificationImpl(NotificationType.INFO, INFO_SHOULD_PICK_ONE_ROLE_NEW_USER()));
        }
        return success;
    }));
    saveAction.configure().toPage(ApplicationFunctions.User.VIEW).withSourceComponent(this);
    saveAction.setPropertyValueResolver(new CurrentURLPropertyValueResolver() {
        @Override
        public Map<String, Object> resolve(PropertyValueResolverParameter parameter) {
            Map<String, Object> map = super.resolve(parameter);
            map.put(URLProperties.USER, _saved);
            return map;
        }
    });
    saveAction.setTarget(this, "close");

    NavigationAction cancelAction = CommonActions.CANCEL.navAction();
    cancelAction.configure().toReturnPath(ApplicationFunctions.User.MANAGEMENT).usingCurrentURLData()
            .withSourceComponent(this);
    cancelAction.setTarget(this, "close");

    setPersistenceActions(saveAction, cancelAction);

    _notifications.forEach(notification -> getNotifiable().sendNotification(notification));
}

From source file:it.tidalwave.northernwind.frontend.media.impl.DefaultMetadataCacheTest.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
private void setTime(final @Nonnull ZonedDateTime dateTime) {
    mockClock = Clock.fixed(dateTime.toInstant(), dateTime.getZone());
    log.info("==== Time set to           {}", ZonedDateTime.now(mockClock));
}

From source file:com.example.app.profile.ui.user.UserMembershipManagement.java

private MenuItem getProfileMenuItem(Profile profile) {
    final Profile finalProfile = profile;
    TextSource profileText = TextSources.createTextForAny(profile);
    MenuItem subMenu;// www.jav a 2  s.  c o  m
    //noinspection ConstantConditions
    if (profile.getProfileType() != null && !profile.getProfileType().getMembershipTypeSet().isEmpty()) {
        subMenu = new Menu(profileText);
        profile.getProfileType().getMembershipTypeSet().stream()
                .sorted(new NamedObjectComparator(getLocaleContext())).forEach(memType -> {
                    MenuItem memTypeItem = new MenuItem(TextSources.createTextForAny(memType));
                    memTypeItem.addActionListener(ev -> {
                        _profileDAO.saveMembership(_profileDAO.createMembership(finalProfile, getUser(),
                                memType, ZonedDateTime.now(getSession().getTimeZone().toZoneId()), true));
                        _searchUI.doAction(SearchUIAction.search);
                    });
                    ((Menu) subMenu).add(memTypeItem);
                });
    } else {
        subMenu = new MenuItem(profileText);
        subMenu.addActionListener(ev -> {
            _profileDAO.saveMembership(_profileDAO.createMembership(finalProfile, getUser(), null,
                    ZonedDateTime.now(getSession().getTimeZone().toZoneId()), true));
            _searchUI.doAction(SearchUIAction.search);
        });
    }
    return subMenu;
}

From source file:alfio.manager.NotificationManager.java

public void sendSimpleEmail(Event event, String recipient, List<String> cc, String subject,
        TextTemplateGenerator textBuilder, List<Mailer.Attachment> attachments) {

    String encodedAttachments = attachments.isEmpty() ? null
            : encodeAttachments(attachments.toArray(new Mailer.Attachment[attachments.size()]));
    String encodedCC = Json.toJson(cc);

    String text = textBuilder.generate();
    String checksum = calculateChecksum(recipient, encodedAttachments, subject, text);
    //in order to minimize the database size, it is worth checking if there is already another message in the table
    Optional<EmailMessage> existing = emailMessageRepository.findByEventIdAndChecksum(event.getId(), checksum);
    if (!existing.isPresent()) {
        emailMessageRepository.insert(event.getId(), recipient, encodedCC, subject, text, encodedAttachments,
                checksum, ZonedDateTime.now(UTC));
    } else {//  ww  w  .j  av  a 2  s. co m
        emailMessageRepository.updateStatus(event.getId(), WAITING.name(), existing.get().getId());
    }
}

From source file:alfio.manager.WaitingQueueManager.java

private Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> distributeAvailableSeats(
        Event event, Ticket.TicketStatus status, Supplier<Integer> availableSeatSupplier) {
    int availableSeats = availableSeatSupplier.get();
    int eventId = event.getId();
    log.debug("processing {} subscribers from waiting queue", availableSeats);
    List<TicketCategory> unboundedCategories = ticketCategoryRepository
            .findUnboundedOrderByExpirationDesc(eventId);
    Iterator<Ticket> tickets = ticketRepository
            .selectWaitingTicketsForUpdate(eventId, status.name(), availableSeats).stream()
            .filter(t -> t.getCategoryId() != null || unboundedCategories.size() > 0).iterator();
    int expirationTimeout = configurationManager.getIntConfigValue(
            Configuration.from(event.getOrganizationId(), event.getId(), WAITING_QUEUE_RESERVATION_TIMEOUT), 4);
    ZonedDateTime expiration = ZonedDateTime.now(event.getZoneId()).plusHours(expirationTimeout)
            .with(WorkingDaysAdjusters.defaultWorkingDays());

    if (!tickets.hasNext()) {
        log.warn("Unable to assign tickets, returning an empty stream");
        return Stream.empty();
    }/*from  w  w w  . ja  v a2s .c om*/
    return waitingQueueRepository.loadWaiting(eventId, availableSeats).stream()
            .map(wq -> Pair.of(wq, tickets.next())).map(pair -> {
                TicketReservationModification ticketReservation = new TicketReservationModification();
                ticketReservation.setAmount(1);
                Integer categoryId = Optional.ofNullable(pair.getValue().getCategoryId())
                        .orElseGet(() -> findBestCategory(unboundedCategories, pair.getKey())
                                .orElseThrow(RuntimeException::new).getId());
                ticketReservation.setTicketCategoryId(categoryId);
                return Pair.of(pair.getLeft(), new TicketReservationWithOptionalCodeModification(
                        ticketReservation, Optional.<SpecialPrice>empty()));
            }).map(pair -> Triple.of(pair.getKey(), pair.getValue(), expiration));
}