Java Code Examples for org.springframework.validation.Errors#hasErrors()

The following examples show how to use org.springframework.validation.Errors#hasErrors() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HarvestNowValidator.java    From webcurator with Apache License 2.0 7 votes vote down vote up
public void validate(Object aCommand, Errors aErrors) {
    TargetInstanceCommand cmd = (TargetInstanceCommand) aCommand;
    if (log.isDebugEnabled()) {
        log.debug("Validating harvest now target instance command.");
    }
    
    ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, TargetInstanceCommand.PARAM_CMD, "required", getObjectArrayForLabel(TargetInstanceCommand.PARAM_CMD), "Action command is a required field.");
    
    if (TargetInstanceCommand.ACTION_HARVEST.equals(cmd.getCmd())) {                        
        ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, TargetInstanceCommand.PARAM_AGENT, "required", getObjectArrayForLabel(TargetInstanceCommand.PARAM_AGENT), "Harvest agent is a required field.");
        ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, TargetInstanceCommand.PARAM_OID, "required", getObjectArrayForLabel(TargetInstanceCommand.PARAM_OID), "Target Instance Id is a required field.");
        if (!aErrors.hasErrors()) {                
            ValidatorUtil.validateMinimumBandwidthAvailable(aErrors, cmd.getTargetInstanceId(), "no.minimum.bandwidth", getObjectArrayForLabel(TargetInstanceCommand.PARAM_OID), "Adding this target instance will reduce the bandwidth.");
            if (cmd.getBandwidthPercent() != null) {                	
            	ValidatorUtil.validateMaxBandwidthPercentage(aErrors, cmd.getBandwidthPercent().intValue(), "max.bandwidth.exeeded");
            }                                            
        }
        
        if (!aErrors.hasErrors()) {
        	ValidatorUtil.validateTargetApproved(aErrors, cmd.getTargetInstanceId(), "target.not.approved");
        }
    }
}
 
Example 2
Source File: SiteURLsValidator.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void validate(Object aCmd, Errors aErrors) {
	UrlCommand cmd = (UrlCommand) aCmd;
	
	if (UrlCommand.ACTION_ADD_URL.equals(cmd.getActionCmd())) {		
		ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "url", "required", new Object[] {"URL"}, "URL is a required field.");
		
		if (!aErrors.hasErrors()) {
			ValidatorUtil.validateURL(aErrors, cmd.getUrl(), "invalid.url", new Object[] { cmd.getUrl()}, "The URL provided is not valid");
		}			
		
		if (!aErrors.hasErrors()) {
			String url = cmd.getUrl();
			
			if (!strategy.isValidPattern(url)) {				
				aErrors.reject("invalid.url", new Object[] {cmd.getUrl()}, "The url provided is not valid.");
			}
		}
	}
}
 
Example 3
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@PostMapping
public String processOrder(@Valid Order order, Errors errors, 
    SessionStatus sessionStatus, 
    @AuthenticationPrincipal User user) {
  
  if (errors.hasErrors()) {
    return "orderForm";
  }

  UserUDT userUDT = new UserUDT(user.getUsername(), user.getFullname(), user.getPhoneNumber());
  order.setUser(userUDT);
  
  orderRepo.save(order);
  sessionStatus.setComplete();
  
  return "redirect:/";
}
 
Example 4
Source File: OrderController.java    From spring-in-action-5-samples with Apache License 2.0 6 votes vote down vote up
@PostMapping
public String processOrder(@Valid Order order, Errors errors, 
    SessionStatus sessionStatus, 
    @AuthenticationPrincipal User user) {
  
  if (errors.hasErrors()) {
    return "orderForm";
  }
  
  order.setUser(user);
  
  orderRepo.save(order);
  sessionStatus.setComplete();
  
  return "redirect:/";
}
 
Example 5
Source File: SignupController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
@RequestMapping(params = "action=signup")
public void action(ActionRequest request, ActionResponse response,
		LoginForm loginForm, Errors errors, SessionStatus sessionStatus) {
	ValidationUtils.rejectIfEmpty(errors, "firstName", "firstName.empty",
			"Please, fill in your first name");
	ValidationUtils.rejectIfEmpty(errors, "lastName", "lastName.empty",
			"Please, fill in your last name");
	if (!errors.hasErrors()) {
		response.setRenderParameter("action", "login");
	}
}
 
