Example usage for org.springframework.validation BindingResult reject

List of usage examples for org.springframework.validation BindingResult reject

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult reject.

Prototype

void reject(String errorCode);

Source Link

Document

Register a global error for the entire target object, using the given error description.

Usage

From source file:alfio.controller.api.user.RestEventApiController.java

@RequestMapping(value = "events/{shortName}/reserve-tickets", method = RequestMethod.POST)
public ResponseEntity<Result<String>> reserveTickets(@PathVariable("shortName") String shortName,
        @RequestBody ReservationForm reservation, BindingResult bindingResult, Locale locale) {
    return eventRepository.findOptionalByShortName(shortName).map(event -> {
        Optional<String> reservationUrl = reservation.validate(bindingResult, ticketReservationManager,
                additionalServiceRepository, eventManager, event).flatMap(selected -> {
                    Date expiration = DateUtils.addMinutes(new Date(),
                            ticketReservationManager.getReservationTimeout(event));
                    try {
                        String reservationId = ticketReservationManager.createTicketReservation(event,
                                selected.getLeft(), selected.getRight(), expiration,
                                Optional.ofNullable(reservation.getPromoCode()), //FIXME check
                                Optional.ofNullable(reservation.getPromoCode()), //FIXME check
                                locale, false);
                        return Optional.of("/event/" + shortName + "/reservation/" + reservationId + "/book");
                    } catch (TicketReservationManager.NotEnoughTicketsException nete) {
                        bindingResult.reject(ErrorsCode.STEP_1_NOT_ENOUGH_TICKETS);
                    } catch (TicketReservationManager.MissingSpecialPriceTokenException missing) {
                        bindingResult.reject(ErrorsCode.STEP_1_ACCESS_RESTRICTED);
                    } catch (TicketReservationManager.InvalidSpecialPriceTokenException invalid) {
                        bindingResult.reject(ErrorsCode.STEP_1_CODE_NOT_FOUND);
                    }//from w  w  w  . jav  a 2 s  .c o  m
                    return Optional.empty();
                });

        Result<String> result = reservationUrl.map(url -> Result.success(url))
                .orElseGet(() -> Result.validationError(bindingResult.getAllErrors()));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}", method = RequestMethod.POST)
public String handleReservation(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId, PaymentForm paymentForm,
        BindingResult bindingResult, Model model, HttpServletRequest request, Locale locale,
        RedirectAttributes redirectAttributes) {

    Optional<Event> eventOptional = eventRepository.findOptionalByShortName(eventName);
    if (!eventOptional.isPresent()) {
        return "redirect:/";
    }/*  w w w  .ja  v  a  2s.  c o  m*/
    Event event = eventOptional.get();
    Optional<TicketReservation> ticketReservation = ticketReservationManager.findById(reservationId);
    if (!ticketReservation.isPresent()) {
        return redirectReservation(ticketReservation, eventName, reservationId);
    }
    if (paymentForm.shouldCancelReservation()) {
        ticketReservationManager.cancelPendingReservation(reservationId, false);
        SessionUtil.removeSpecialPriceData(request);
        return "redirect:/event/" + eventName + "/";
    }
    if (!ticketReservation.get().getValidity().after(new Date())) {
        bindingResult.reject(ErrorsCode.STEP_2_ORDER_EXPIRED);
    }

    final TotalPrice reservationCost = ticketReservationManager.totalReservationCostWithVAT(reservationId);
    if (isCaptchaInvalid(reservationCost.getPriceWithVAT(), paymentForm.getPaymentMethod(), request, event)) {
        log.debug("captcha validation failed.");
        bindingResult.reject(ErrorsCode.STEP_2_CAPTCHA_VALIDATION_FAILED);
    }

    if (paymentForm.getPaymentMethod() != PaymentProxy.PAYPAL || !paymentForm.hasPaypalTokens()) {
        if (!paymentForm.isPostponeAssignment()
                && !ticketRepository.checkTicketUUIDs(reservationId, paymentForm.getTickets().keySet())) {
            bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA);
        }
        paymentForm.validate(bindingResult, reservationCost, event,
                ticketFieldRepository.findAdditionalFieldsForEvent(event.getId()));
        if (bindingResult.hasErrors()) {
            SessionUtil.addToFlash(bindingResult, redirectAttributes);
            return redirectReservation(ticketReservation, eventName, reservationId);
        }
    }

    CustomerName customerName = new CustomerName(paymentForm.getFullName(), paymentForm.getFirstName(),
            paymentForm.getLastName(), event);

    //handle paypal redirect!
    if (paymentForm.getPaymentMethod() == PaymentProxy.PAYPAL && !paymentForm.hasPaypalTokens()) {
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event,
                locale);
        try {
            String checkoutUrl = paymentManager.createPaypalCheckoutRequest(event, reservationId, orderSummary,
                    customerName, paymentForm.getEmail(), paymentForm.getBillingAddress(), locale,
                    paymentForm.isPostponeAssignment());
            assignTickets(eventName, reservationId, paymentForm, bindingResult, request, true);
            return "redirect:" + checkoutUrl;
        } catch (Exception e) {
            bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_REQUEST_CREATION);
            SessionUtil.addToFlash(bindingResult, redirectAttributes);
            return redirectReservation(ticketReservation, eventName, reservationId);
        }
    }

    //handle mollie redirect
    if (paymentForm.getPaymentMethod() == PaymentProxy.MOLLIE) {
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event,
                locale);
        try {
            String checkoutUrl = mollieManager.createCheckoutRequest(event, reservationId, orderSummary,
                    customerName, paymentForm.getEmail(), paymentForm.getBillingAddress(), locale,
                    paymentForm.isInvoiceRequested(), paymentForm.getVatCountryCode(), paymentForm.getVatNr(),
                    ticketReservation.get().getVatStatus());
            assignTickets(eventName, reservationId, paymentForm, bindingResult, request, true);
            return "redirect:" + checkoutUrl;
        } catch (Exception e) {
            bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_REQUEST_CREATION);
            SessionUtil.addToFlash(bindingResult, redirectAttributes);
            return redirectReservation(ticketReservation, eventName, reservationId);
        }
    }
    //

    final PaymentResult status = ticketReservationManager.confirm(paymentForm.getToken(),
            paymentForm.getPaypalPayerID(), event, reservationId, paymentForm.getEmail(), customerName, locale,
            paymentForm.getBillingAddress(), reservationCost,
            SessionUtil.retrieveSpecialPriceSessionId(request),
            Optional.ofNullable(paymentForm.getPaymentMethod()), paymentForm.isInvoiceRequested(),
            paymentForm.getVatCountryCode(), paymentForm.getVatNr(), ticketReservation.get().getVatStatus());

    if (!status.isSuccessful()) {
        String errorMessageCode = status.getErrorCode().get();
        MessageSourceResolvable message = new DefaultMessageSourceResolvable(
                new String[] { errorMessageCode, StripeManager.STRIPE_UNEXPECTED });
        bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_PROCESSING_ERROR,
                new Object[] { messageSource.getMessage(message, locale) }, null);
        SessionUtil.addToFlash(bindingResult, redirectAttributes);
        return redirectReservation(ticketReservation, eventName, reservationId);
    }

    //
    TicketReservation reservation = ticketReservationManager.findById(reservationId)
            .orElseThrow(IllegalStateException::new);
    sendReservationCompleteEmail(request, event, reservation);
    sendReservationCompleteEmailToOrganizer(request, event, reservation);
    //

    if (paymentForm.getPaymentMethod() != PaymentProxy.PAYPAL) {
        assignTickets(eventName, reservationId, paymentForm, bindingResult, request,
                paymentForm.getPaymentMethod() == PaymentProxy.OFFLINE);
    }

    return "redirect:/event/" + eventName + "/reservation/" + reservationId + "/success";
}

