Search in sources :

Example 1 with StringUtils.trimToNull

use of org.apache.commons.lang3.StringUtils.trimToNull in project alf.io by alfio-event.

the class DynamicResourcesController method getGoogleAnalyticsScript.

@RequestMapping("/resources/js/google-analytics")
public void getGoogleAnalyticsScript(HttpSession session, HttpServletResponse response, @RequestParam("e") Integer eventId) throws IOException {
    response.setContentType("application/javascript");
    Optional<Event> ev = Optional.ofNullable(eventId).flatMap(id -> Optional.ofNullable(eventRepository.findById(id)));
    ConfigurationPathKey pathKey = ev.map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_KEY)).orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_KEY));
    final Optional<String> id = configurationManager.getStringConfigValue(pathKey);
    final String script;
    ConfigurationPathKey anonymousPathKey = ev.map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_ANONYMOUS_MODE)).orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_ANONYMOUS_MODE));
    if (id.isPresent() && configurationManager.getBooleanConfigValue(anonymousPathKey, true)) {
        String trackingId = Optional.ofNullable(StringUtils.trimToNull((String) session.getAttribute("GA_TRACKING_ID"))).orElseGet(() -> UUID.randomUUID().toString());
        Map<String, Object> model = new HashMap<>();
        model.put("clientId", trackingId);
        model.put("account", id.get());
        script = templateManager.renderTemplate(TemplateResource.GOOGLE_ANALYTICS, model, Locale.ENGLISH);
    } else {
        script = id.map(x -> String.format(GOOGLE_ANALYTICS_SCRIPT, x)).orElse(EMPTY);
    }
    response.getWriter().write(script);
}
Also used : ConfigurationPathKey(alfio.model.system.Configuration.ConfigurationPathKey) HttpSession(javax.servlet.http.HttpSession) RequestParam(org.springframework.web.bind.annotation.RequestParam) java.util(java.util) ConfigurationPathKey(alfio.model.system.Configuration.ConfigurationPathKey) GOOGLE_ANALYTICS_KEY(alfio.model.system.ConfigurationKeys.GOOGLE_ANALYTICS_KEY) TemplateManager(alfio.util.TemplateManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) IOException(java.io.IOException) ConfigurationManager(alfio.manager.system.ConfigurationManager) Controller(org.springframework.stereotype.Controller) EventRepository(alfio.repository.EventRepository) StringUtils(org.apache.commons.lang3.StringUtils) GOOGLE_ANALYTICS_ANONYMOUS_MODE(alfio.model.system.ConfigurationKeys.GOOGLE_ANALYTICS_ANONYMOUS_MODE) Configuration(alfio.model.system.Configuration) Event(alfio.model.Event) TemplateResource(alfio.util.TemplateResource) Event(alfio.model.Event) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with StringUtils.trimToNull

use of org.apache.commons.lang3.StringUtils.trimToNull in project alf.io by alfio-event.

the class ReservationForm method validate.