Example 6
Source File: UserController.java    From todolist with MIT License 5 votes vote down vote up
@RequestMapping(value="/{id:[0-9]+}")
public String update(@PathVariable("id") Long id, @Valid @ModelAttribute("form") UserForm form, Errors errors) {
    if(!Strings.isNullOrEmpty(form.getPassword())) {
        if(form.getPassword().length() < 6) {
            errors.rejectValue("password", "Size", "密码不少于6个字符");
            return "admin/user/edit";
        }
    }

    if (errors.hasErrors()) {
        return "admin/user/edit";
    }

    User user = null;
    try {
        user = userService.findOne(id);

        if(!user.getEmail().equals(form.getEmail())) {
            if (userService.existsByEmail(form.getEmail())) {
                errors.rejectValue("email", "Duplication", "邮箱地址已被使用");
                return "admin/user/edit";
            }
        }

        form.push(user, passwordEncoder);
        userService.save(user);
    } catch (DataAccessException ex) {
        return "admin/user/edit";
    }

    return "redirect:/admin/users?q=" + user.getName();
}
 
Example 7
Source File: SchemaController.java    From nakadi with MIT License 5 votes vote down vote up
@RequestMapping(value = "/event-types/{name}/schemas", method = RequestMethod.POST)
public ResponseEntity<?> create(@PathVariable("name") final String name,
                                @Valid @RequestBody final EventTypeSchemaBase schema,
                                final Errors errors) {
    if (errors.hasErrors()) {
        throw new ValidationException(errors);
    }

    schemaService.addSchema(name, schema);

    return status(HttpStatus.OK).build();
}
 
Example 8
Source File: UserController.java    From todolist with MIT License 5 votes vote down vote up
@RequestMapping(value="/register", method=RequestMethod.POST)
public String registerSubmit(Principal principal, @Valid @ModelAttribute("form") UserForm form, Errors errors, Model model, RedirectAttributes redirectAttributes) {
    if (errors.hasErrors()) {
        return "user/register";
    }

    User user = new User(form.getEmail(), form.getName(), passwordEncoder.encode(form.getPassword()));
    userService.save(user);
    redirectAttributes.addFlashAttribute("user", user);
    return "redirect:/register/result";
}
 
Example 9
Source File: TargetSeedsValidator.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * Validates that the URL Search Criteria is valid.
 * @param command The command object.
 * @param errors  The errors object to populate.
 * @return        true if valid; otherwise false.
 */
public boolean validateLinkSearch(SeedsCommand command, Errors errors) {
	if( SeedsCommand.SEARCH_URL.equals(command.getSearchType())) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "urlSearchCriteria", "required", getObjectArrayForLabel("urlSearchCriteria"), "urlSearchCriteria is a required field");
           if (command.getUrlSearchCriteria() != null && command.getUrlSearchCriteria().length() > 0) {
               ValidatorUtil.validateURL(errors, command.getUrlSearchCriteria(), "target.errors.badUrl", getObjectArrayForLabel("urlSearchCriteria"),"Invalid URL");
           }			
	}
	return !errors.hasErrors();
}
 
Example 10
Source File: TemplateValidatorHelper.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the template for all the varible names and check that they are valid.
 * @param aErrors the errors object to populate
 */
public void parseForErrors(Errors aErrors) {
    String target = template;
    Matcher m = varPattern.matcher(target);
    while(m.find()) { 
        //find all the defined template attributes for replacement
        String varName = m.group(1);
        isAttributeValid(varName,aErrors);
        if (aErrors.hasErrors()) {
            aErrors.reject("template.defined.attributes");
        }
    }   
}
 
Example 11
Source File: AbstractValidator.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void validate(final Object target, final Errors errors) {
    try {
        boolean hasErrors = errors.hasErrors();

        if (!hasErrors || passThruBeanValidation(hasErrors)) {
            // 各機能で実装しているバリデーションを実行する
            doValidate((T) target, errors);
        }
    } catch (RuntimeException e) {
        log.error("validate error", e);
        throw e;
    }
}
 
Example 12
Source File: EmployeeController.java    From training with MIT License 5 votes vote down vote up
@RequestMapping(value = "{id}", method = POST)
public String updateEmployee(@PathVariable String id, @Valid Employee employee, Errors errors) {
    if (errors.hasErrors()) {
    	log.error("Had errors: " + errors);
        return "employeeEditPage";
       }
	service.updateEmployee(id, employee);
	return "redirect:/employee/";
}
 
Example 13
Source File: DesignTacoController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@PostMapping
public String processDesign(@Valid @ModelAttribute("design") Taco design, Errors errors, Model model) {
  if (errors.hasErrors()) {
    return "design";
  }

  // Save the taco design...
  // We'll do this in chapter 3
  log.info("Processing design: " + design);

  return "redirect:/orders/current";
}
 
Example 14
Source File: SpitterController.java    From Project with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/register", method=POST)
public String processRegistration(
    @Valid Spitter spitter, 
    Errors errors) {
  if (errors.hasErrors()) {
    return "registerForm";
  }
  
  spitterRepository.save(spitter);
  return "redirect:/spitter/" + spitter.getUsername();
}
 
