Example usage for org.springframework.ui Model asMap

List of usage examples for org.springframework.ui Model asMap

Introduction

In this page you can find the example usage for org.springframework.ui Model asMap.

Prototype

Map<String, Object> asMap();

Source Link

Document

Return the current set of model attributes as a Map.

Usage

From source file:org.opentravel.pubs.controllers.PublicationController.java

/**
 * Performs a download of the publication or publication item content specified by the URL
 * parameters./*from  w w w .  j  av a 2 s . com*/
 * 
 * @param model  the UI model for the current request
 * @param session  the HTTP session
 * @param registrant  the web site registrant who is performing the download
 * @param request  the HTTP request for the content download
 * @param response  the HTTP response to which output should be directed
 * @param redirectAttrs  request attributes that must be available in case of a page redirect
 * @param releaseDateStr  the release date of the code list archive being downloaded
 * @param filename  the name of the content item that is being downloaded
 * @return String
 * @throws DAOException  thrown if an error occurs while accessing the content from persistent storage
 * @throws IOException  thrown if the content cannot be streamed to the HTTP response
 */
protected String doCodeListDownload(Model model, HttpSession session, Registrant registrant,
        HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttrs,
        String releaseDateStr, String filename) throws DAOException, IOException {
    InputStream contentStream = null;
    String targetPath = null;

    if ((releaseDateStr != null) && (releaseDateStr.trim().length() > 0)) {
        CodeListDAO cDao = DAOFactoryManager.getFactory().newCodeListDAO();
        DownloadDAO dDao = DAOFactoryManager.getFactory().newDownloadDAO();

        try {
            CodeList codeList = cDao.getCodeList(CodeList.labelFormat.parse(releaseDateStr));

            if (codeList != null) {
                if (filename.equals(codeList.getArchiveFilename())) {
                    contentStream = dDao.getArchiveContent(codeList, registrant);
                }
            }

        } catch (ParseException e) {
            log.warn("Unreadable release date specified for code list download: \"" + releaseDateStr + "\"");
        }
    }

    if (contentStream != null) {
        try (OutputStream responseOut = response.getOutputStream()) {
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;

            while ((bytesRead = contentStream.read(buffer, 0, buffer.length)) >= 0) {
                responseOut.write(buffer, 0, bytesRead);
            }

        } finally {
            try {
                contentStream.close();
            } catch (Throwable t) {
            }
        }

    } else {
        model.asMap().clear();
        redirectAttrs.addAttribute("filename", request.getRequestURL());
        targetPath = "redirect:/specifications/DownloadNotFound.html";
    }
    return targetPath;
}

From source file:org.opentravel.pubs.controllers.PublicationController.java

/**
 * Performs a download of the publication or publication item content specified by the URL
 * parameters.//from   w  w w.ja v a 2 s.  co  m
 * 
 * @param model  the UI model for the current request
 * @param session  the HTTP session
 * @param registrant  the web site registrant who is performing the download
 * @param request  the HTTP request for the content download
 * @param response  the HTTP response to which output should be directed
 * @param redirectAttrs  request attributes that must be available in case of a page redirect
 * @param pubName  the name of the publication from which content is being downloaded
 * @param type  the type of the publication
 * @param filename  the name of the content item that is being downloaded
 * @return String
 * @throws DAOException  thrown if an error occurs while accessing the content from persistent storage
 * @throws IOException  thrown if the content cannot be streamed to the HTTP response
 */