public Optional<Pair<List<TicketReservationWithOptionalCodeModification>, List<ASReservationWithOptionalCodeModification>>> validate(Errors bindingResult, TicketReservationManager tickReservationManager, AdditionalServiceRepository additionalServiceRepository, EventManager eventManager, Event event) {
    int selectionCount = ticketSelectionCount();
    if (selectionCount <= 0) {
        bindingResult.reject(ErrorsCode.STEP_1_SELECT_AT_LEAST_ONE);
        return Optional.empty();
    }
    List<Pair<TicketReservationModification, Integer>> maxTicketsByTicketReservation = selected().stream().map(r -> Pair.of(r, tickReservationManager.maxAmountOfTicketsForCategory(event.getOrganizationId(), event.getId(), r.getTicketCategoryId()))).collect(toList());
    Optional<Pair<TicketReservationModification, Integer>> error = maxTicketsByTicketReservation.stream().filter(p -> p.getKey().getAmount() > p.getValue()).findAny();
    if (error.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_1_OVER_MAXIMUM, new Object[] { error.get().getValue() }, null);
        return Optional.empty();
    }
    final List<TicketReservationModification> categories = selected();
    final List<AdditionalServiceReservationModification> additionalServices = selectedAdditionalServices();
    final boolean validCategorySelection = categories.stream().allMatch(c -> {
        TicketCategory tc = eventManager.getTicketCategoryById(c.getTicketCategoryId(), event.getId());
        return OptionalWrapper.optionally(() -> eventManager.findEventByTicketCategory(tc)).isPresent();
    });
    final boolean validAdditionalServiceSelected = additionalServices.stream().allMatch(asm -> {
        AdditionalService as = eventManager.getAdditionalServiceById(asm.getAdditionalServiceId(), event.getId());
        ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
        return as.getInception(event.getZoneId()).isBefore(now) && as.getExpiration(event.getZoneId()).isAfter(now) && asm.getQuantity() >= 0 && ((as.isFixPrice() && asm.isQuantityValid(as, selectionCount)) || (!as.isFixPrice() && asm.getAmount() != null && asm.getAmount().compareTo(BigDecimal.ZERO) >= 0)) && OptionalWrapper.optionally(() -> eventManager.findEventByAdditionalService(as)).isPresent();
    });
    if (!validCategorySelection || !validAdditionalServiceSelected) {
        bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE);
        return Optional.empty();
    }
    List<TicketReservationWithOptionalCodeModification> res = new ArrayList<>();
    // 
    Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode)).flatMap((trimmedCode) -> tickReservationManager.getSpecialPriceByCode(trimmedCode));
    // 
    final ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    maxTicketsByTicketReservation.forEach((pair) -> validateCategory(bindingResult, tickReservationManager, eventManager, event, pair.getRight(), res, specialCode, now, pair.getLeft()));
    return bindingResult.hasErrors() ? Optional.empty() : Optional.of(Pair.of(res, additionalServices.stream().map(as -> new ASReservationWithOptionalCodeModification(as, specialCode)).collect(Collectors.toList())));
}
Also used : Errors(org.springframework.validation.Errors) TicketReservationModification(alfio.model.modification.TicketReservationModification) ZonedDateTime(java.time.ZonedDateTime) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) BigDecimal(java.math.BigDecimal) Pair(org.apache.commons.lang3.tuple.Pair) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceRepository(alfio.repository.AdditionalServiceRepository) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) Collections.emptyList(java.util.Collections.emptyList) Optional.ofNullable(java.util.Optional.ofNullable) ErrorsCode(alfio.util.ErrorsCode) OptionalWrapper(alfio.util.OptionalWrapper) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) TicketReservationManager(alfio.manager.TicketReservationManager) TicketCategory(alfio.model.TicketCategory) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) EventManager(alfio.manager.EventManager) AdditionalService(alfio.model.AdditionalService) SpecialPrice(alfio.model.SpecialPrice) Data(lombok.Data) Optional(java.util.Optional) Event(alfio.model.Event) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) SpecialPrice(alfio.model.SpecialPrice) AdditionalService(alfio.model.AdditionalService) ArrayList(java.util.ArrayList) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) TicketCategory(alfio.model.TicketCategory) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) ZonedDateTime(java.time.ZonedDateTime) TicketReservationModification(alfio.model.modification.TicketReservationModification) Pair(org.apache.commons.lang3.tuple.Pair)

Example 3 with StringUtils.trimToNull

use of org.apache.commons.lang3.StringUtils.trimToNull in project alf.io by alfio-event.

the class EventController method handleCode.