From source file:alfio.controller.EventController.java

private String validateAndReserve(String eventName, ReservationForm reservation, BindingResult bindingResult,
        ServletWebRequest request, RedirectAttributes redirectAttributes, Locale locale, Event event) {
    final String redirectToEvent = "redirect:/event/" + eventName + "/";
    return reservation
            .validate(bindingResult, ticketReservationManager, additionalServiceRepository, eventManager, event)
            .map(selected -> {/*from   w w  w . j  a va  2s  .  c  om*/

                Date expiration = DateUtils.addMinutes(new Date(),
                        ticketReservationManager.getReservationTimeout(event));

                try {
                    String reservationId = ticketReservationManager.createTicketReservation(event,
                            selected.getLeft(), selected.getRight(), expiration,
                            SessionUtil.retrieveSpecialPriceSessionId(request.getRequest()),
                            SessionUtil.retrievePromotionCodeDiscount(request.getRequest()), locale, false);
                    return "redirect:/event/" + eventName + "/reservation/" + reservationId + "/book";
                } catch (TicketReservationManager.NotEnoughTicketsException nete) {
                    bindingResult.reject(ErrorsCode.STEP_1_NOT_ENOUGH_TICKETS);
                    addToFlash(bindingResult, redirectAttributes);
                    return redirectToEvent;
                } catch (TicketReservationManager.MissingSpecialPriceTokenException missing) {
                    bindingResult.reject(ErrorsCode.STEP_1_ACCESS_RESTRICTED);
                    addToFlash(bindingResult, redirectAttributes);
                    return redirectToEvent;
                } catch (TicketReservationManager.InvalidSpecialPriceTokenException invalid) {
                    bindingResult.reject(ErrorsCode.STEP_1_CODE_NOT_FOUND);
                    addToFlash(bindingResult, redirectAttributes);
                    SessionUtil.removeSpecialPriceData(request.getRequest());
                    return redirectToEvent;
                }
            }).orElseGet(() -> {
                addToFlash(bindingResult, redirectAttributes);
                return redirectToEvent;
            });
}

