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:com.expedia.common.controller.WeatherControllerTest.java

/**
 * //from  w  ww  .  java2 s  .com
 * @param mav
 * @param name
 * @return
 */
private BindingResult getBindingResult(ModelAndView mav, String name) {
    BindingResult result = (BindingResult) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + name);
    assertTrue("No BindingResult for attribute: " + name, result != null);
    return result;
}

From source file:com.abm.mainet.water.ui.controller.PlumberLicenseFormController.java

@RequestMapping(method = RequestMethod.POST, params = "getCheckListAndCharges")
public ModelAndView doGetApplicableCheckListAndCharges(HttpServletRequest httpServletRequest) {
    this.bindModel(httpServletRequest);
    long orgId = UserSession.getCurrent().getOrganisation().getOrgid();
    ModelAndView modelAndView = null;//from   ww  w  . j  av a  2  s. c  om
    PlumberLicenseFormModel model = this.getModel();
    try {
        for (Iterator<Entry<Long, Set<File>>> it = FileUploadUtility.getCurrent().getFileMap().entrySet()
                .iterator(); it.hasNext();) {
            Entry<Long, Set<File>> entry = it.next();
            if (entry.getKey().longValue() == 0) {
                Set<File> set = entry.getValue();
                File file = set.iterator().next();
                String bytestring = "";
                Base64 base64 = new Base64();
                try {
                    bytestring = base64.encodeToString(FileUtils.readFileToByteArray(file));
                } catch (IOException e) {
                    logger.error("Exception has been occurred in file byte to string conversions", e);
                }
                String plumberImage = file.getName();
                model.setPlumberImage(plumberImage);
                model.getPlumberLicenseReqDTO().setPlumberImage(plumberImage);
                model.getPlumberLicenseReqDTO().setImageByteCode(bytestring);
                break;
            }
        }
        if (model.getPlumberImage() == null || model.getPlumberImage().isEmpty()) {
            this.getModel().addValidationError(ApplicationSession.getInstance()
                    .getMessage("water.plumberLicense.valMsg.uploadPlumberPhoto"));
        } else {
            model.findApplicableCheckListAndCharges(this.getModel().getServiceId(), orgId);
        }
        modelAndView = new ModelAndView("PlumberLicenseFormValidn", "command", model);
        if (model.getBindingResult() != null) {
            modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME,
                    getModel().getBindingResult());
        }
    } catch (Exception ex) {
        modelAndView = defaultExceptionFormView();
    }
    return modelAndView;
}

From source file:org.gvnix.web.json.DataBinderMappingJackson2HttpMessageConverter.java

/**
 * Before call to {@link ObjectMapper#readValue(java.io.InputStream, Class)}
 * creates a {@link ServletRequestDataBinder} and put it to current Thread
 * in order to be used by the {@link DataBinderDeserializer}.
 * <p/>//from   ww w  . ja  v  a2s .c  o  m
 * Ref: <a href=
 * "http://java.dzone.com/articles/java-thread-local-%E2%80%93-how-use">When
 * to use Thread Local?</a>
 * 
 * @param javaType
 * @param inputMessage
 * @return
 */
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
    try {
        Object target = null;
        String objectName = null;

        // CRear el DataBinder con un target object en funcion del javaType,
        // ponerlo en el thread local
        Class<?> clazz = javaType.getRawClass();
        if (Collection.class.isAssignableFrom(clazz)) {
            Class<?> contentClazz = javaType.getContentType().getRawClass();
            target = new DataBinderList<Object>(contentClazz);
            objectName = "list";
        } else if (Map.class.isAssignableFrom(clazz)) {
            // TODO Class<?> contentClazz =
            // javaType.getContentType().getRawClass();
            target = CollectionFactory.createMap(clazz, 0);
            objectName = "map";
        } else {
            target = BeanUtils.instantiateClass(clazz);
            objectName = "bean";
        }

        WebDataBinder binder = new ServletRequestDataBinder(target, objectName);
        binder.setConversionService(this.conversionService);
        binder.setAutoGrowNestedPaths(true);
        binder.setValidator(validator);

        ThreadLocalUtil.setThreadVariable(BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder"), binder);

        Object value = getObjectMapper().readValue(inputMessage.getBody(), javaType);

        return value;
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: ".concat(ex.getMessage()), ex);
    }
}

From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java

@Test
public void whenGETBindError_returnBadRequest() throws Exception {
    when(singleJPAEntityService.findOne(TestEntity.class, 1l)).thenReturn(baseEntity);

    MvcResult result = mvc.perform(get("/entity/a")).andExpect(status().isBadRequest())
            .andExpect(view().name("errors/badrequest")).andReturn();

    BindingResult bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(),
            BindingResult.MODEL_KEY_PREFIX + "testEntityController", BindingResult.class);

    //Validation errors should be bound to result as FieldError
    assertEquals(false, bindingResult.hasGlobalErrors());
    assertEquals(true, bindingResult.hasFieldErrors());
    assertEquals(1, bindingResult.getFieldErrorCount());
}

From source file:org.hdiv.web.servlet.tags.form.AbstractHtmlElementTagTests.java

protected void exposeBindingResult(Errors errors) {
    // wrap errors in a Model
    Map model = new HashMap();
    model.put(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors);

    // replace the request context with one containing the errors
    MockPageContext pageContext = getPageContext();
    RequestContext context = new RequestContext((HttpServletRequest) pageContext.getRequest(), model);
    pageContext.setAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE, context);
}

