Example usage for org.springframework.validation BindingResult MODEL_KEY_PREFIX

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

Introduction

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

Prototype

String MODEL_KEY_PREFIX

To view the source code for org.springframework.validation BindingResult MODEL_KEY_PREFIX.

Click Source Link

Document

Prefix for the name of the BindingResult instance in a model, followed by the object name.

Usage

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleEditBuildNumberPost02() throws IOException, ServletException {
    this.setUpSecurity();

    SharedBuildNumber originalNumber = new SharedBuildNumber(37);

    expect(this.request.getParameter("action")).andReturn("edit");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("id")).andReturn("37");
    expect(this.service.getSharedBuildNumber(37)).andReturn(originalNumber);
    expect(this.request.getParameter("name")).andReturn("help");
    expect(this.request.getParameter("description")).andReturn("");
    expect(this.request.getParameter("format")).andReturn("{0");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("15.1");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/editBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);
    assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX,
            model.get("sbnParameterPrefix"));

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());/*ww w.j  a va  2 s. com*/
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 3 errors.", 3, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 3, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "name", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The name must be between 5 and 60 characters long.", errors.get(1).getDefaultMessage());
    assertEquals("The third error is not correct.", "format", errors.get(2).getField());
    assertEquals("The third error has the wrong message.",
            "The build number format must be at least 3 characters long.", errors.get(2).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "help", form.getName());
    assertEquals("The description is not correct.", "", form.getDescription());
    assertEquals("The format is not correct.", "{0", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleEditBuildNumberPost03() throws IOException, ServletException {
    this.setUpSecurity();

    SharedBuildNumber originalNumber = new SharedBuildNumber(26);

    expect(this.request.getParameter("action")).andReturn("edit");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("id")).andReturn("26");
    expect(this.service.getSharedBuildNumber(26)).andReturn(originalNumber);
    expect(this.request.getParameter("name")).andReturn("Hello");
    expect(this.request.getParameter("description")).andReturn("This is a description.");
    expect(this.request.getParameter("format")).andReturn("1.0.0.{D}");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("-16");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/editBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);
    assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX,
            model.get("sbnParameterPrefix"));

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());/*  w  w  w  .  ja  v a2  s  .c  o  m*/
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 2 errors.", 2, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 2, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "dateFormat", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The date format must be at least 3 characters long.", errors.get(1).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "Hello", form.getName());
    assertEquals("The description is not correct.", "This is a description.", form.getDescription());
    assertEquals("The format is not correct.", "1.0.0.{D}", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}

From source file:com.octanner.controllers.AbstractProductConfigController.java

protected void populateConfigurationModel(final KBKeyData kbKey, final String configId,
        final String selectedGroup, final Model model, final UiStatus uiStatus,
        final String cartEntryHandleFromRequest) {
    if (model.containsAttribute(Octsapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE)) {
        return;//from   ww w . j  a v a2 s.  c o m
    }

    final ConfigurationData configData;
    if (configId != null) {
        configData = reloadConfiguration(kbKey, configId, selectedGroup, uiStatus);
    } else {
        configData = loadNewConfiguration(kbKey, selectedGroup);
    }

    if (cartEntryHandleFromRequest == null) {
        setCartItemPk(configData);
    } else {
        configData.setCartItemPK(cartEntryHandleFromRequest);
    }

    model.addAttribute(Octsapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE, configData);

    final BindingResult errors = getBindingResultForConfig(configData);
    model.addAttribute(BindingResult.MODEL_KEY_PREFIX + Octsapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE,
            errors);

}

From source file:de.hybris.platform.sap.productconfig.frontend.controllers.AbstractProductConfigController.java

protected void populateConfigurationModel(final KBKeyData kbKey, final String configId,
        final String selectedGroup, final Model model, final UiStatus uiStatus,
        final String cartEntryHandleFromRequest) {
    if (model.containsAttribute(Sapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE)) {
        return;//from   ww w. j  a  va 2  s  .  co m
    }

    final ConfigurationData configData;
    if (configId != null) {
        configData = reloadConfiguration(kbKey, configId, selectedGroup, uiStatus);
    } else {
        configData = loadNewConfiguration(kbKey, selectedGroup);
    }

    if (cartEntryHandleFromRequest == null) {
        setCartItemPk(configData);
    } else {
        configData.setCartItemPK(cartEntryHandleFromRequest);
    }

    model.addAttribute(Sapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE, configData);

    final BindingResult errors = getBindingResultForConfig(configData);
    model.addAttribute(BindingResult.MODEL_KEY_PREFIX + Sapproductconfigb2baddonConstants.CONFIG_ATTRIBUTE,
            errors);

}