From source file:fragment.web.UsersControllerTest.java

@Test
public void testUpdateUserFail() throws Exception {
    asRoot();//from   w  w w.  j a  v a2  s . c  om
    User user = userDAO.find(3L);
    UserForm form = new UserForm((com.citrix.cpbm.access.User) CustomProxy.newInstance(user));
    form.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    user.setFirstName("Updated");
    form.setUserClone((com.citrix.cpbm.access.User) CustomProxy.newInstance((User) user.clone()));
    BindingResult result = validate(form);
    result.reject("dummy");
    String view = controller.edit(user.getParam(), form, result,
            getRequestTemplate(HttpMethod.POST, "/users/" + user.getUuid() + "/myprofile"), map, status);
    Assert.assertEquals("redirect:/portal/users/" + user.getUuid() + "/myprofile", view);
    Object o = map.get("user");
    Assert.assertNull(o);
    Assert.assertFalse(status.isComplete());
}

From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java

/**
 * @should work for an example/*from   w w w  .  j  a v a 2s  .  co  m*/
 */
@RequestMapping(value = "/phr/user.form", method = RequestMethod.POST)
public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model,
        @RequestParam(required = false, value = "action") final String action,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") final String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") final String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") final String[] roles,
        @RequestParam(required = false, value = "createNewPerson") final String createNewPerson,
        @RequestParam(required = false, value = "sharingToken") String sharingToken,
        @ModelAttribute("user") final User user, final BindingResult errors) {

    if (sharingToken == null) {
        sharingToken = (String) model.get("sharingToken");
    }

    log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken);
    //add temporary privileges
    boolean isTemporary = false;
    boolean isAdministrator = false;
    if (!Context.isAuthenticated()) {
        Context.authenticate("temporary", "Temporary8");
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        Context.addProxyPrivilege("PHR Restricted Patient Access");
        isTemporary = true;
        log.debug("Added proxy privileges!");
    } else {
        if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue()
                .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) {
            isAdministrator = true;
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        }
    }

    try {
        final UserService us = Context.getUserService();
        final MessageSourceService mss = Context.getMessageSourceService();

        if (mss.getMessage("User.assumeIdentity").equals(action)) {
            Context.becomeUser(user.getSystemId());
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
            return "redirect:/phr/index.htm";

        } else if (mss.getMessage("User.delete").equals(action)) {
            try {
                Context.getUserService().purgeUser(user);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
                return "redirect:/phr/user.list";
            } catch (final Exception ex) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
                log.error("Failed to delete user", ex);
                return "redirect:/phr/user.form?userId=" + request.getParameter("userId");
            }

        } else if (mss.getMessage("User.retire").equals(action)) {
            final String retireReason = request.getParameter("retireReason");
            if (!(StringUtils.hasText(retireReason))) {
                errors.rejectValue("retireReason", "User.disableReason.empty");
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            } else {
                us.retireUser(user, retireReason);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
            }

        } else if (mss.getMessage("User.unRetire").equals(action)) {
            us.unretireUser(user);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
        } else {
            // check if username is already in the database
            if (us.hasDuplicateUsername(user)) {
                errors.rejectValue("username", "error.username.taken");
            }

            // check if password and password confirm are identical
            if ((password == null) || password.equals("XXXXXXXXXXXXXXX")) {
                password = "";
            }
            if ((confirm == null) || confirm.equals("XXXXXXXXXXXXXXX")) {
                confirm = "";
            }

            if (!password.equals(confirm)) {
                errors.reject("error.password.match");
            }

            if ((password.length() == 0) && isNewUser(user)) {
                errors.reject("error.password.weak");
            }

            //check password strength
            if (password.length() > 0) {
                try {
                    OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
                } catch (final PasswordException e) {
                    errors.reject(e.getMessage());
                }
            }

            final Set<Role> newRoles = new HashSet<Role>();
            if (roles != null) {
                for (final String r : roles) {
                    // Make sure that if we already have a detached instance of this role in the
                    // user's roles, that we don't fetch a second copy of that same role from
                    // the database, or else hibernate will throw a NonUniqueObjectException.
                    Role role = null;
                    if (user.getRoles() != null) {
                        for (final Role test : user.getRoles()) {
                            if (test.getRole().equals(r)) {
                                role = test;
                            }
                        }
                    }
                    if (role == null) {
                        role = us.getRole(r);
                        user.addRole(role);
                    }
                    newRoles.add(role);
                }
            } else {
                final Role role = us.getRole("PHR Restricted User");
                newRoles.add(role);
                user.addRole(role);
                log.debug("Added PHR Restricted User role only: " + role);
            }

            if (user.getRoles() == null) {
                newRoles.clear();
            } else {
                user.getRoles().retainAll(newRoles);
            }

            final String[] keys = request.getParameterValues("property");
            final String[] values = request.getParameterValues("value");

            if ((keys != null) && (values != null)) {
                for (int x = 0; x < keys.length; x++) {
                    final String key = keys[x];
                    final String val = values[x];
                    user.setUserProperty(key, val);
                }
            }

            new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);

            final UserValidator uv = new UserValidator();
            uv.validate(user, errors);

            if (errors.hasErrors()) {
                log.debug("errors validating user: " + errors.getErrorCount() + errors.toString());
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            }

            String emailEntered = request.getParameter("9");

            if (isNewUser(user) && !isAdministrator) {
                log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken);
                final PhrSharingToken token = Context.getService(PhrSharingTokenService.class)
                        .getSharingToken(sharingToken);

                //check token existence and name matching
                if (token == null || token.getExpireDate().before(new Date())) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register without a valid sharing token");
                    log.error("Failed to register without a valid sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register without a valid sharing token; user_name="
                                    + user.getName());

                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }
                    return "redirect:/phr/index.htm?noredirect=true";
                } else if ((token != null) && (token.getRelatedPerson() != null)) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register with a used sharing token");
                    log.error("Failed to register with a used sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register with a used sharing token; user_name=" + user.getName()
                                    + "; sharingToken=" + token);
                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }

                    return "redirect:/phr/index.htm?noredirect=true";
                } else if (emailEntered != null
                        && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) {
                    // look for person attributes (including email entered) in the request and save to user
                    for (final PersonAttributeType type : Context.getPersonService()
                            .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) {
                        final String paramName = type.getPersonAttributeTypeId().toString();
                        final String value = request.getParameter(paramName);

                        this.log.debug("paramName=" + paramName);

                        // if there is an error displaying the attribute, the value will be null
                        if (value != null) {
                            final PersonAttribute attribute = new PersonAttribute(type, value);
                            try {
                                final Object hydratedObject = attribute.getHydratedObject();
                                if ((hydratedObject == null) || "".equals(hydratedObject.toString())) {
                                    // if null is returned, the value should be blanked out
                                    attribute.setValue("");
                                } else if (hydratedObject instanceof Attributable) {
                                    attribute.setValue(((Attributable) hydratedObject).serialize());
                                } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) {
                                    // if the classes doesn't match the format, the hydration failed somehow
                                    // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors?
                                    throw new APIException();
                                }
                            } catch (final APIException e) {
                                errors.rejectValue("attributeMap[" + type.getName() + "]",
                                        "Invalid value for " + type.getName() + ": '" + value + "'");
                                this.log.warn("Got an invalid value: " + value
                                        + " while setting personAttributeType id #" + paramName, e);

                                // setting the value to empty so that the user can reset the value to something else
                                attribute.setValue("");

                            }
                            user.getPerson().addAttribute(attribute);
                        }
                    }

                    //create a new user by self registration
                    us.saveUser(user, password);

                    //update sharing token
                    token.setRelatedPerson(user.getPerson());
                    token.setChangedBy(user);
                    final Date date = new Date();
                    token.setDateChanged(date);
                    token.setActivateDate(date);
                    Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up");
                    log.debug("New self-registered user created: " + user.getUsername());
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user,
                            httpSession.getId(), null, "info=New self-registered user created; user_name="
                                    + user.getName() + "; sharingToken=" + token);

                    //save email to messaging service
                    Integer addressId = saveEmail(user.getPerson(), emailEntered);

                    //set default messaging alert address
                    boolean shouldAlert = true;
                    PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId);

                    //send email notification

                    // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ...
                    final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24";

                    final String url = deployUrl + "/openmrs/phr/index.htm";
                    final String passwordOption = Context.getAdministrationService()
                            .getGlobalProperty("personalhr.show.password");

                    String notification = NOTIFICATION_TEMPLATE;
                    notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON",
                            user.getPerson().getGivenName());
                    notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername());
                    notification = notification.replaceAll("OPENMRS_PASSWORD",
                            showPassword(password, passwordOption));
                    notification = notification.replaceAll("OPENMRS_URL", url);

                    PersonalhrUtil.sendEmail(emailEntered, notification);
                } else {
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                            "Failed to create new user due to email mismatch: " + emailEntered);
                    log.debug("Failed to create new user due to email mismatch: "
                            + token.getRelatedPersonEmail() + " vs " + emailEntered);
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "info=Failed to create new user due to email mismatch: "
                                    + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken="
                                    + token);
                }
            } else if (isNewUser(user) && isAdministrator) {
                //create a new user by PHR Administrator
                us.saveUser(user, password);
            } else {
                //modify an exiting user
                us.saveUser(user, null);

                if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
                    if (log.isDebugEnabled()) {
                        log.debug("calling changePassword for user " + user + " by user "
                                + Context.getAuthenticatedUser());
                    }
                    us.changePassword(user, password);
                }
                log.debug("Existing user " + user.getUsername() + " changed by user "
                        + Context.getAuthenticatedUser().getUsername());
                PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(),
                        Context.getAuthenticatedUser(), httpSession.getId(), null,
                        "info=Existing user updated; user_name=" + user.getName());
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }

            if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
                us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }
        }
    } finally {
        //remove temporary privileges
        if (isTemporary) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            Context.removeProxyPrivilege("PHR Restricted Patient Access");
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            Context.logout();
            log.debug("Removed proxy privileges for self registration!");
        } else if (isAdministrator) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            log.debug("Removed proxy privileges for PHR Administrator!");
        }
    }
    return "redirect:/phr/index.htm?noredirect=true";
}

