List of usage examples for org.springframework.validation MapBindingResult MapBindingResult
public MapBindingResult(Map<?, ?> target, String objectName)
From source file:org.openmrs.web.dwr.DWRRelationshipService.java
public String[] createRelationship(Integer personAId, Integer personBId, Integer relationshipTypeId, String startDateStr) throws Exception { PersonService ps = Context.getPersonService(); Person personA = ps.getPerson(personAId); Person personB = ps.getPerson(personBId); RelationshipType relType = Context.getPersonService().getRelationshipType(relationshipTypeId); Relationship rel = new Relationship(); rel.setPersonA(personA);/*from w w w .j a v a 2 s . co m*/ rel.setPersonB(personB); rel.setRelationshipType(relType); if (StringUtils.isNotBlank(startDateStr)) { rel.setStartDate(Context.getDateFormat().parse(startDateStr)); } Map<String, String> map = new HashMap<String, String>(); MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName()); new RelationshipValidator().validate(rel, errors); String errmsgs[]; if (!errors.hasErrors()) { ps.saveRelationship(rel); errmsgs = null; return errmsgs; } errmsgs = errors.getGlobalError().getCodes(); return errmsgs; }
From source file:org.openmrs.web.dwr.DWRRelationshipService.java
public boolean changeRelationshipDates(Integer relationshipId, String startDateStr, String endDateStr) throws Exception { Relationship r = Context.getPersonService().getRelationship(relationshipId); Date startDate = null;//from w w w . java 2 s . c om if (StringUtils.isNotBlank(startDateStr)) { startDate = Context.getDateFormat().parse(startDateStr); } Date endDate = null; if (StringUtils.isNotBlank(endDateStr)) { endDate = Context.getDateFormat().parse(endDateStr); } r.setStartDate(startDate); r.setEndDate(endDate); Map<String, String> map = new HashMap<String, String>(); MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName()); new RelationshipValidator().validate(r, errors); if (errors.hasErrors()) { return false; } else { Context.getPersonService().saveRelationship(r); return true; } }
From source file:org.hdiv.web.validator.EditableParameterValidatorTest.java
@SuppressWarnings("unchecked") public void testEditableValidator() { MockHttpServletRequest request = (MockHttpServletRequest) HDIVUtil.getHttpServletRequest(); this.dataComposer.beginRequest(this.targetName); this.dataComposer.compose("paramName", "", true, "text"); String pageState = this.dataComposer.endRequest(); this.dataComposer.endPage(); request.addParameter(hdivParameter, pageState); request.addParameter("paramName", "<script>storeCookie()</script>"); RequestWrapper requestWrapper = new RequestWrapper(request); boolean result = helper.validate(requestWrapper).isValid(); assertTrue(result);/*ww w. j ava2s . c o m*/ // Editable errors in request? Hashtable<String, String[]> parameters = (Hashtable<String, String[]>) requestWrapper .getAttribute(Constants.EDITABLE_PARAMETER_ERROR); assertEquals(1, parameters.size()); // Set request attributes on threadlocal RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(requestWrapper)); // New Editable instance EditableParameterValidator validator = new EditableParameterValidator(); Errors errors = new MapBindingResult(new HashMap<String, String>(), ""); assertFalse(errors.hasErrors()); // move errors to Errors instance validator.validate("anyObject", errors); assertTrue(errors.hasErrors()); }
From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java
/** * {@inheritDoc}/*from w ww .ja va 2 s . com*/ * <p> * Downcast {@link org.springframework.web.bind.WebDataBinder} to * {@link org.springframework.web.bind.ServletRequestDataBinder} before binding. * * @throws Exception * @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory */ protected void bindRequestParameters(ModelAndViewContainer mavContainer, WebDataBinderFactory binderFactory, WebDataBinder binder, NativeWebRequest request, MethodParameter parameter) throws Exception { // Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>(); // // Class<?> targetType = binder.getTarget().getClass(); // WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null); Collection target = (Collection) binder.getTarget(); Class<?>[] paramTypes = parameter.getMethod().getParameterTypes(); Method method = parameter.getMethod(); Object[] args = new Object[paramTypes.length]; Map<String, Object> argMap = new HashMap<String, Object>(args.length); MapBindingResult errors = new MapBindingResult(argMap, ""); ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; MethodParameter methodParam = new MethodParameter(method, i); methodParam.initParameterNameDiscovery(parameterNameDiscoverer); String paramName = methodParam.getParameterName(); // ?? if (BeanUtils.isSimpleProperty(paramType)) { SimpleTypeConverter converter = new SimpleTypeConverter(); Object value; // ? if (paramType.isArray()) { value = request.getParameterValues(paramName); } else { value = request.getParameter(paramName); } try { args[i] = converter.convertIfNecessary(value, paramType, methodParam); } catch (TypeMismatchException e) { errors.addError(new FieldError(paramName, paramName, e.getMessage())); } } else { // ???POJO if (paramType.isArray()) { ObjectArrayDataBinder binders = new ObjectArrayDataBinder(paramType.getComponentType(), paramName); target.addAll(ArrayUtils.arrayConvert(binders.bind(request))); } } } // if (Collection.class.isAssignableFrom(targetType)) {// bind collection or array // // Type type = parameter.getGenericParameterType(); // Class<?> componentType = Object.class; // // Collection target = (Collection) binder.getTarget(); // // List targetList = new ArrayList(target); // // if (type instanceof ParameterizedType) { // componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]; // } // // if (parameter.getParameterType().isArray()) { // componentType = parameter.getParameterType().getComponentType(); // } // // for (Object key : servletRequest.getParameterMap().keySet()) { // String prefixName = getPrefixName((String) key); // // // ?prefix ?? // if (hasProcessedPrefixMap.containsKey(prefixName)) { // continue; // } else { // hasProcessedPrefixMap.put(prefixName, Boolean.TRUE); // } // // if (isSimpleComponent(prefixName)) { // bind simple type // Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName); // Matcher matcher = INDEX_PATTERN.matcher(prefixName); // if (!matcher.matches()) { // ? array=1&array=2 // for (Object value : paramValues.values()) { // targetList.add(simpleBinder.convertIfNecessary(value, componentType)); // } // } else { // ? array[0]=1&array[1]=2 // int index = Integer.valueOf(matcher.group(1)); // // if (targetList.size() <= index) { // growCollectionIfNecessary(targetList, index); // } // targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType)); // } // } else { // ? votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1 // Object component = null; // // ? ????? // Matcher matcher = INDEX_PATTERN.matcher(prefixName); // if (!matcher.matches()) { // throw new IllegalArgumentException("bind collection error, need integer index, key:" + key); // } // int index = Integer.valueOf(matcher.group(1)); // if (targetList.size() <= index) { // growCollectionIfNecessary(targetList, index); // } // Iterator iterator = targetList.iterator(); // for (int i = 0; i < index; i++) { // iterator.next(); // } // component = iterator.next(); // // if (component == null) { // component = BeanUtils.instantiate(componentType); // } // // WebDataBinder componentBinder = binderFactory.createBinder(request, component, null); // component = componentBinder.getTarget(); // // if (component != null) { // ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues( // servletRequest, // prefixName, // ""); // componentBinder.bind(pvs); // validateIfApplicable(componentBinder, parameter); // if (componentBinder.getBindingResult().hasErrors()) { // if (isBindExceptionRequired(componentBinder, parameter)) { // throw new BindException(componentBinder.getBindingResult()); // } // } // targetList.set(index, component); // } // } // target.clear(); // target.addAll(targetList); // } // } else if (MapWapper.class.isAssignableFrom(targetType)) { // // Type type = parameter.getGenericParameterType(); // Class<?> keyType = Object.class; // Class<?> valueType = Object.class; // // if (type instanceof ParameterizedType) { // keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]; // valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1]; // } // // MapWapper mapWapper = ((MapWapper) binder.getTarget()); // Map target = mapWapper.getInnerMap(); // if (target == null) { // target = new HashMap(); // mapWapper.setInnerMap(target); // } // // for (Object key : servletRequest.getParameterMap().keySet()) { // String prefixName = getPrefixName((String) key); // // // ?prefix ?? // if (hasProcessedPrefixMap.containsKey(prefixName)) { // continue; // } else { // hasProcessedPrefixMap.put(prefixName, Boolean.TRUE); // } // // Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType); // // if (isSimpleComponent(prefixName)) { // bind simple type // Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName); // // for (Object value : paramValues.values()) { // target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType)); // } // } else { // // Object component = target.get(keyValue); // if (component == null) { // component = BeanUtils.instantiate(valueType); // } // // WebDataBinder componentBinder = binderFactory.createBinder(request, component, null); // component = componentBinder.getTarget(); // // if (component != null) { // ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues( // servletRequest, // prefixName, // ""); // componentBinder.bind(pvs); // // validateComponent(componentBinder, parameter); // // target.put(keyValue, component); // } // } // } // } else {// bind model // ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder; // servletBinder.bind(servletRequest); // } }
From source file:com.ms.commons.summer.web.handler.DataBinderUtil.java
/** * ?// w w w . java 2 s. c o m * * @param method * @param model * @param request * @param response * @param c * @return */ @SuppressWarnings("unchecked") public static Object[] getArgs(Method method, Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, Class<?> c) { Class<?>[] paramTypes = method.getParameterTypes(); Object[] args = new Object[paramTypes.length]; Map<String, Object> argMap = new HashMap<String, Object>(args.length); Map<String, String> pathValues = null; PathPattern pathPattern = method.getAnnotation(PathPattern.class); if (pathPattern != null) { String path = request.getRequestURI(); int index = path.lastIndexOf('.'); if (index != -1) { path = path.substring(0, index); String[] patterns = pathPattern.patterns(); pathValues = getPathValues(patterns, path); } } MapBindingResult errors = new MapBindingResult(argMap, ""); ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; MethodParameter methodParam = new MethodParameter(method, i); methodParam.initParameterNameDiscovery(parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(methodParam, c.getClass()); String paramName = methodParam.getParameterName(); // map if (Map.class.isAssignableFrom(paramType)) { args[i] = model; } // HttpServletRequest else if (HttpServletRequest.class.isAssignableFrom(paramType)) { args[i] = request; } // HttpServletResponse else if (HttpServletResponse.class.isAssignableFrom(paramType)) { args[i] = response; } // HttpSession else if (HttpSession.class.isAssignableFrom(paramType)) { args[i] = request.getSession(); } // Errors else if (Errors.class.isAssignableFrom(paramType)) { args[i] = errors; } // MultipartFile else if (MultipartFile.class.isAssignableFrom(paramType)) { MultipartFile[] files = resolveMultipartFiles(request, errors, paramName); if (files != null && files.length > 0) { args[i] = files[0]; } } // MultipartFile[] else if (MultipartFile[].class.isAssignableFrom(paramType)) { args[i] = resolveMultipartFiles(request, errors, paramName); } else { // ?? if (BeanUtils.isSimpleProperty(paramType)) { SimpleTypeConverter converter = new SimpleTypeConverter(); Object value; // ? if (paramType.isArray()) { value = request.getParameterValues(paramName); } else { Object[] parameterAnnotations = methodParam.getParameterAnnotations(); value = null; if (parameterAnnotations != null && parameterAnnotations.length > 0) { if (pathValues != null && pathValues.size() > 0) { for (Object object : parameterAnnotations) { if (PathVariable.class.isInstance(object)) { PathVariable pv = (PathVariable) object; if (StringUtils.isEmpty(pv.value())) { value = pathValues.get(paramName); } else { value = pathValues.get(pv.value()); } break; } } } } else { value = request.getParameter(paramName); } } try { args[i] = converter.convertIfNecessary(value, paramType, methodParam); model.put(paramName, args[i]); } catch (TypeMismatchException e) { errors.addError(new FieldError(paramName, paramName, e.getMessage())); } } else { // ???POJO if (paramType.isArray()) { ObjectArrayDataBinder binder = new ObjectArrayDataBinder(paramType.getComponentType(), paramName); args[i] = binder.bind(request); model.put(paramName, args[i]); } else { Object bindObject = BeanUtils.instantiateClass(paramType); SummerServletRequestDataBinder binder = new SummerServletRequestDataBinder(bindObject, paramName); binder.bind(request); BindException be = new BindException(binder.getBindingResult()); List<FieldError> fieldErrors = be.getFieldErrors(); for (FieldError fieldError : fieldErrors) { errors.addError(fieldError); } args[i] = binder.getTarget(); model.put(paramName, args[i]); } } } } return args; }
From source file:org.codehaus.groovy.grails.web.mapping.RegexUrlMapping.java
@SuppressWarnings("unchecked") private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m, int tokenCount) { boolean hasOptionalExtension = urlData.hasOptionalExtension(); Map params = new HashMap(); Errors errors = new MapBindingResult(params, "urlMapping"); String lastGroup = null;/*from w ww. ja v a 2 s . co m*/ for (int i = 0, count = m.groupCount(); i < count; i++) { lastGroup = m.group(i + 1); // if null optional.. ignore if (i == tokenCount & hasOptionalExtension) { ConstrainedProperty cp = constraints[constraints.length - 1]; cp.validate(this, lastGroup, errors); if (errors.hasErrors()) { return null; } params.put(cp.getPropertyName(), lastGroup); break; } else { if (lastGroup == null) continue; int j = lastGroup.indexOf('?'); if (j > -1) { lastGroup = lastGroup.substring(0, j); } if (constraints.length > i) { ConstrainedProperty cp = constraints[i]; cp.validate(this, lastGroup, errors); if (errors.hasErrors()) { return null; } params.put(cp.getPropertyName(), lastGroup); } } } for (Object key : parameterValues.keySet()) { params.put(key, parameterValues.get(key)); } if (controllerName == null) { controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, constraints); } if (actionName == null) { actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, constraints); } if (namespace == null) { namespace = createRuntimeConstraintEvaluator(NAMESPACE, constraints); } if (viewName == null) { viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, constraints); } if (redirectInfo == null) { redirectInfo = createRuntimeConstraintEvaluator("redirect", constraints); } DefaultUrlMappingInfo info; if (forwardURI != null && controllerName == null) { info = new DefaultUrlMappingInfo(forwardURI, getHttpMethod(), urlData, servletContext); } else if (viewName != null && controllerName == null) { info = new DefaultUrlMappingInfo(viewName, params, urlData, servletContext); } else { info = new DefaultUrlMappingInfo(redirectInfo, controllerName, actionName, namespace, pluginName, getViewName(), getHttpMethod(), getVersion(), params, urlData, servletContext); } if (parseRequest) { info.setParsingRequest(parseRequest); } return info; }
From source file:org.grails.web.mapping.RegexUrlMapping.java
@SuppressWarnings("unchecked") private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m) { boolean hasOptionalExtension = urlData.hasOptionalExtension(); Map params = new HashMap(); Errors errors = new MapBindingResult(params, "urlMapping"); int groupCount = m.groupCount(); String lastGroup = null;//from w ww . j a v a2 s . co m for (int i = 0; i < groupCount; i++) { lastGroup = m.group(i + 1); // if null optional.. ignore if (i == groupCount - 1 && hasOptionalExtension) { ConstrainedProperty cp = constraints[constraints.length - 1]; cp.validate(this, lastGroup, errors); if (errors.hasErrors()) { return null; } params.put(cp.getPropertyName(), lastGroup); break; } else { if (lastGroup == null) continue; int j = lastGroup.indexOf('?'); if (j > -1) { lastGroup = lastGroup.substring(0, j); } if (constraints.length > i) { ConstrainedProperty cp = constraints[i]; cp.validate(this, lastGroup, errors); if (errors.hasErrors()) { return null; } params.put(cp.getPropertyName(), lastGroup); } } } for (Object key : parameterValues.keySet()) { params.put(key, parameterValues.get(key)); } if (controllerName == null) { controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, constraints); } if (actionName == null) { actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, constraints); } if (namespace == null) { namespace = createRuntimeConstraintEvaluator(NAMESPACE, constraints); } if (viewName == null) { viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, constraints); } if (redirectInfo == null) { redirectInfo = createRuntimeConstraintEvaluator("redirect", constraints); } DefaultUrlMappingInfo info; if (forwardURI != null && controllerName == null) { info = new DefaultUrlMappingInfo(forwardURI, getHttpMethod(), urlData, grailsApplication); } else if (viewName != null && controllerName == null) { info = new DefaultUrlMappingInfo(viewName, params, urlData, grailsApplication); } else { info = new DefaultUrlMappingInfo(redirectInfo, controllerName, actionName, namespace, pluginName, getViewName(), getHttpMethod(), getVersion(), params, urlData, grailsApplication); } if (parseRequest) { info.setParsingRequest(parseRequest); } return info; }
From source file:org.orcid.frontend.web.controllers.ManageProfileController.java
@RequestMapping(value = "/addEmail.json", method = RequestMethod.POST) public @ResponseBody org.orcid.pojo.Email addEmailsJson(HttpServletRequest request, @RequestBody org.orcid.pojo.AddEmail email) { List<String> errors = new ArrayList<String>(); // Check password if (email.getPassword() == null || !encryptionManager.hashMatches(email.getPassword(), getEffectiveProfile().getPassword())) { errors.add(getMessage("check_password_modal.incorrect_password")); }/*from w w w.j a v a 2 s .c om*/ if (errors.isEmpty()) { String newPrime = null; String oldPrime = null; List<String> emailErrors = new ArrayList<String>(); // clear errros email.setErrors(new ArrayList<String>()); // if blank if (email.getValue() == null || email.getValue().trim().equals("")) { emailErrors.add(getMessage("Email.personalInfoForm.email")); } OrcidProfile currentProfile = getEffectiveProfile(); List<Email> emails = currentProfile.getOrcidBio().getContactDetails().getEmail(); MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email"); // make sure there are no dups validateEmailAddress(email.getValue(), false, false, request, mbr); for (ObjectError oe : mbr.getAllErrors()) { emailErrors.add(getMessage(oe.getCode(), email.getValue())); } email.setErrors(emailErrors); if (emailErrors.size() == 0) { if (email.isPrimary()) { for (Email curEmail : emails) { if (curEmail.isPrimary()) oldPrime = curEmail.getValue(); curEmail.setPrimary(false); } newPrime = email.getValue(); } emails.add(email); currentProfile.getOrcidBio().getContactDetails().setEmail(emails); email.setSource(sourceManager.retrieveSourceOrcid()); emailManager.addEmail(currentProfile.getOrcidIdentifier().getPath(), email); // send verifcation email for new address notificationManager.sendVerificationEmail(currentProfile, email.getValue()); // if primary also send change notification. if (newPrime != null && !newPrime.equalsIgnoreCase(oldPrime)) { request.getSession().setAttribute(ManageProfileController.CHECK_EMAIL_VALIDATED, false); notificationManager.sendEmailAddressChangedNotification(currentProfile, new Email(oldPrime)); } } } else { email.setErrors(errors); } return email; }
From source file:org.orcid.frontend.web.controllers.ManageProfileController.java
@SuppressWarnings("unchecked") @RequestMapping(value = "/emails.json", method = RequestMethod.POST) public @ResponseBody org.orcid.pojo.ajaxForm.Emails postEmailsJson(HttpServletRequest request, @RequestBody org.orcid.pojo.ajaxForm.Emails emails) { org.orcid.pojo.Email newPrime = null; org.orcid.pojo.Email oldPrime = null; List<String> allErrors = new ArrayList<String>(); for (org.orcid.pojo.Email email : emails.getEmails()) { MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email"); validateEmailAddress(email.getValue(), request, mbr); List<String> emailErrors = new ArrayList<String>(); for (ObjectError oe : mbr.getAllErrors()) { String msg = getMessage(oe.getCode(), email.getValue()); emailErrors.add(getMessage(oe.getCode(), email.getValue())); allErrors.add(msg);// w w w . j av a2 s .c om } email.setErrors(emailErrors); if (email.isPrimary()) newPrime = email; } if (newPrime == null) { allErrors.add("A Primary Email Must be selected"); } OrcidProfile currentProfile = getEffectiveProfile(); if (currentProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail() != null) oldPrime = new org.orcid.pojo.Email( currentProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail()); emails.setErrors(allErrors); if (allErrors.size() == 0) { currentProfile.getOrcidBio().getContactDetails().setEmail((List<Email>) (Object) emails.getEmails()); emailManager.updateEmails(currentProfile.getOrcidIdentifier().getPath(), currentProfile.getOrcidBio().getContactDetails().getEmail()); if (newPrime != null && !newPrime.getValue().equalsIgnoreCase(oldPrime.getValue())) { notificationManager.sendEmailAddressChangedNotification(currentProfile, new Email(oldPrime.getValue())); if (!newPrime.isVerified()) { notificationManager.sendVerificationEmail(currentProfile, newPrime.getValue()); request.getSession().setAttribute(ManageProfileController.CHECK_EMAIL_VALIDATED, false); } } } return emails; }
From source file:org.orcid.frontend.web.controllers.RegistrationController.java
public Registration regEmailValidate(HttpServletRequest request, Registration reg, boolean isOauthRequest, boolean isKeyup) { reg.getEmail().setErrors(new ArrayList<String>()); if (!isKeyup && (reg.getEmail().getValue() == null || reg.getEmail().getValue().trim().isEmpty())) { setError(reg.getEmail(), "Email.registrationForm.email"); }/*from w ww . j a v a 2s . c om*/ // validate email MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email"); // make sure there are no dups validateEmailAddress(reg.getEmail().getValue(), false, true, request, mbr); for (ObjectError oe : mbr.getAllErrors()) { if (isOauthRequest && oe.getCode().equals("orcid.frontend.verify.duplicate_email")) { // XXX reg.getEmail().getErrors().add(getMessage("oauth.registration.duplicate_email", oe.getArguments())); } else { reg.getEmail().getErrors().add(getMessage(oe.getCode(), oe.getArguments())); } } // validate confirm if already field out if (reg.getEmailConfirm().getValue() != null) { regEmailConfirmValidate(reg); } return reg; }