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:org.apache.openmeetings.web.user.calendar.CalendarPanel.java

@Override
protected void onInitialize() {
    final Form<Date> form = new Form<>("form");
    add(form);//  w w w  .  j  av  a 2 s  .com

    dialog = new AppointmentDialog("appointment", this, new CompoundPropertyModel<>(getDefault()));
    add(dialog);

    boolean isRtl = isRtl();
    Options options = new Options();
    options.set("isRTL", isRtl);
    options.set("height", Options.asString("parent"));
    options.set("header", isRtl
            ? "{left: 'agendaDay,agendaWeek,month', center: 'title', right: 'today nextYear,next,prev,prevYear'}"
            : "{left: 'prevYear,prev,next,nextYear today', center: 'title', right: 'month,agendaWeek,agendaDay'}");
    options.set("allDaySlot", false);
    options.set("axisFormat", Options.asString("H(:mm)"));
    options.set("defaultEventMinutes", 60);
    options.set("timeFormat", Options.asString("H(:mm)"));

    options.set("buttonText", new JSONObject().put("month", getString("801")).put("week", getString("800"))
            .put("day", getString("799")).put("today", getString("1555")).toString());

    options.set("locale", Options.asString(WebSession.get().getLocale().toLanguageTag()));

    calendar = new Calendar("calendar", new AppointmentModel(), options) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onInitialize() {
            super.onInitialize();
            add(new CalendarFunctionsBehavior(getMarkupId()));
        }

        @Override
        public boolean isSelectable() {
            return true;
        }

        @Override
        public boolean isDayClickEnabled() {
            return true;
        }

        @Override
        public boolean isEventClickEnabled() {
            return true;
        }

        @Override
        public boolean isEventDropEnabled() {
            return true;
        }

        @Override
        public boolean isEventResizeEnabled() {
            return true;
        }

        //no need to override onDayClick
        @Override
        public void onSelect(AjaxRequestTarget target, CalendarView view, LocalDateTime start,
                LocalDateTime end, boolean allDay) {
            Appointment a = getDefault();
            LocalDateTime s = start, e = end;
            if (CalendarView.month == view) {
                LocalDateTime now = ZonedDateTime.now(getZoneId()).toLocalDateTime();
                s = start.withHour(now.getHour()).withMinute(now.getMinute());
                e = s.plus(1, ChronoUnit.HOURS);
            }
            a.setStart(getDate(s));
            a.setEnd(getDate(e));
            dialog.setModelObjectWithAjaxTarget(a, target);

            dialog.open(target);
        }

        @Override
        public void onEventClick(AjaxRequestTarget target, CalendarView view, String eventId) {
            if (!StringUtils.isNumeric(eventId)) {
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            dialog.setModelObjectWithAjaxTarget(a, target);

            dialog.open(target);
        }

        @Override
        public void onEventDrop(AjaxRequestTarget target, String eventId, long delta, boolean allDay) {
            if (!StringUtils.isNumeric(eventId)) {
                refresh(target);
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            if (!AppointmentDialog.isOwner(a)) {
                return;
            }
            java.util.Calendar cal = WebSession.getCalendar();
            cal.setTime(a.getStart());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setStart(cal.getTime());

            cal.setTime(a.getEnd());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setEnd(cal.getTime());

            apptDao.update(a, getUserId());

            if (a.getCalendar() != null) {
                updatedeleteAppointment(target, CalendarDialog.DIALOG_TYPE.UPDATE_APPOINTMENT, a);
            }
        }

        @Override
        public void onEventResize(AjaxRequestTarget target, String eventId, long delta) {
            if (!StringUtils.isNumeric(eventId)) {
                refresh(target);
                return;
            }
            Appointment a = apptDao.get(Long.valueOf(eventId));
            if (!AppointmentDialog.isOwner(a)) {
                return;
            }
            java.util.Calendar cal = WebSession.getCalendar();
            cal.setTime(a.getEnd());
            cal.add(java.util.Calendar.MILLISECOND, (int) delta);
            a.setEnd(cal.getTime());

            apptDao.update(a, getUserId());

            if (a.getCalendar() != null) {
                updatedeleteAppointment(target, CalendarDialog.DIALOG_TYPE.UPDATE_APPOINTMENT, a);
            }
        }
    };

    form.add(calendar);

    populateGoogleCalendars();

    add(refreshTimer);
    add(syncTimer);

    calendarDialog = new CalendarDialog("calendarDialog", this,
            new CompoundPropertyModel<>(getDefaultCalendar()));

    add(calendarDialog);

    calendarListContainer.setOutputMarkupId(true);
    calendarListContainer
            .add(new ListView<OmCalendar>("items", new LoadableDetachableModel<List<OmCalendar>>() {
                private static final long serialVersionUID = 1L;

                @Override
                protected List<OmCalendar> load() {
                    List<OmCalendar> cals = new ArrayList<>(apptManager.getCalendars(getUserId()));
                    cals.addAll(apptManager.getGoogleCalendars(getUserId()));
                    return cals;
                }
            }) {
                private static final long serialVersionUID = 1L;

                @Override
                protected void populateItem(final ListItem<OmCalendar> item) {
                    item.setOutputMarkupId(true);
                    final OmCalendar cal = item.getModelObject();
                    item.add(new WebMarkupContainer("item").add(new Label("name", cal.getTitle())));
                    item.add(new AjaxEventBehavior(EVT_CLICK) {
                        private static final long serialVersionUID = 1L;

                        @Override
                        protected void onEvent(AjaxRequestTarget target) {
                            calendarDialog.open(target, CalendarDialog.DIALOG_TYPE.UPDATE_CALENDAR, cal);
                            target.add(calendarDialog);
                        }
                    });
                }
            });

    add(new Button("syncCalendarButton").add(new AjaxEventBehavior(EVT_CLICK) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            syncCalendar(target);
        }
    }));

    add(new Button("submitCalendar").add(new AjaxEventBehavior(EVT_CLICK) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onEvent(AjaxRequestTarget target) {
            calendarDialog.open(target, CalendarDialog.DIALOG_TYPE.UPDATE_CALENDAR, getDefaultCalendar());
            target.add(calendarDialog);
        }
    }));

    add(calendarListContainer);

    super.onInitialize();
}