From source file:com.luna.common.web.upload.FileUploadUtils.java

/**
 * ?//from  w w w  .  j av a2  s.c  o m
 *
 * @param request          ?
 * @param file             
 * @param result           ?
 * @param allowedExtension ?
 * @return
 */
public static final String upload(HttpServletRequest request, MultipartFile file, BindingResult result,
        String[] allowedExtension) {
    try {
        return upload(request, getDefaultBaseDir(), file, allowedExtension, DEFAULT_MAX_SIZE, true);
    } catch (IOException e) {
        log.error("file upload error", e);
        result.reject("upload.server.error");
    } catch (InvalidExtensionException.InvalidImageExtensionException e) {
        result.reject("upload.not.allow.image.extension");
    } catch (InvalidExtensionException.InvalidFlashExtensionException e) {
        result.reject("upload.not.allow.flash.extension");
    } catch (InvalidExtensionException.InvalidMediaExtensionException e) {
        result.reject("upload.not.allow.media.extension");
    } catch (InvalidExtensionException e) {
        result.reject("upload.not.allow.extension");
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        result.reject("upload.exceed.maxSize");
    } catch (FileNameLengthLimitExceededException e) {
        result.reject("upload.filename.exceed.length");
    }
    return null;
}

From source file:com.thinker.arch.common.web.upload.FileUploadUtils.java

