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.controller.EventController.java

@RequestMapping(value = "/event/{eventName}/promoCode/{promoCode}", method = RequestMethod.POST)
@ResponseBody/*from  ww w . j  av a 2s  . com*/
public ValidationResult savePromoCode(@PathVariable("eventName") String eventName,
        @PathVariable("promoCode") String promoCode, Model model, HttpServletRequest request) {

    SessionUtil.removeSpecialPriceData(request);

    Optional<Event> optional = eventRepository.findOptionalByShortName(eventName);
    if (!optional.isPresent()) {
        return ValidationResult.failed(new ValidationResult.ErrorDescriptor("event", ""));
    }
    Event event = optional.get();
    ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    Optional<String> maybeSpecialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode));
    Optional<SpecialPrice> specialCode = maybeSpecialCode
            .flatMap((trimmedCode) -> specialPriceRepository.getByCode(trimmedCode));
    Optional<PromoCodeDiscount> promotionCodeDiscount = maybeSpecialCode
            .flatMap((trimmedCode) -> promoCodeRepository.findPromoCodeInEventOrOrganization(event.getId(),
                    trimmedCode));

    if (specialCode.isPresent()) {
        if (!optionally(() -> eventManager.getTicketCategoryById(specialCode.get().getTicketCategoryId(),
                event.getId())).isPresent()) {
            return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
        }

        if (specialCode.get().getStatus() != SpecialPrice.Status.FREE) {
            return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
        }

    } else if (promotionCodeDiscount.isPresent()
            && !promotionCodeDiscount.get().isCurrentlyValid(event.getZoneId(), now)) {
        return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
    } else if (!specialCode.isPresent() && !promotionCodeDiscount.isPresent()) {
        return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
    }

    if (maybeSpecialCode.isPresent() && !model.asMap().containsKey("hasErrors")) {
        if (specialCode.isPresent()) {
            SessionUtil.saveSpecialPriceCode(maybeSpecialCode.get(), request);
        } else if (promotionCodeDiscount.isPresent()) {
            SessionUtil.savePromotionCodeDiscount(maybeSpecialCode.get(), request);
        }
        return ValidationResult.success();
    }
    return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
}

From source file:com.github.aptd.simulation.datamodel.CXMLReader.java

@Override
@SuppressWarnings("unchecked")
public final IExperiment get(final IFactory p_factory, final String p_datamodel, final long p_simulationsteps,
        final boolean p_parallel, final String p_timemodel,
        final Supplier<RealDistribution> p_platformchangedurationdistributionsupplier,
        final int p_numberofpassengers, final double p_lightbarrierminfreetime, final double p_delayseconds) {
    try (final FileInputStream l_stream = new FileInputStream(p_datamodel)) {
        final Asimov l_model = (Asimov) m_context.createUnmarshaller().unmarshal(l_stream);

        // time definition

        final Instant l_starttime = ZonedDateTime.now(ZoneId.systemDefault())
                .with(ChronoField.CLOCK_HOUR_OF_DAY, 8).with(ChronoField.MINUTE_OF_HOUR, 45)
                .with(ChronoField.SECOND_OF_MINUTE, 0).with(ChronoField.NANO_OF_SECOND, 0)
                .with(ChronoField.DAY_OF_MONTH, 3).with(ChronoField.MONTH_OF_YEAR, 10)
                .with(ChronoField.YEAR, 2017).toInstant();

        final ITime l_time = "jump".equals(p_timemodel) ? new CJumpTime(l_starttime, p_simulationsteps)
                : new CStepTime(l_starttime, Duration.ofSeconds(1), p_simulationsteps);

        final CMessenger l_messenger = new CMessenger();

        final Set<IAction> l_actionsfrompackage = CCommon.actionsFromPackage().collect(Collectors.toSet());

        // asl agent definition
        final Map<String, String> l_agentdefs = agents(l_model.getAi());

        // macro (train-network) and microscopic model
        final Map<String, IPlatform<?>> l_platform = platform(l_model.getNetwork(), l_agentdefs, p_factory,
                l_time);//w w  w .j av  a2s  .c om
        final Map<String, IStation<?>> l_station = station(l_model.getNetwork(), l_agentdefs, p_factory, l_time,
                l_platform);
        final Pair<Map<String, ITrain<?>>, Map<String, IDoor<?>>> l_train = train(l_model.getNetwork(),
                l_agentdefs, p_factory, l_time, p_lightbarrierminfreetime);

        final Map<String, IElement<?>> l_agents = new HashMap<>();
        l_agents.putAll(l_platform);
        l_agents.putAll(l_station);
        l_agents.putAll(l_train.getLeft());
        l_agents.putAll(l_train.getRight());

        final CExperiment l_experiment = new CExperiment(p_simulationsteps, p_parallel, IStatistic.EMPTY,
                l_agents, l_time, l_messenger);

        // @todo create passengersources and their passenger generators according to scenario definition

        final IElement.IGenerator<IPassenger<?>> l_passengergenerator = passengergenerator(p_factory,
                "+!activate <-\n    state/transition\n.", l_actionsfrompackage, l_time);

        l_experiment.addAgent("passengersource_test",
                passengersourcegenerator(p_factory, "+!activate <-\n    state/transition\n.",
                        l_actionsfrompackage, l_time).generatesingle(new UniformRealDistribution(0.0, 1.0),
                                l_time.current().toEpochMilli(), p_numberofpassengers, l_passengergenerator,
                                l_experiment, l_agents.get("toy-node-1"),
                                p_platformchangedurationdistributionsupplier.get()));

        l_messenger.experiment(l_experiment);

        // experiment (executable model)
        return l_experiment;

    } catch (final Exception l_execption) {
        throw new CRuntimeException(l_execption);
    }
}