From source file:com.baasbox.controllers.actions.filters.WrapResponse.java

private void setServerTime(Http.Response response) {
    ZonedDateTime date = ZonedDateTime.now(ZoneId.of("GMT"));
    String httpDate = DateTimeFormatter.RFC_1123_DATE_TIME.format(date);
    response.setHeader("Date", httpDate);
}

From source file:alfio.model.Event.java

public boolean expiredSince(int days) {
    return ZonedDateTime.now(getZoneId()).truncatedTo(ChronoUnit.DAYS).minusDays(days)
            .isAfter(getEnd().truncatedTo(ChronoUnit.DAYS));
}

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

@Test
public void getUserDayActivityOverviews_activityPresent_resultsWithActivity() {
    ZonedDateTime today = getDayStartTime(ZonedDateTime.now(userAnonZone));
    ZonedDateTime yesterday = today.minusDays(1);

    // gambling goal was created 2 weeks ago, see above
    // mock some activity on yesterday 20:58-21:00
    DayActivity yesterdayRecordedActivity = DayActivity.createInstance(userAnonEntity, gamblingGoal,
            userAnonZone, yesterday.toLocalDate());
    Activity recordedActivity = Activity.createInstance(userAnonZone,
            yesterday.plusHours(20).plusMinutes(58).toLocalDateTime(),
            yesterday.plusHours(21).plusMinutes(00).toLocalDateTime(), Optional.empty());
    yesterdayRecordedActivity.addActivity(recordedActivity);
    Set<UUID> relevantGoalIds = userAnonEntity.getGoals().stream().map(Goal::getId).collect(Collectors.toSet());
    when(mockDayActivityRepository.findAll(userAnonId, relevantGoalIds, today.minusDays(2).toLocalDate(),
            today.plusDays(1).toLocalDate())).thenReturn(Arrays.asList(yesterdayRecordedActivity));

    Page<DayActivityOverviewDto<DayActivityDto>> dayOverviews = service.getUserDayActivityOverviews(userId,
            new PageRequest(0, 3));

    // assert that the right retrieve from database was done
    verify(mockDayActivityRepository, times(1)).findAll(userAnonId, relevantGoalIds,
            today.minusDays(2).toLocalDate(), today.plusDays(1).toLocalDate());

    // because the gambling goal was added with creation date two weeks ago, there are multiple days, equal to the limit of
    // our page request = 3
    assertThat(dayOverviews.getNumberOfElements(), equalTo(3));

    // get the current day (first item)
    DayActivityOverviewDto<DayActivityDto> dayOverview = dayOverviews.getContent().get(0);
    assertThat(dayOverview.getDayActivities().size(), equalTo(userAnonEntity.getGoals().size()));
    DayActivityDto dayActivityForGambling = dayOverview.getDayActivities().stream()
            .filter(a -> a.getGoalId().equals(gamblingGoal.getId())).findAny().get();
    assertThat(dayActivityForGambling.getStartTime(), equalTo(today));
    assertThat(dayActivityForGambling.getTotalActivityDurationMinutes().get(), equalTo(0));
    assertThat(dayActivityForGambling.getTotalMinutesBeyondGoal(), equalTo(0));

    // get yesterday, with recorded activity
    dayOverview = dayOverviews.getContent().get(1);
    assertThat(dayOverview.getDayActivities().size(), equalTo(1));
    dayActivityForGambling = dayOverview.getDayActivities().stream()
            .filter(a -> a.getGoalId().equals(gamblingGoal.getId())).findAny().get();
    assertThat(dayActivityForGambling.getStartTime(), equalTo(yesterday));
    assertThat(dayActivityForGambling.getTotalActivityDurationMinutes().get(), equalTo(2));
    assertThat(dayActivityForGambling.getTotalMinutesBeyondGoal(), equalTo(2));
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testMigrationWithExistingRecord() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {/*from   ww  w  .  j a v a  2 s  .co  m*/
        eventMigrationRepository.insertMigrationData(event.getId(), "1.4",
                ZonedDateTime.now(ZoneId.of("UTC")).minusDays(1), EventMigration.Status.COMPLETE.toString());
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);
        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(buildTimestamp, eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(20, tickets.size());
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:org.openrepose.filters.custom.extractdeviceid.ExtractDeviceIdFilter.java

static String getRetryString(Header[] headers, int statusCode) {
    String rtn;/*from  w w  w . ja v  a  2  s .  c om*/
    Object[] retryHeaders = Arrays.stream(headers).filter(header -> header.getName().equals(RETRY_AFTER))
            .toArray();
    if (retryHeaders.length < 1) {
        LOG.info("Missing {} header on Auth Response status code: {}", RETRY_AFTER, statusCode);
        final ZonedDateTime zdt = ZonedDateTime.now(Clock.systemUTC());
        zdt.plusSeconds(5);
        rtn = zdt.format(RFC_1123_DATE_TIME);
    } else {
        rtn = ((Header) retryHeaders[0]).getValue();
    }
    return rtn;
}

From source file:alfio.controller.EventController.java

@RequestMapping(value = "/event/{eventName}", method = { RequestMethod.GET, RequestMethod.HEAD })
public String showEvent(@PathVariable("eventName") String eventName, Model model, HttpServletRequest request,
        Locale locale) {/*from w w  w.  j  ava2 s. c o m*/

    return eventRepository.findOptionalByShortName(eventName)
            .filter(e -> e.getStatus() != Event.Status.DISABLED).map(event -> {
                Optional<String> maybeSpecialCode = SessionUtil.retrieveSpecialPriceCode(request);
                Optional<SpecialPrice> specialCode = maybeSpecialCode
                        .flatMap((trimmedCode) -> specialPriceRepository.getByCode(trimmedCode));

                Optional<PromoCodeDiscount> promoCodeDiscount = SessionUtil
                        .retrievePromotionCodeDiscount(request).flatMap((code) -> promoCodeRepository
                                .findPromoCodeInEventOrOrganization(event.getId(), code));

                final ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
                //hide access restricted ticket categories
                List<TicketCategory> ticketCategories = ticketCategoryRepository
                        .findAllTicketCategories(event.getId());
                Map<Integer, String> categoriesDescription = ticketCategoryDescriptionRepository
                        .descriptionsByTicketCategory(ticketCategories.stream().map(TicketCategory::getId)
                                .collect(Collectors.toList()), locale.getLanguage());

                List<SaleableTicketCategory> saleableTicketCategories = ticketCategories.stream()
                        .filter((c) -> !c.isAccessRestricted() || (specialCode
                                .filter(sc -> sc.getTicketCategoryId() == c.getId()).isPresent()))
                        .map((m) -> new SaleableTicketCategory(m,
                                categoriesDescription.getOrDefault(m.getId(), ""), now, event,
                                ticketReservationManager.countAvailableTickets(event, m),
                                configurationManager.getIntConfigValue(
                                        Configuration.from(event.getOrganizationId(), event.getId(), m.getId(),
                                                ConfigurationKeys.MAX_AMOUNT_OF_TICKETS_BY_RESERVATION),
                                        5),
                                promoCodeDiscount.filter(promoCode -> shouldApplyDiscount(promoCode, m))
                                        .orElse(null)))
                        .collect(Collectors.toList());
                //

                final int orgId = event.getOrganizationId();
                final int eventId = event.getId();
                Map<ConfigurationKeys, Optional<String>> geoInfoConfiguration = configurationManager
                        .getStringConfigValueFrom(
                                Configuration.from(orgId, eventId, ConfigurationKeys.MAPS_PROVIDER),
                                Configuration.from(orgId, eventId, ConfigurationKeys.MAPS_CLIENT_API_KEY),
                                Configuration.from(orgId, eventId, ConfigurationKeys.MAPS_HERE_APP_ID),
                                Configuration.from(orgId, eventId, ConfigurationKeys.MAPS_HERE_APP_CODE));

                LocationDescriptor ld = LocationDescriptor.fromGeoData(event.getLatLong(),
                        TimeZone.getTimeZone(event.getTimeZone()), geoInfoConfiguration);

                final boolean hasAccessPromotions = ticketCategoryRepository
                        .countAccessRestrictedRepositoryByEventId(event.getId()) > 0
                        || promoCodeRepository.countByEventAndOrganizationId(event.getId(),
                                event.getOrganizationId()) > 0;

                String eventDescription = eventDescriptionRepository
                        .findDescriptionByEventIdTypeAndLocale(event.getId(),
                                EventDescription.EventDescriptionType.DESCRIPTION, locale.getLanguage())
                        .orElse("");

                final EventDescriptor eventDescriptor = new EventDescriptor(event, eventDescription);
                List<SaleableTicketCategory> expiredCategories = saleableTicketCategories.stream()
                        .filter(SaleableTicketCategory::getExpired).collect(Collectors.toList());
                List<SaleableTicketCategory> validCategories = saleableTicketCategories.stream()
                        .filter(tc -> !tc.getExpired()).collect(Collectors.toList());
                List<SaleableAdditionalService> additionalServices = additionalServiceRepository
                        .loadAllForEvent(event.getId()).stream().map((as) -> getSaleableAdditionalService(event,
                                locale, as, promoCodeDiscount.orElse(null)))
                        .collect(Collectors.toList());
                Predicate<SaleableTicketCategory> waitingQueueTargetCategory = tc -> !tc.getExpired()
                        && !tc.isBounded();
                boolean validPaymentConfigured = isEventHasValidPaymentConfigurations(event,
                        configurationManager);

                List<SaleableAdditionalService> notExpiredServices = additionalServices.stream()
                        .filter(SaleableAdditionalService::isNotExpired).collect(Collectors.toList());

                List<SaleableAdditionalService> supplements = adjustIndex(0,
                        notExpiredServices.stream()
                                .filter(a -> a.getType() == AdditionalService.AdditionalServiceType.SUPPLEMENT)
                                .collect(Collectors.toList()));
                List<SaleableAdditionalService> donations = adjustIndex(supplements.size(),
                        notExpiredServices.stream()
                                .filter(a -> a.getType() == AdditionalService.AdditionalServiceType.DONATION)
                                .collect(Collectors.toList()));

                model.addAttribute("event", eventDescriptor)//
                        .addAttribute("organization", organizationRepository.getById(event.getOrganizationId()))
                        .addAttribute("ticketCategories", validCategories)//
                        .addAttribute("expiredCategories", expiredCategories)//
                        .addAttribute("containsExpiredCategories", !expiredCategories.isEmpty())//
                        .addAttribute("showNoCategoriesWarning", validCategories.isEmpty())
                        .addAttribute("hasAccessPromotions", hasAccessPromotions)
                        .addAttribute("promoCode", specialCode.map(SpecialPrice::getCode).orElse(null))
                        .addAttribute("locationDescriptor", ld)
                        .addAttribute("pageTitle", "show-event.header.title")
                        .addAttribute("hasPromoCodeDiscount", promoCodeDiscount.isPresent())
                        .addAttribute("promoCodeDiscount", promoCodeDiscount.orElse(null))
                        .addAttribute("displayWaitingQueueForm",
                                EventUtil.displayWaitingQueueForm(event, saleableTicketCategories,
                                        configurationManager, eventStatisticsManager.noSeatsAvailable()))
                        .addAttribute("displayCategorySelectionForWaitingQueue",
                                saleableTicketCategories.stream().filter(waitingQueueTargetCategory)
                                        .count() > 1)
                        .addAttribute("unboundedCategories",
                                saleableTicketCategories.stream().filter(waitingQueueTargetCategory)
                                        .collect(Collectors.toList()))
                        .addAttribute("preSales", EventUtil.isPreSales(event, saleableTicketCategories))
                        .addAttribute("userLanguage", locale.getLanguage())
                        .addAttribute("showAdditionalServices", !notExpiredServices.isEmpty())
                        .addAttribute("showAdditionalServicesDonations", !donations.isEmpty())
                        .addAttribute("showAdditionalServicesSupplements", !supplements.isEmpty())
                        .addAttribute("enabledAdditionalServicesDonations", donations)
                        .addAttribute("enabledAdditionalServicesSupplements", supplements)
                        .addAttribute("forwardButtonDisabled",
                                (saleableTicketCategories.stream()
                                        .noneMatch(SaleableTicketCategory::getSaleable))
                                        || !validPaymentConfigured)
                        .addAttribute("useFirstAndLastName", event.mustUseFirstAndLastName())
                        .addAttribute("validPaymentMethodAvailable", validPaymentConfigured)
                        .addAttribute("validityStart", event.getBegin())
                        .addAttribute("validityEnd", event.getEnd());

                model.asMap().putIfAbsent("hasErrors", false);//
                return "/event/show-event";
            }).orElse(REDIRECT + "/");
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testAlreadyMigratedEvent() {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()),
            new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {/*from   w  w  w . j  a v a  2 s  .  co m*/
        ZonedDateTime migrationTs = ZonedDateTime.now(ZoneId.of("UTC"));
        eventMigrationRepository.insertMigrationData(event.getId(), currentVersion, migrationTs,
                EventMigration.Status.COMPLETE.toString());
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);
        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(migrationTs.toString(), eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(AVAILABLE_SEATS, tickets.size());//<-- the migration has not been done
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:alfio.manager.WaitingQueueManager.java

private Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> handlePreReservation(
        Event event, int waitingPeople) {
    List<TicketCategory> ticketCategories = ticketCategoryRepository.findAllTicketCategories(event.getId());
    // Given that this Job runs more than once in a minute, in order to ensure that all the waiting queue subscribers would get a seat *before*
    // all other people, we must process their a little bit before the sale period starts
    Optional<TicketCategory> categoryWithInceptionInFuture = ticketCategories.stream()
            .sorted(TicketCategory.COMPARATOR).findFirst().filter(t -> ZonedDateTime.now(event.getZoneId())
                    .isBefore(t.getInception(event.getZoneId()).minusMinutes(5)));
    int ticketsNeeded = Math.min(waitingPeople, eventRepository.countExistingTickets(event.getId()));
    if (ticketsNeeded > 0) {
        preReserveIfNeeded(event, ticketsNeeded);
        if (!categoryWithInceptionInFuture.isPresent()) {
            return distributeAvailableSeats(event, Ticket.TicketStatus.PRE_RESERVED, () -> ticketsNeeded);
        }// w w w  .j  a va2s .c om
    }
    return Stream.empty();
}