/**
 * ?/*from   w  w w  .  j av a 2s .  c  o m*/
 *
 * @param request          ?
 * @param file             
 * @param result           ?
 * @param allowedExtension ?
 * @return
 */
public static final String upload(HttpServletRequest request, MultipartFile file, BindingResult result,
        String[] allowedExtension) {
    try {
        return upload(request, getDefaultBaseDir(), file, allowedExtension, DEFAULT_MAX_SIZE, true);
    } catch (IOException e) {
        LogUtils.logError("file upload error", e);
        result.reject("upload.server.error");
    } catch (InvalidExtensionException.InvalidImageExtensionException e) {
        result.reject("upload.not.allow.image.extension");
    } catch (InvalidExtensionException.InvalidFlashExtensionException e) {
        result.reject("upload.not.allow.flash.extension");
    } catch (InvalidExtensionException.InvalidMediaExtensionException e) {
        result.reject("upload.not.allow.media.extension");
    } catch (InvalidExtensionException e) {
        result.reject("upload.not.allow.extension");
    } catch (FileSizeLimitExceededException e) {
        result.reject("upload.exceed.maxSize");
    } catch (FileNameLengthLimitExceededException e) {
        result.reject("upload.filename.exceed.length");
    }
    return null;
}

From source file:com.yqboots.dict.web.controller.DataDictController.java