From source file:com.match_tracker.twitter.TwitterSearch.java

protected long calculateSearchDelay(ZonedDateTime startTime) {
    long searchDelay = 0;

    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime offsetStartTime = startTime.plusSeconds(SEARCH_START_DELAY_SECONDS);

    if (now.isBefore(offsetStartTime)) {
        searchDelay = now.until(offsetStartTime, ChronoUnit.MILLIS);
    }/*from  www  .  j a  v  a 2 s .  c o m*/

    return searchDelay;
}

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

private void migrateEventToCurrentVersion(Event event) {
    Optional<EventMigration> optional = optionally(
            () -> eventMigrationRepository.loadEventMigration(event.getId()));
    boolean alreadyDefined = optional.isPresent();
    if (!alreadyDefined || optional.filter(this::needsFixing).isPresent()) {
        transactionTemplate.execute(s -> {
            //optional.ifPresent(eventMigration -> eventMigrationRepository.lockEventMigrationForUpdate(eventMigration.getId()));
            if (ZonedDateTime.now(event.getZoneId()).isBefore(event.getEnd())) {
                fixAvailableSeats(event);
                fillDescriptions(event);
                fixCategoriesSize(event);
            }/*from  w  w  w  .ja v  a2s  . c  o m*/

            //migrate prices to new structure. This should be done for all events, regardless of the expiration date.
            migratePrices(event.getId());
            fixStuckTickets(event.getId());

            if (alreadyDefined) {
                EventMigration eventMigration = optional.get();
                int result = eventMigrationRepository.updateMigrationData(eventMigration.getId(),
                        currentVersionAsString, buildTimestamp, EventMigration.Status.COMPLETE.name());
                Validate.isTrue(result == 1, "error during update " + result);
            } else {
                eventMigrationRepository.insertMigrationData(event.getId(), currentVersionAsString,
                        buildTimestamp, EventMigration.Status.COMPLETE.name());
            }

            return null;
        });
    }
}

From source file:alfio.manager.WaitingQueueManager.java

private WaitingQueueSubscription.Type getSubscriptionType(Event event) {
    ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    return ticketCategoryRepository.findByEventId(event.getId()).stream().findFirst()
            .filter(tc -> now.isBefore(tc.getInception(event.getZoneId())))
            .map(tc -> WaitingQueueSubscription.Type.PRE_SALES).orElse(WaitingQueueSubscription.Type.SOLD_OUT);
}

From source file:org.xlrnet.metadict.engines.leo.LeoEngine.java