From source file:org.egov.infra.web.spring.interceptor.DuplicateFormSubmissionInterceptor.java

private static BindingResult getBindingResult(final ModelAndView modelAndView) {
    final Set<String> paramNames = modelAndView.getModelMap().keySet();
    return (BindingResult) modelAndView.getModelMap().get(paramNames.parallelStream()
            .filter(e -> e.startsWith(BindingResult.MODEL_KEY_PREFIX)).findFirst().get());
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Updates details in UDDI for this dataset.
 * // w ww  . j a va2  s  .  c  om
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView completeManualRegistration(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    // bind to object
    ResourceDetail resource = new ResourceDetail();
    ServletRequestDataBinder binder = createBinder(request, resource);
    initBinder(request, binder);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    validateDataResource(resource, result);
    logger.info("Adding the resource: " + resource.getName());

    if (result.hasErrors()) {
        logger.info("Errors have occurred: " + result);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put(REQUEST_RESOURCE, resource);
        data.putAll(referenceDataForResourceList(request));
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_RESOURCE, result);
        data.put("editableEndpoint", true);
        // put the errors in the request
        return new ModelAndView("registrationResourceManual", data);
    } else {
        String businessKey = request.getParameter("businessKey");
        uddiUtils.updateResource(resource, businessKey);
        return new ModelAndView(new RedirectView(
                request.getContextPath() + "/register/showDataResources?businessKey=" + businessKey));
    }
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Create a new user in LDAP.//from www.  j  a v a 2  s. c o  m
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView newUser(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (!isFormSubmission(request)) {
        ModelAndView mav = new ModelAndView("newUser");
        UserLogin ul = new UserLogin();
        mav.addObject("user", ul);
        return mav;
    }

    UserLogin ul = new UserLogin();
    ServletRequestDataBinder binder = createBinder(request, ul);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    String systemUserName = getSystemUserName(ul.getUsername());
    String suggestedUsername = null;
    // validate
    if (StringUtils.isEmpty(ul.getUsername())) {
        result.rejectValue("username", ErrorMessageKeys.MUST_BE_SPECIFIED);
    } else if (ul.getUsername().length() < minimumUsernameLength) {
        result.rejectValue("username", ErrorMessageKeys.MUST_BE_MINIMIUM_LENGTH);
    } else if (!validateUsername(ul.getUsername())) {
        result.rejectValue("username", ErrorMessageKeys.CONTAINS_INVALID_CHARS);
    } else if (ldapUtils.userNameInUse(systemUserName)) {
        // iterate until a username available
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            suggestedUsername = getSystemUserName(ul.getUsername() + i);
            if (!ldapUtils.userNameInUse(suggestedUsername)) {
                break;
            }
        }
        result.rejectValue("username", ErrorMessageKeys.USERNAME_IN_USE);
    }

    if (StringUtils.isEmpty(ul.getFirstName())) {
        result.rejectValue("firstName", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }
    if (StringUtils.isEmpty(ul.getSurname())) {
        result.rejectValue("surname", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }

    if (!StringUtils.isEmpty(ul.getEmail())) {
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(ul.getEmail());
        boolean validEmail = m.matches();
        if (!validEmail)
            result.rejectValue("email", ErrorMessageKeys.INVALID_VALUE);
    } else {
        result.rejectValue("email", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }
    if (StringUtils.isEmpty(ul.getPassword())) {
        result.rejectValue("password", ErrorMessageKeys.MUST_BE_SPECIFIED);
    } else if (!validatePassword(ul.getPassword())) {
        result.rejectValue("password", ErrorMessageKeys.MUST_BE_MINIMIUM_LENGTH);
    }

    if (result.hasErrors()) {
        ModelAndView mav = new ModelAndView("newUser");
        if (suggestedUsername != null) {
            mav.addObject("suggestedUsername", suggestedUsername);
        }
        mav.addObject(BindingResult.MODEL_KEY_PREFIX + "user", result);
        return mav;
    }

    // send verification email
    SimpleMailMessage verificationMessage = new SimpleMailMessage(userTemplateMessage);
    verificationMessage.setTo(ul.getEmail());
    String encryptedPassword = passwordUtils.encryptPassword(ul.getPassword(), true);
    verificationMessage.setSubject("Confirm e-mail address for GBIF Data Portal");
    verificationMessage.setText("Please visit the following link to confirm your e-mail address:\n\n"
            + "http://" + request.getHeader("host") + request.getContextPath() + "/user/verification" + "?fn="
            + ul.getFirstName() + "&sn=" + ul.getSurname() + "&e=" + ul.getEmail() + "&u=" + ul.getUsername()
            + "&p=" + encryptedPassword);
    try {
        mailSender.send(verificationMessage);
    } catch (MailException e) {
        // simply log it and go on...
        logger.error("Couldn't send message", e);
        ModelAndView mav = new ModelAndView("registrationVerificationFailureView");
        mav.addObject("user", ul);
        return mav;
    }

    // successful
    ModelAndView mav = new ModelAndView("registrationVerificationSuccessView");
    mav.addObject("user", ul);
    return mav;
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Saves the values for the data provider
 *///from   w w  w.  j a  v a 2  s  . c  o m
@SuppressWarnings("unchecked")
public ModelAndView synchroniseProvider(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ProviderDetail provider = new ProviderDetail();
    ServletRequestDataBinder binder = createBinder(request, provider);
    initBinder(request, binder);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    validateDataProvider(provider, result);

    if (result.hasErrors()) {
        logger.info("Errors have occurred: " + result);
        Map<String, Object> data = new HashMap<String, Object>();
        // put the errors in the request
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_PROVIDER_DETAIL, result);
        data.put(RegistrationController.REQUEST_CONTACT_TYPES, ProviderDetail.ContactTypes.values());
        data.put(RegistrationController.REQUEST_PROVIDER_DETAIL, result.getTarget());
        data.putAll(referenceDataForProvider(request));
        return new ModelAndView("registrationUpdateProviderDetail", data);
    } else {
        boolean success = synchroniseProvider(request, provider, result);
        if (!success) {
            return new ModelAndView("registrationUDDIFailure");
        }
        // return showDataResources(request, response, provider);
        return new ModelAndView(new RedirectView(request.getContextPath() + "/register/viewDataProvider?"
                + REQUEST_BUSINESS_UDDI_KEY + "=" + provider.getBusinessKey()));
    }
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * This is the entry point for the AJAX call to update the resource
 *///from w ww .ja  v  a  2 s. com
@SuppressWarnings("unchecked")
public ModelAndView updateDataResource(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    logger.info("Updating a resource...");
    debugRequestParams(request);
    ResourceDetail resource = new ResourceDetail();
    ServletRequestDataBinder binder = createBinder(request, resource);
    binder.bind(request);
    String businessKey = request.getParameter(REQUEST_BUSINESS_UDDI_KEY);
    BindingResult result = binder.getBindingResult();
    validateDataResource(resource, result);

    if (result.getErrorCount() == 0) {
        // it is always the last one, due to the fact that only one is ever submitted
        // although it's id may be something other than 0
        if (logger.isDebugEnabled()) {
            logger.debug("Resource name: " + resource.getName());
            logger.debug("Resource description: " + resource.getDescription());
        }
        uddiUtils.updateResource(resource, request.getParameter(REQUEST_BUSINESS_UDDI_KEY));
        return new ModelAndView(new RedirectView(
                request.getContextPath() + "/register/showDataResources?businessKey=" + businessKey));
    } else {
        logger.error(result.getAllErrors());
        // put the errors in the request
        Map<String, Object> data = new HashMap<String, Object>();
        data.putAll(referenceDataForResource(request, resource));
        data.put(RegistrationController.REQUEST_RESOURCE, resource);
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_RESOURCE, result);
        List<String> beanProperties = retrieveReadonlyPropertiesForResource(resource);
        data.putAll(referenceDataForResourceList(request));
        data.put("readonlyProperties", beanProperties);
        return new ModelAndView("registrationResourceDetail", data);
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.ComponentUtils.java

/**
 * /*from  www.j  a  v  a  2s .  c o m*/
 * @param
 * @return
 *
 * @param modelAndView
 * @return
 */
public static SubCommandProvider getCommand(ModelAndView modelAndView) {
    String prefix = BindingResult.MODEL_KEY_PREFIX;
    if (modelAndView == null) {
        return null;
    }
    for (String name : modelAndView.getModel().keySet()) {
        if (name.startsWith(prefix)) {
            BindingResult res = BindingResultUtils.getBindingResult(modelAndView.getModel(),
                    name.substring(prefix.length()));
            if (res != null && res.getTarget() instanceof SubCommandProvider) {
                return (SubCommandProvider) res.getTarget();
            }
        }
    }
    return null;
}