From source file:com.abm.mainet.water.ui.controller.PlumberLicenseFormController.java

@RequestMapping(params = "save", method = RequestMethod.POST)
public ModelAndView savePlumberLicenseForm(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) {
    this.getModel().bind(httpServletRequest);
    PlumberLicenseFormModel model = this.getModel();
    ModelAndView modelAndView = null;//  w ww.j  a  v a2  s .  c  o m
    if (model.saveForm()) {
        CommonChallanDTO offline = model.getOfflineDTO();
        if (offline.getOnlineOfflineCheck() != null
                && offline.getOnlineOfflineCheck().equals(MainetConstants.NewWaterServiceConstants.NO)) {
            return jsonResult(
                    JsonViewObject.successResult(getApplicationSession().getMessage("continue.forchallan")));
        } else {
            return jsonResult(
                    JsonViewObject.successResult(getApplicationSession().getMessage("continue.forpayment")));
        }
    }
    modelAndView = new ModelAndView("PlumberLicenseFormValidn", MainetConstants.FORM_NAME, getModel());
    modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME,
            getModel().getBindingResult());
    return modelAndView;
}

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

protected ModelAndView submitAddBuildNumber(HttpServletRequest request) throws IOException {
    SharedBuildNumber form = new SharedBuildNumber(0);
    BindingResult result = new BeanPropertyBindingResult(form, SharedBuildNumberController.FORM);
    this.bindAndValidateForm(request, result);

    if (result.hasErrors()) {
        ModelAndView modelAndView = new ModelAndView(this.addJspPagePath);

        modelAndView.getModel().put(BindingResult.MODEL_KEY_PREFIX + SharedBuildNumberController.FORM, result);
        modelAndView.getModel().put(SharedBuildNumberController.FORM, form);

        return modelAndView;
    }//from w  w w  .j  a v a2 s. c  o m

    SharedBuildNumber buildNumber = new SharedBuildNumber(this.configurationService.getNextBuildNumberId());
    this.copyFormToBuildNumber(form, buildNumber);
    this.configurationService.saveSharedBuildNumber(buildNumber);

    return this.returnRedirectView("/admin/admin.html?item=sharedBuildNumbers");
}

From source file:org.hdiv.web.servlet.tags.form.CheckboxTagTests.java

public void testWithSingleValueAndEditor() throws Exception {
    this.bean.setName("Rob Harrop");
    this.tag.setPath("name");
    this.tag.setValue("   Rob Harrop");
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class,
            new StringTrimmerEditor(false));
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getWriter().toString();

    // wrap the output so it is valid XML
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element checkboxElement = (Element) document.getRootElement().elements().get(0);
    assertEquals("input", checkboxElement.getName());
    assertEquals("checkbox", checkboxElement.attribute("type").getValue());
    assertEquals("name", checkboxElement.attribute("name").getValue());
    assertEquals("checked", checkboxElement.attribute("checked").getValue());
    assertEquals("   Rob Harrop", checkboxElement.attribute("value").getValue());
}

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

protected ModelAndView submitEditBuildNumber(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    Integer id = this.getId(request);
    if (id != null) {
        SharedBuildNumber buildNumber = this.configurationService.getSharedBuildNumber(id);
        if (buildNumber != null) {
            SharedBuildNumber form = new SharedBuildNumber(id);
            BindingResult result = new BeanPropertyBindingResult(form, SharedBuildNumberController.FORM);
            this.bindAndValidateForm(request, result);

            if (result.hasErrors()) {
                ModelAndView modelAndView = new ModelAndView(this.editJspPagePath);

                modelAndView.getModel().put(BindingResult.MODEL_KEY_PREFIX + SharedBuildNumberController.FORM,
                        result);/*w ww .  j  a  v a2 s . c  om*/
                modelAndView.getModel().put(SharedBuildNumberController.PREFIX,
                        BuildNumberPropertiesProvider.PARAMETER_PREFIX);
                modelAndView.getModel().put(SharedBuildNumberController.FORM, form);

                return modelAndView;
            }

            this.copyFormToBuildNumber(form, buildNumber);
            this.configurationService.saveSharedBuildNumber(buildNumber);

            return this.returnRedirectView("/admin/admin.html?item=sharedBuildNumbers");
        }
    }

    SharedBuildNumberController.logger.info("Edit requested for non-existent shared build number.");
    WebUtil.notFound(request, response, "The shared build number you are trying to edit does not exist.",
            SharedBuildNumberController.logger);
    return null;
}

From source file:org.hdiv.web.servlet.tags.form.CheckboxTagTests.java

public void testWithMultiValueWithEditor() throws Exception {
    this.tag.setPath("stringArray");
    this.tag.setValue("   foo");
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class,
            new StringTrimmerEditor(false));
    getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getWriter().toString();

    // wrap the output so it is valid XML
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element checkboxElement = (Element) document.getRootElement().elements().get(0);
    assertEquals("input", checkboxElement.getName());
    assertEquals("checkbox", checkboxElement.attribute("type").getValue());
    assertEquals("stringArray", checkboxElement.attribute("name").getValue());
    assertEquals("checked", checkboxElement.attribute("checked").getValue());
    assertEquals("   foo", checkboxElement.attribute("value").getValue());
}