private Connection buildTargetConnection(String searchString, Language inputLanguage, Language outputLanguage) {
    String targetDictionary = resolveDictionaryConfig(inputLanguage, outputLanguage);
    if (targetDictionary == null) {
        targetDictionary = resolveDictionaryConfig(outputLanguage, inputLanguage);
        if (targetDictionary == null)
            throw new IllegalArgumentException(
                    "No suitable dictionary configuration found - this might be an internal metadict error");
    }/*from  w w w  . ja v  a2s. c o m*/

    return Jsoup.connect("https://dict.leo.org/dictQuery/m-vocab/" + targetDictionary + "/query.xml").userAgent(
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36")
            .data(DEFAULT_QUERY_DATA).data("lp", targetDictionary).data("search", searchString)
            .data("t", ZonedDateTime.now(ZoneOffset.UTC).toString());
}

From source file:org.sakaiproject.sitestats.tool.wicket.pages.UserActivityPage.java

@Override
protected void onInitialize() {
    super.onInitialize();

    Form form = new Form("form");
    add(form);// w  w w. j  a  v a  2 s  .  c o m
    add(new Menus("menu", siteId));

    lastJobRunContainer = new WebMarkupContainer("lastJobRunContainer");
    lastJobRunContainer.setOutputMarkupId(true);
    add(lastJobRunContainer);
    lastJobRunContainer.add(new LastJobRun("lastJobRun", siteId));

    IChoiceRenderer<DisplayUser> userChoiceRenderer = new ChoiceRenderer<DisplayUser>() {
        @Override
        public Object getDisplayValue(DisplayUser user) {
            // Short circuit if user is blank
            if (StringUtils.isBlank(user.userId)) {
                return new ResourceModel("user_unknown").getObject();
            }

            // String representation of 'select user' option
            if (ReportManager.WHO_NONE.equals(user.userId)) {
                return new ResourceModel("de_select_user").getObject();
            }

            return user.display;
        }

        @Override
        public String getIdValue(DisplayUser user, int index) {
            return user.userId;
        }
    };

    DropDownChoice<DisplayUser> userFilter = new DropDownChoice<>("userFilter",
            new PropertyModel<>(this, "displayUser"), new LoadableDisplayUserListModel(siteId),
            userChoiceRenderer);
    userFilter.add(new AjaxFormComponentUpdatingBehavior("onchange") {
        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            if (ReportManager.WHO_NONE.equals(displayUser.userId)) {
                searchButton.setEnabled(false);
                target.add(searchButton);
            } else {
                searchButton.setEnabled(true);
                target.add(searchButton);
            }
        }
    });
    userFilter.setLabel(new ResourceModel("de_userFilter"));
    form.add(new SimpleFormComponentLabel("userFilterLabel", userFilter));
    form.add(userFilter);

    IChoiceRenderer<String> toolChoiceRenderer = new ChoiceRenderer<String>() {
        @Override
        public Object getDisplayValue(String toolId) {
            return Locator.getFacade().getEventRegistryService().getToolName(toolId);
        }

        @Override
        public String getIdValue(String toolId, int index) {
            return toolId;
        }
    };
    DropDownChoice<String> eventFilterByTool = new DropDownChoice<>("eventFilter",
            new PropertyModel<>(this, "tool"), new LoadableToolIdListModel(siteId), toolChoiceRenderer);
    eventFilterByTool.setLabel(new ResourceModel("de_eventFilter"));
    form.add(new SimpleFormComponentLabel("eventFilterLabel", eventFilterByTool));
    form.add(eventFilterByTool);

    ZoneId tz = Locator.getFacade().getUserTimeService().getLocalTimeZone().toZoneId();
    startDate = ZonedDateTime.now(tz).truncatedTo(ChronoUnit.DAYS);
    SakaiDateTimeField startDateField = new SakaiDateTimeField("startDate",
            new PropertyModel<>(this, "startDate"), tz);
    startDateField.setLabel(new ResourceModel("de_dateRangeFrom"));
    form.add(new SimpleFormComponentLabel("startDateLabel", startDateField));
    form.add(startDateField);

    endDate = startDate.plusDays(1);
    SakaiDateTimeField endDateField = new SakaiDateTimeField("endDate", new PropertyModel<>(this, "endDate"),
            tz);
    endDateField.setLabel(new ResourceModel("de_dateRangeTo"));
    form.add(new SimpleFormComponentLabel("endDateLabel", endDateField));
    form.add(endDateField);

    String zoneName = startDate.getZone().getDisplayName(TextStyle.FULL, getSession().getLocale());
    StringResourceModel legendModel = new StringResourceModel("de_dateRange", getPage(), null,
            new Object[] { zoneName });
    form.add(new Label("dateRangeLegend", legendModel));

    final UserTrackingResultsPanel resultsPanel = new UserTrackingResultsPanel("results",
            TrackingParams.EMPTY_PARAMS);
    resultsPanel.setOutputMarkupPlaceholderTag(true);
    resultsPanel.setVisible(false);
    add(resultsPanel);

    searchButton = new SakaiAjaxButton("search", form) {
        @Override
        public void onSubmit(AjaxRequestTarget target, Form form) {
            // run search
            PrefsData pd = Locator.getFacade().getStatsManager().getPreferences(siteId, false);
            TrackingParams params = new TrackingParams(siteId,
                    Tools.getEventsForToolFilter(tool, siteId, pd, true),
                    Collections.singletonList(displayUser.userId), startDate.toInstant(), endDate.toInstant());
            resultsPanel.setTrackingParams(params);
            resultsPanel.setVisible(true);
            target.add(resultsPanel);
            lastJobRunContainer.replace(new LastJobRun("lastJobRun", siteId));
            target.add(lastJobRunContainer);
            Locator.getFacade().getStatsManager().logEvent(new UserId(user), StatsManager.LOG_ACTION_TRACK,
                    siteId, false);
        }
    };
    searchButton.setEnabled(false);
    form.add(searchButton);
}