Example 15
Source File: TaskController.java    From todolist with MIT License 5 votes vote down vote up
@RequestMapping(value = "/{id:[0-9]+}", method = RequestMethod.POST)
public String update(@PathVariable("id") Long id, @Valid @ModelAttribute("form") TaskForm form, Errors errors) {
    if (errors.hasErrors()) {
        return "admin/task/edit";
    }

    Task task = null;
    User newBelongsTo = null;
    try {
        task = taskService.findOne(id);

        if (!task.getBelongsTo().getEmail().equals(form.getBelongsTo())) {
            newBelongsTo = userService.findByEmail(form.getBelongsTo());
            if(newBelongsTo == null) {
                errors.rejectValue("belongsTo", "NullPointerException", "请输入正确的邮箱地址或名称");
                return "admin/task/edit";
            }

            task.setBelongsTo(newBelongsTo);
            task.setBelongsToName(newBelongsTo.getName());
         task.setBelongsToEmail(newBelongsTo.getEmail());
        }

        form.push(task);
        taskService.save(task);
    } catch (DataAccessException ex) {
        errors.rejectValue("error", "DataAccesException", ex.getMessage());
        return "admin/task/edit";
    }

    return "redirect:/admin/tasks?q=id:" + task.getId();
}
 
Example 16
Source File: PostSubscriptionController.java    From nakadi with MIT License 5 votes vote down vote up
@RequestMapping(value = "/subscriptions/{subscription_id}", method = RequestMethod.PUT)
public ResponseEntity<?> updateSubscription(
        @PathVariable("subscription_id") final String subscriptionId,
        @Valid @RequestBody final SubscriptionBase subscription,
        final Errors errors,
        final NativeWebRequest request)
        throws NoSuchSubscriptionException, ValidationException, SubscriptionUpdateConflictException {
    if (errors.hasErrors()) {
        throw new ValidationException(errors);
    }
    subscriptionService.updateSubscription(subscriptionId, subscription);
    return ResponseEntity.noContent().build();

}
 
Example 17
Source File: DesignTacoController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@PostMapping
public String processDesign(
    @Valid Taco design, Errors errors, 
    @ModelAttribute Order order) {

  if (errors.hasErrors()) {
    return "design";
  }

  Taco saved = designRepo.save(design);
  order.addDesign(saved);

  return "redirect:/orders/current";
}
 
Example 18
Source File: FilterTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value="/persons", method=RequestMethod.POST)
public String save(@Valid Person person, Errors errors, RedirectAttributes redirectAttrs) {
	if (errors.hasErrors()) {
		return "person/add";
	}
	redirectAttrs.addAttribute("id", "1");
	redirectAttrs.addFlashAttribute("message", "success!");
	return "redirect:/person/{id}";
}
 
Example 19
Source File: RedirectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@PostMapping("/persons")
public String save(@Valid Person person, Errors errors, RedirectAttributes redirectAttrs) {
	if (errors.hasErrors()) {
		return "persons/add";
	}
	redirectAttrs.addAttribute("name", "Joe");
	redirectAttrs.addFlashAttribute("message", "success!");
	return "redirect:/persons/{name}";
}
 
Example 20
Source File: UserRESTController.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@PostMapping(value="/register",consumes= MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<String>> registerNewUser(@Valid @RequestBody UserDTO userDto,Errors errors) {
	
	if(userDto.getUsername() != null) {
		User existingUser = userRepository.findByUsername(userDto.getUsername());
		if(existingUser !=null) {
			
			errors.reject("Existing username", "User is already exist with usernae '"+userDto.getUsername()+"'. ");
		}
		existingUser = userRepository.findByEmail(userDto.getEmail());
		if(existingUser !=null) {
			errors.reject("Existing username", "User is already exist with email '"+userDto.getEmail()+"'. ");
		}
		
		if(!userDto.getPassword().equalsIgnoreCase(userDto.getConfirmPassword())) {
			errors.reject("password not match", "password and confirm password are not same");
		}
	}
	
	if(errors.hasErrors()) {
		List<String> errorMsg = new ArrayList<String>();
		errors.getAllErrors().forEach(a -> errorMsg.add(a.getDefaultMessage()));
		return new ResponseEntity<List<String>>(errorMsg, HttpStatus.BAD_REQUEST);
	}else {
		User userEntity = new User();
		userEntity.setUsername(userDto.getUsername());
		userEntity.setPassword(passwordEncoder.encode(userDto.getPassword()));
		userEntity.setEmail(userDto.getEmail());
		userEntity.setMobile(userDto.getMobile());
		
		userRepository.save(userEntity);
		List<String> msgLst = Arrays.asList("User registered successfully");
		return new ResponseEntity<List<String>>(msgLst, HttpStatus.OK);
	}
}