@PreAuthorize(DataDictPermissions.WRITE)
@RequestMapping(value = WebKeys.MAPPING_ROOT, method = RequestMethod.POST)
public String update(@Valid @ModelAttribute(WebKeys.MODEL) final DataDict dict,
        final BindingResult bindingResult, final ModelMap model) {
    if (bindingResult.hasErrors()) {
        return VIEW_FORM;
    }/*from  w  w  w.  j  a va  2s  . c  o  m*/

    try {
        dataDictManager.update(dict);
    } catch (DataDictExistsException e) {
        bindingResult.reject("I0001");
        return VIEW_FORM;
    }

    model.clear();

    return REDIRECT_VIEW_PATH;
}

From source file:com.yqboots.menu.web.controller.MenuItemController.java

@PreAuthorize(MenuItemPermissions.WRITE)
@RequestMapping(value = WebKeys.MAPPING_ROOT, method = RequestMethod.POST)
public String update(@Valid @ModelAttribute(WebKeys.MODEL) final MenuItem menuItem,
        final BindingResult bindingResult, final ModelMap model) {
    if (bindingResult.hasErrors()) {
        return VIEW_FORM;
    }//from  w w w. ja  v  a 2s  . com

    try {
        menuItemManager.update(menuItem);
    } catch (MenuItemExistsException e) {
        bindingResult.reject("I0001");
        return VIEW_FORM;
    }

    model.clear();

    return REDIRECT_VIEW_PATH;
}