From source file:com.omertron.slackbot.functions.scheduler.AbstractBotTask.java

/**
 * Get the current date/time in the local time zone
 *
 * @return/* www. ja v a  2s  . c  o m*/
 */
private static ZonedDateTime localeDateTime() {
    return ZonedDateTime.now(TIMEZONE);
}

From source file:org.bedework.synch.cnctrs.orgSyncV2.OrgSyncV2ConnectorInstance.java

private IcalendarType toXcal(final List<OrgSyncV2Event> osEvents, final boolean onlyPublic) {
    final IcalendarType ical = new IcalendarType();
    final VcalendarType vcal = new VcalendarType();

    ical.getVcalendar().add(vcal);//w w  w .ja  va 2  s.  c  o m

    vcal.setProperties(new ArrayOfProperties());
    final List<JAXBElement<? extends BasePropertyType>> vcalProps = vcal.getProperties()
            .getBasePropertyOrTzid();

    final VersionPropType vers = new VersionPropType();
    vers.setText("2.0");
    vcalProps.add(of.createVersion(vers));

    final ProdidPropType prod = new ProdidPropType();
    prod.setText("//Bedework.org//BedeWork V3.11.1//EN");
    vcalProps.add(of.createProdid(prod));

    final ArrayOfComponents aoc = new ArrayOfComponents();
    vcal.setComponents(aoc);

    for (final OrgSyncV2Event osev : osEvents) {
        if (onlyPublic && !osev.getIsPublic()) {
            continue;
        }

        final VeventType ev = new VeventType();

        aoc.getBaseComponent().add(of.createVevent(ev));

        ev.setProperties(new ArrayOfProperties());
        final List<JAXBElement<? extends BasePropertyType>> evProps = ev.getProperties()
                .getBasePropertyOrTzid();

        final UidPropType uid = new UidPropType();
        uid.setText(config.getUidPrefix() + "-" + osev.getId());
        evProps.add(of.createUid(uid));

        final DtstampPropType dtstamp = new DtstampPropType();
        try {
            //Get todays date
            final ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC);
            final String todayStr = today.format(DateTimeFormatter.ISO_INSTANT);

            dtstamp.setUtcDateTime(XcalUtil.getXMlUTCCal(todayStr));
            evProps.add(of.createDtstamp(dtstamp));

            final CreatedPropType created = new CreatedPropType();
            created.setUtcDateTime(XcalUtil.getXMlUTCCal(todayStr));
            evProps.add(of.createCreated(created));

            final SummaryPropType sum = new SummaryPropType();
            sum.setText(osev.getName());
            evProps.add(of.createSummary(sum));

            final DescriptionPropType desc = new DescriptionPropType();
            desc.setText(osev.getDescription());
            evProps.add(of.createDescription(desc));

            final LocationPropType l = new LocationPropType();
            l.setText(osev.getLocation());
            evProps.add(of.createLocation(l));

            if (info.getLocationKey() != null) {
                final XBedeworkLocKeyParamType par = of.createXBedeworkLocKeyParamType();

                par.setText(info.getLocationKey());
                l.setParameters(new ArrayOfParameters());
                l.getParameters().getBaseParameter().add(of.createXBedeworkLocKey(par));
            }
        } catch (final Throwable t) {
            error(t);
            continue;
        }

        if (osev.getCategory() != null) {
            final CategoriesPropType cat = new CategoriesPropType();
            cat.getText().add(osev.getCategory().getName());
            evProps.add(of.createCategories(cat));
        }

        /* The first (only) element of occurrences is the start/end of the
           event or master.
                
           If there are more occurrences these become rdates and the event is
           recurring.
         */

        if (Util.isEmpty(osev.getOccurrences())) {
            // warn?
            continue;
        }

        boolean first = true;
        for (final OrgSyncV2Occurrence occ : osev.getOccurrences()) {
            if (first) {
                final DtstartPropType dtstart = (DtstartPropType) makeDt(new DtstartPropType(),
                        occ.getStartsAt());
                evProps.add(of.createDtstart(dtstart));

                final DtendPropType dtend = (DtendPropType) makeDt(new DtendPropType(), occ.getEndsAt());
                evProps.add(of.createDtend(dtend));

                first = false;
                continue;
            }

            // Add an rdate
            // TODO - add duration if different from the master
            final RdatePropType rdate = (RdatePropType) makeDt(new RdatePropType(), occ.getStartsAt());
            evProps.add(of.createRdate(rdate));
        }
    }

    return ical;
}