protected String doPublicationDownload(Model model, HttpSession session, Registrant registrant,
        HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttrs,
        String pubName, String type, String filename) throws DAOException, IOException {
    InputStream contentStream = null;
    String targetPath = null;

    if ((pubName != null) && (type != null) && (filename != null)) {
        PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
        DownloadDAO dDao = DAOFactoryManager.getFactory().newDownloadDAO();
        PublicationType pubType = resolvePublicationType(type);
        Publication publication = pDao.getPublication(pubName, pubType);

        if (publication != null) {
            if (filename.equals(publication.getArchiveFilename())) {
                contentStream = dDao.getArchiveContent(publication, registrant);

            } else {
                PublicationItem item = pDao.findPublicationItem(publication, filename);

                if (item != null) {
                    contentStream = dDao.getContent(item, registrant);
                }
            }
        }
    }

    if (contentStream != null) {
        try (OutputStream responseOut = response.getOutputStream()) {
            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;

            while ((bytesRead = contentStream.read(buffer, 0, buffer.length)) >= 0) {
                responseOut.write(buffer, 0, bytesRead);
            }

        } finally {
            try {
                contentStream.close();
            } catch (Throwable t) {
            }
        }

    } else {
        model.asMap().clear();
        redirectAttrs.addAttribute("filename", request.getRequestURL());
        targetPath = "redirect:/specifications/DownloadNotFound.html";
    }
    return targetPath;
}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/success", method = RequestMethod.GET)
public String showConfirmationPage(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId,
        @RequestParam(value = "confirmation-email-sent", required = false, defaultValue = "false") boolean confirmationEmailSent,
        @RequestParam(value = "ticket-email-sent", required = false, defaultValue = "false") boolean ticketEmailSent,
        Model model, Locale locale, HttpServletRequest request) {

    return eventRepository.findOptionalByShortName(eventName).map(ev -> {
        Optional<TicketReservation> tr = ticketReservationManager.findById(reservationId);
        return tr.filter(r -> r.getStatus() == TicketReservationStatus.COMPLETE).map(reservation -> {
            SessionUtil.removeSpecialPriceData(request);
            model.addAttribute("reservationId", reservationId);
            model.addAttribute("reservation", reservation);
            model.addAttribute("confirmationEmailSent", confirmationEmailSent);
            model.addAttribute("ticketEmailSent", ticketEmailSent);

            List<Ticket> tickets = ticketReservationManager.findTicketsInReservation(reservationId);
            List<Triple<AdditionalService, List<AdditionalServiceText>, AdditionalServiceItem>> additionalServices = ticketReservationManager
                    .findAdditionalServicesInReservation(reservationId).stream()
                    .map(t -> Triple.of(
                            t.getLeft(), t.getMiddle().stream()
                                    .filter(d -> d.getLocale().equals(locale.getLanguage())).collect(toList()),
                            t.getRight()))
                    .collect(Collectors.toList());
            boolean hasPaidSupplement = ticketReservationManager.hasPaidSupplements(reservationId);
            model.addAttribute("ticketsByCategory", tickets.stream()
                    .collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream().map((e) -> {
                        TicketCategory category = eventManager.getTicketCategoryById(e.getKey(), ev.getId());
                        List<TicketDecorator> decorators = TicketDecorator
                                .decorate(e.getValue(),
                                        !hasPaidSupplement && configurationManager.getBooleanConfigValue(
                                                Configuration.from(ev.getOrganizationId(), ev.getId(),
                                                        category.getId(), ALLOW_FREE_TICKETS_CANCELLATION),
                                                false),
                                        eventManager.checkTicketCancellationPrerequisites(),
                                        ticket -> ticketHelper.findTicketFieldConfigurationAndValue(ev.getId(),
                                                ticket, locale),
                                        tickets.size() == 1, TicketDecorator.EMPTY_PREFIX_GENERATOR);
                        return Pair.of(category, decorators);
                    }).collect(toList()));
            boolean ticketsAllAssigned = tickets.stream().allMatch(Ticket::getAssigned);
            model.addAttribute("ticketsAreAllAssigned", ticketsAllAssigned);
            model.addAttribute("collapseEnabled", tickets.size() > 1 && !ticketsAllAssigned);
            model.addAttribute("additionalServicesOnly", tickets.isEmpty() && !additionalServices.isEmpty());
            model.addAttribute("additionalServices", additionalServices);
            model.addAttribute("countries", TicketHelper.getLocalizedCountries(locale));
            model.addAttribute("pageTitle", "reservation-page-complete.header.title");
            model.addAttribute("event", ev);
            model.addAttribute("useFirstAndLastName", ev.mustUseFirstAndLastName());
            model.asMap().putIfAbsent("validationResult", ValidationResult.success());
            return "/event/reservation-page-complete";
        }).orElseGet(() -> redirectReservation(tr, eventName, reservationId));
    }).orElse("redirect:/");
}