From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java

@RequestMapping(value = { "edit/{eventId}/groupdraws" }, method = POST)
public ModelAndView postGroupDraws(@PathVariable("eventId") Long eventId,
        @ModelAttribute("Model") @Valid EventGroups eventGroups, BindingResult bindingResult,
        HttpServletRequest request) {/* w  ww.  ja  va 2  s.  com*/
    Event event = eventDAO.findByIdFetchWithParticipantsAndGames(eventId);
    Iterator<Map.Entry<Integer, Set<Participant>>> iterator = eventGroups.getGroupParticipants().entrySet()
            .iterator();
    while (iterator.hasNext()) {
        Map.Entry<Integer, Set<Participant>> entry = iterator.next();
        if (entry.getValue() == null) {
            bindingResult.reject("PleaseSelectParticipantsForEachGroup");
        }
    }

    //prevent modification of group draws if knockout round games have already begun
    if (event.getEventType().equals(EventType.Knockout)) {
        SortedMap<Integer, List<Game>> roundGames = eventsUtil.getRoundGameMap(event);
        if (!roundGames.isEmpty()) {
            bindingResult.reject("CannotModifyEventAfterGroupPhaseHasEnded");
        }
    }

    if (bindingResult.hasErrors()) {
        return getGroupDrawsView(event, eventGroups);
    }

    //remove games that have not been played yet
    gameUtil.removeObsoleteGames(event);

    //remove games with teams that are no longer part of a group
    Iterator<Game> gameIterator = event.getGames().iterator();
    while (gameIterator.hasNext()) {
        Game game = gameIterator.next();
        Integer groupNumber = game.getGroupNumber();
        if (groupNumber != null) {
            Set<Participant> groupParticipants = eventGroups.getGroupParticipants().get(groupNumber);
            if (!groupParticipants.containsAll(game.getParticipants())) {
                gameDAO.deleteById(game.getId());
                gameIterator.remove();
            }
        }
    }

    //create missing games
    for (int groupNumber = 0; groupNumber < event.getNumberOfGroups(); groupNumber++) {
        Set<Participant> groupParticipants = eventGroups.getGroupParticipants().get(groupNumber);
        Integer roundNumber = null;
        switch (event.getEventType()) {
        case GroupKnockout:
            //for GroupKnockout events, only knockout games have a round
            roundNumber = ROUND_NONE;
            break;
        case GroupTwoRounds:
            //for GroupTwoRound events, every round has a number
            roundNumber = ROUND_ONE;
            break;
        }
        gameUtil.createMissingGames(event, groupParticipants, groupNumber, roundNumber);
    }

    return new ModelAndView("redirect:/admin/events/edit/" + eventId + "/groupschedule");
}