From source file:alfio.manager.SpecialPriceManager.java

public boolean sendCodeToAssignee(List<SendCodeModification> input, String eventName, int categoryId,
        String username) {/*from w  w  w . j  a v a2  s  .co m*/
    final Event event = eventManager.getSingleEvent(eventName, username);
    final Organization organization = eventManager.loadOrganizer(event, username);
    Set<SendCodeModification> set = new LinkedHashSet<>(input);
    checkCodeAssignment(set, categoryId, event, username);
    Validate.isTrue(set.stream().allMatch(IS_CODE_PRESENT),
            "There are missing codes. Please check input file.");
    List<ContentLanguage> eventLanguages = i18nManager.getEventLanguages(event.getLocales());
    Validate.isTrue(!eventLanguages.isEmpty(),
            "No locales have been defined for the event. Please check the configuration");
    ContentLanguage defaultLocale = eventLanguages.contains(ContentLanguage.ENGLISH) ? ContentLanguage.ENGLISH
            : eventLanguages.get(0);
    set.forEach(m -> {
        Locale locale = Locale.forLanguageTag(StringUtils.defaultString(StringUtils.trimToNull(m.getLanguage()),
                defaultLocale.getLanguage()));
        Map<String, Object> model = TemplateResource.prepareModelForSendReservedCode(organization, event, m,
                eventManager.getEventUrl(event));
        notificationManager.sendSimpleEmail(event, m.getEmail(),
                messageSource.getMessage("email-code.subject", new Object[] { event.getDisplayName() }, locale),
                () -> templateManager.renderTemplate(event, TemplateResource.SEND_RESERVED_CODE, model,
                        locale));
        int marked = specialPriceRepository.markAsSent(ZonedDateTime.now(event.getZoneId()),
                m.getAssignee().trim(), m.getEmail().trim(), m.getCode().trim());
        Validate.isTrue(marked == 1, "Expected exactly one row updated, got " + marked);
    });
    return true;
}