From source file:org.busko.routemanager.web.admin.community.RouteOutlineController.java

/**
 * Needs to process all the data submitted to create, at present, the associated Route object.
 *///w  ww  . j a  va 2 s  .c om
@Transactional
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@Valid RouteOutline routeOutline, BindingResult bindingResult, Model uiModel,
        HttpServletRequest httpServletRequest) {
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, routeOutline);
        return "admin/community/routeoutlines/update";
    }

    // Sort the request data
    HashMap<String, String> latMap = new HashMap<String, String>();
    HashMap<String, String> lonMap = new HashMap<String, String>();
    HashMap<String, String> descMap = new HashMap<String, String>();
    HashMap<String, HashMap<String, String>> tripStoptimeMap = new HashMap<String, HashMap<String, String>>();
    HashMap<String, String> frequencyMap = new HashMap<String, String>();
    for (Object o : httpServletRequest.getParameterMap().keySet()) {
        String key = o.toString();
        if (key.startsWith("LAT")) {
            latMap.put(key.substring(3), httpServletRequest.getParameter(key));
        } else if (key.startsWith("LON")) {
            lonMap.put(key.substring(3), httpServletRequest.getParameter(key));
        } else if (key.startsWith("DESC")) {
            descMap.put(key.substring(4), httpServletRequest.getParameter(key));
        } else if (key.endsWith("FREQUENCY")) {
            frequencyMap.put(key.substring(4, key.indexOf("-")), httpServletRequest.getParameter(key));
        } else if (key.startsWith("TRIP")) {
            String index = key.substring(4, key.indexOf("-"));
            HashMap<String, String> stoptimeMap = tripStoptimeMap.get(index);
            if (stoptimeMap == null) {
                stoptimeMap = new HashMap<String, String>();
                tripStoptimeMap.put(index, stoptimeMap);
            }
            stoptimeMap.put(key.substring(key.indexOf("-") + 1), httpServletRequest.getParameter(key));
        }
    }

    RouteOutline theRouteOutline = RouteOutline.findRouteOutline(routeOutline.getId());
    theRouteOutline.setUsername(routeOutline.getUsername());
    theRouteOutline.setRouteName(routeOutline.getRouteName());
    theRouteOutline.setRouteDescription(routeOutline.getRouteDescription());
    theRouteOutline.setSubmittedDateTime(routeOutline.getSubmittedDateTime());

    Route route = theRouteOutline.createAndAssociateNewRoute();
    route.persist();
    theRouteOutline.merge();

    // Stops should be prefixed with 'STOPx_' where the x is the stop number. If this format is used then set the stopId accordingly.
    HashMap<String, Stop> stopMap = new HashMap<String, Stop>();
    for (int i = 0; i < latMap.size(); i++) {
        String index = Integer.toString(i);
        String stopName = descMap.get(index);
        String stopId = null;
        if (stopName.toLowerCase().startsWith("stop")) {
            int pos = stopName.indexOf("_");
            if (pos > 4) {
                stopId = stopName.substring(4, pos);
                stopName = stopName.substring(pos + 1);
            }
        }
        Stop stop = new Stop(stopId != null ? stopId : "XX", stopName, null, latMap.get(index),
                lonMap.get(index));

        // todo Here we may need to set Agency if stop is being reused
        route.addStop(stop);

        stopMap.put(index, stop);
        stop.persist();
    }

    // Create the shape from the GPS data
    // TODO Do we want to do this from the GUI to allow points to be added/moved on the interface?
    GpxToShapeParser gpxToShapeParser = new GpxToShapeParser();
    gpxToShapeParser.parse(theRouteOutline);
    gpxToShapeParser.getShapeCollection().persist();

    for (String tripNumber : tripStoptimeMap.keySet()) {
        Trip trip = new Trip(frequencyMap.get(tripNumber), null, routeOutline.getRouteName(), 0);
        trip.setCalendar(Calendar.findCalendarsByServiceIdEquals(trip.getServiceId()).getSingleResult());
        trip.setShapeCollection(gpxToShapeParser.getShapeCollection());
        route.addTrip(trip);
        trip.persist();

        HashMap<String, String> stoptimeMap = tripStoptimeMap.get(tripNumber);
        for (int i = 0; i < latMap.size(); i++) {
            String index = Integer.toString(i);
            StopTime stopTime = new StopTime(stoptimeMap.get(index), stoptimeMap.get(index), i);
            trip.addStopTime(stopTime);

            Stop stop = stopMap.get(index);
            stop.addStopTime(stopTime);
            stopTime.persist();
        }
    }

    uiModel.asMap().clear();
    return "redirect:/admin/community/routeoutlines/"
            + encodeUrlPathSegment(routeOutline.getId().toString(), httpServletRequest);
}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/book", method = RequestMethod.GET)
public String showPaymentPage(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId,
        //paypal related parameters
        @RequestParam(value = "paymentId", required = false) String paypalPaymentId,
        @RequestParam(value = "PayerID", required = false) String paypalPayerID,
        @RequestParam(value = "paypal-success", required = false) Boolean isPaypalSuccess,
        @RequestParam(value = "paypal-error", required = false) Boolean isPaypalError,
        @RequestParam(value = "fullName", required = false) String fullName,
        @RequestParam(value = "firstName", required = false) String firstName,
        @RequestParam(value = "lastName", required = false) String lastName,
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "billingAddress", required = false) String billingAddress,
        @RequestParam(value = "hmac", required = false) String hmac,
        @RequestParam(value = "postponeAssignment", required = false) Boolean postponeAssignment, Model model,
        Locale locale) {//w w  w  . ja  v  a  2 s . c o m

    return eventRepository.findOptionalByShortName(eventName)
            .map(event -> ticketReservationManager.findById(reservationId).map(reservation -> {

                if (reservation.getStatus() != TicketReservationStatus.PENDING) {
                    return redirectReservation(Optional.of(reservation), eventName, reservationId);
                }

                List<Ticket> ticketsInReservation = ticketReservationManager
                        .findTicketsInReservation(reservationId);
                if (Boolean.TRUE.equals(isPaypalSuccess) && paypalPayerID != null && paypalPaymentId != null) {
                    model.addAttribute("paypalPaymentId", paypalPaymentId)
                            .addAttribute("paypalPayerID", paypalPayerID)
                            .addAttribute("paypalCheckoutConfirmation", true).addAttribute("fullName", fullName)
                            .addAttribute("firstName", firstName).addAttribute("lastName", lastName)
                            .addAttribute("email", email).addAttribute("billingAddress", billingAddress)
                            .addAttribute("hmac", hmac)
                            .addAttribute("postponeAssignment", Boolean.TRUE.equals(postponeAssignment))
                            .addAttribute("showPostpone", Boolean.TRUE.equals(postponeAssignment));
                } else {
                    model.addAttribute("paypalCheckoutConfirmation", false)
                            .addAttribute("postponeAssignment", false)
                            .addAttribute("showPostpone", ticketsInReservation.size() > 1);
                }

                try {
                    model.addAttribute("delayForOfflinePayment", Math.max(1, TicketReservationManager
                            .getOfflinePaymentWaitingPeriod(event, configurationManager)));
                } catch (TicketReservationManager.OfflinePaymentException e) {
                    if (event.getAllowedPaymentProxies().contains(PaymentProxy.OFFLINE)) {
                        log.error("Already started event {} has been found with OFFLINE payment enabled",
                                event.getDisplayName(), e);
                    }
                    model.addAttribute("delayForOfflinePayment", 0);
                }

                OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId,
                        event, locale);
                List<PaymentProxy> activePaymentMethods = paymentManager
                        .getPaymentMethods(event.getOrganizationId()).stream()
                        .filter(p -> TicketReservationManager.isValidPaymentMethod(p, event,
                                configurationManager))
                        .map(PaymentManager.PaymentMethod::getPaymentProxy).collect(toList());

                if (orderSummary.getFree() || activePaymentMethods.stream()
                        .anyMatch(p -> p == PaymentProxy.OFFLINE || p == PaymentProxy.ON_SITE)) {
                    boolean captchaForOfflinePaymentEnabled = configurationManager
                            .isRecaptchaForOfflinePaymentEnabled(event);
                    model.addAttribute("captchaRequestedForOffline", captchaForOfflinePaymentEnabled)
                            .addAttribute("recaptchaApiKey",
                                    configurationManager.getStringConfigValue(
                                            Configuration.getSystemConfiguration(RECAPTCHA_API_KEY), null))
                            .addAttribute("captchaRequestedFreeOfCharge",
                                    orderSummary.getFree() && captchaForOfflinePaymentEnabled);
                }

                boolean invoiceAllowed = configurationManager.hasAllConfigurationsForInvoice(event)
                        || vatChecker.isVatCheckingEnabledFor(event.getOrganizationId());
                PaymentForm paymentForm = PaymentForm.fromExistingReservation(reservation);
                model.addAttribute("multiplePaymentMethods", activePaymentMethods.size() > 1)
                        .addAttribute("orderSummary", orderSummary).addAttribute("reservationId", reservationId)
                        .addAttribute("reservation", reservation)
                        .addAttribute("pageTitle", "reservation-page.header.title").addAttribute("event", event)
                        .addAttribute("activePaymentMethods", activePaymentMethods)
                        .addAttribute("expressCheckoutEnabled", isExpressCheckoutEnabled(event, orderSummary))
                        .addAttribute("useFirstAndLastName", event.mustUseFirstAndLastName())
                        .addAttribute("countries", TicketHelper.getLocalizedCountries(locale))
                        .addAttribute("euCountries",
                                TicketHelper.getLocalizedEUCountries(locale,
                                        configurationManager.getRequiredValue(
                                                getSystemConfiguration(ConfigurationKeys.EU_COUNTRIES_LIST))))
                        .addAttribute("euVatCheckingEnabled",
                                vatChecker.isVatCheckingEnabledFor(event.getOrganizationId()))
                        .addAttribute("invoiceIsAllowed", invoiceAllowed)
                        .addAttribute("vatNrIsLinked",
                                orderSummary.isVatExempt() || paymentForm.getHasVatCountryCode())
                        .addAttribute("billingAddressLabel", invoiceAllowed ? "reservation-page.billing-address"
                                : "reservation-page.receipt-address");

                boolean includeStripe = !orderSummary.getFree()
                        && activePaymentMethods.contains(PaymentProxy.STRIPE);
                model.addAttribute("includeStripe", includeStripe);
                if (includeStripe) {
                    model.addAttribute("stripe_p_key", paymentManager.getStripePublicKey(event));
                }
                Map<String, Object> modelMap = model.asMap();
                modelMap.putIfAbsent("paymentForm", paymentForm);
                modelMap.putIfAbsent("hasErrors", false);

                boolean hasPaidSupplement = ticketReservationManager.hasPaidSupplements(reservationId);
                model.addAttribute("ticketsByCategory", ticketsInReservation.stream()
                        .collect(Collectors.groupingBy(Ticket::getCategoryId)).entrySet().stream().map((e) -> {
                            TicketCategory category = eventManager.getTicketCategoryById(e.getKey(),
                                    event.getId());
                            List<TicketDecorator> decorators = TicketDecorator
                                    .decorate(e.getValue(),
                                            !hasPaidSupplement && configurationManager.getBooleanConfigValue(
                                                    Configuration.from(event.getOrganizationId(), event.getId(),
                                                            category.getId(), ALLOW_FREE_TICKETS_CANCELLATION),
                                                    false),
                                            eventManager.checkTicketCancellationPrerequisites(),
                                            ticket -> ticketHelper.findTicketFieldConfigurationAndValue(
                                                    event.getId(), ticket, locale),
                                            true, (t) -> "tickets['" + t.getUuid() + "'].");
                            return Pair.of(category, decorators);
                        }).collect(toList()));
                return "/event/reservation-page";
            }).orElseGet(() -> redirectReservation(Optional.empty(), eventName, reservationId)))
            .orElse("redirect:/");
}

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) {// w w w . j  a  v  a 2  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:com.jd.survey.web.security.AccountController.java

/**
 * Updates logged in user information//from   w  w w. ja va 2  s  .  c om
 * @param proceed
 * @param user
 * @param bindingResult
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid User user,
        BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {
        User loggedInUser = userService.user_findByLogin(principal.getName());
        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                uiModel.addAttribute("user", user);
                return "account/update";
            }
            if (userService.user_findByLogin(user.getLogin()) != null
                    && userService.user_ValidateLoginIsUnique(user) == true) {
                bindingResult.rejectValue("login", "field_unique");
                uiModel.addAttribute("user", user);
                return "account/update";
            }
            if (userService.user_findByEmail(user.getEmail()) != null
                    && userService.user_ValidateEmailIsUnique(user) == true) {
                bindingResult.rejectValue("email", "field_unique");
                uiModel.addAttribute("user", user);
                return "account/update";
            }
            uiModel.asMap().clear();
            user = userService.user_updateInformation(user);
            return "redirect:/account/show";

        } else {
            return "redirect:/account/show";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.security.AccountController.java

/**
 * Updates  logged in user password/*from   w w w . j  av  a 2 s .  co m*/
 * @param oldPassword
 * @param newPassword
 * @param newPasswordConfirm
 * @param proceed
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/rpass", method = RequestMethod.POST, produces = "text/html")
public String updatePasswordPost(@RequestParam(value = "password", required = true) String oldPassword,
        @RequestParam(value = "nPassword", required = true) String newPassword,
        @RequestParam(value = "cPassword", required = true) String newPasswordConfirm,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        if (proceed != null) {

            //check that the old password is correct
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    principal.getName(), oldPassword);
            authenticationToken.setDetails(new WebAuthenticationDetails(httpServletRequest));
            try {
                Authentication auth = authenticationManager.authenticate(authenticationToken);
                if (auth == null || !auth.isAuthenticated()) {
                    //invalid password enetered
                    uiModel.asMap().clear();
                    uiModel.addAttribute("status", "E"); //Unmatching Passwords
                    return "account/rpass";
                }

            } catch (AuthenticationException e) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "E"); //Unmatching Passwords
                return "account/rpass";
            }
            //Check new password strenght 
            if (!GenericValidator.matchRegexp(newPassword, globalSettings.getPasswordEnforcementRegex())) {
                uiModel.asMap().clear();
                uiModel.addAttribute("status", "I"); //Unmatching Passwords
                return "account/rpass";
            }
            //check that passwords match    
            if (!newPassword.equals(newPasswordConfirm)) {
                uiModel.asMap().clear();

                uiModel.addAttribute("status", "U"); //Unmatching Passwords
                return "account/rpass";
            }
            User loggedInUser = userService.user_findByLogin(principal.getName());
            //All validations passed, save the HASH of the password in the database
            loggedInUser.setPassword(newPassword);
            userService.user_updatePassword(loggedInUser);
            uiModel.addAttribute("status", "S");//success
            return "account/rpass";
        } else {
            return "redirect:/account/show";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.security.AuthorityController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(@Valid Authority authority, BindingResult bindingResult, Principal principal,
        Model uiModel, HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {/*from   w  w  w  .j  a  v a  2  s  . com*/
        User user = userService.user_findByLogin(principal.getName());
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, authority, user);
            return "security/authorities/create";
        }
        if (!userService.authority_ValidateNameIsUnique(authority)) {
            bindingResult.rejectValue("name", "field_unique");
            populateEditForm(uiModel, authority, user);
            return "security/authorities/create";
        }

        uiModel.asMap().clear();
        authority = userService.authority_merge(authority);
        return "redirect:/security/authorities/"
                + encodeUrlPathSegment(authority.getId().toString(), httpServletRequest);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}