@RequestMapping(value = "/event/{eventName}/code/{code}", method = { RequestMethod.GET, RequestMethod.HEAD })
public String handleCode(@PathVariable("eventName") String eventName, @PathVariable("code") String code, Model model, ServletWebRequest request, RedirectAttributes redirectAttributes, Locale locale) {
    String trimmedCode = StringUtils.trimToNull(code);
    return eventRepository.findOptionalByShortName(eventName).map(event -> {
        String redirectToEvent = "redirect:/event/" + eventName + "/";
        ValidationResult res = savePromoCode(eventName, trimmedCode, model, request.getRequest());
        CodeType codeType = getCodeType(event.getId(), trimmedCode);
        if (res.isSuccess() && codeType == CodeType.PROMO_CODE_DISCOUNT) {
            return redirectToEvent;
        } else if (codeType == CodeType.TICKET_CATEGORY_CODE) {
            TicketCategory category = ticketCategoryRepository.findCodeInEvent(event.getId(), trimmedCode).get();
            if (!category.isAccessRestricted()) {
                return makeSimpleReservation(eventName, request, redirectAttributes, locale, null, event, category.getId());
            } else {
                Optional<SpecialPrice> specialPrice = specialPriceRepository.findActiveNotAssignedByCategoryId(category.getId()).stream().findFirst();
                if (!specialPrice.isPresent()) {
                    return redirectToEvent;
                }
                savePromoCode(eventName, specialPrice.get().getCode(), model, request.getRequest());
                return makeSimpleReservation(eventName, request, redirectAttributes, locale, specialPrice.get().getCode(), event, category.getId());
            }
        } else if (res.isSuccess() && codeType == CodeType.SPECIAL_PRICE) {
            int ticketCategoryId = specialPriceRepository.getByCode(trimmedCode).get().getTicketCategoryId();
            return makeSimpleReservation(eventName, request, redirectAttributes, locale, trimmedCode, event, ticketCategoryId);
        } else {
            return redirectToEvent;
        }
    }).orElse("redirect:/");
}
Also used : ValidationResult(alfio.model.result.ValidationResult) alfio.repository(alfio.repository) ReservationForm(alfio.controller.form.ReservationForm) java.util(java.util) TicketReservationModification(alfio.model.modification.TicketReservationModification) SaleableAdditionalService(alfio.controller.decorator.SaleableAdditionalService) PaymentProxy(alfio.model.transaction.PaymentProxy) ZonedDateTime(java.time.ZonedDateTime) BindingResult(org.springframework.validation.BindingResult) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) ConfigurationManager(alfio.manager.system.ConfigurationManager) Controller(org.springframework.stereotype.Controller) StringUtils(org.apache.commons.lang3.StringUtils) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Model(org.springframework.ui.Model) HttpServletRequest(javax.servlet.http.HttpServletRequest) LocationDescriptor(alfio.model.modification.support.LocationDescriptor) SessionUtil.addToFlash(alfio.controller.support.SessionUtil.addToFlash) EventDescriptor(alfio.controller.decorator.EventDescriptor) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) RedirectAttributes(org.springframework.web.servlet.mvc.support.RedirectAttributes) OrganizationRepository(alfio.repository.user.OrganizationRepository) Predicate(java.util.function.Predicate) HttpMethod(org.springframework.http.HttpMethod) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) SessionUtil(alfio.controller.support.SessionUtil) ErrorsCode(alfio.util.ErrorsCode) Collectors(java.util.stream.Collectors) DateUtils(org.apache.commons.lang3.time.DateUtils) TicketReservationManager(alfio.manager.TicketReservationManager) EventManager(alfio.manager.EventManager) alfio.model(alfio.model) EventStatisticsManager(alfio.manager.EventStatisticsManager) Configuration(alfio.model.system.Configuration) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) EventUtil(alfio.util.EventUtil) ResponseEntity(org.springframework.http.ResponseEntity) I18nManager(alfio.manager.i18n.I18nManager) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) OptionalWrapper.optionally(alfio.util.OptionalWrapper.optionally) ValidationResult(alfio.model.result.ValidationResult) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)3 SaleableTicketCategory (alfio.controller.decorator.SaleableTicketCategory)2 EventManager (alfio.manager.EventManager)2 TicketReservationManager (alfio.manager.TicketReservationManager)2 ConfigurationManager (alfio.manager.system.ConfigurationManager)2 Event (alfio.model.Event)2 TicketReservationModification (alfio.model.modification.TicketReservationModification)2 Configuration (alfio.model.system.Configuration)2 ErrorsCode (alfio.util.ErrorsCode)2 IOException (java.io.IOException)2 ZonedDateTime (java.time.ZonedDateTime)2 java.util (java.util)2 Collectors (java.util.stream.Collectors)2 EventDescriptor (alfio.controller.decorator.EventDescriptor)1 SaleableAdditionalService (alfio.controller.decorator.SaleableAdditionalService)1 ReservationForm (alfio.controller.form.ReservationForm)1 SessionUtil (alfio.controller.support.SessionUtil)1 SessionUtil.addToFlash (alfio.controller.support.SessionUtil.addToFlash)1 EventStatisticsManager (alfio.manager.EventStatisticsManager)1 I18nManager (alfio.manager.i18n.I18nManager)1