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

The following examples show how to use org.springframework.validation.Errors#reject() . 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: PageValidator.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void validateJsonPatchRequest(JsonNode jsonPatch, Errors errors) {
    try {
        jsonPatchValidator.validatePatch(jsonPatch);
    } catch (PatchException e) {
        errors.reject(ERRCODE_INVALID_PATCH, "jsonPatch.invalid");
    }

    for (JsonNode node : jsonPatch) {
        String operationPath = node.get("path").asText();

        if (operationPath.equals("/code")) {
            errors.reject(ERRCODE_INVALID_PATCH, new String[]{"code"}, "jsonPatch.field.protected");
        }
    }

}
 
Example 2
Source File: TargetSeedsValidator.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void validate(Object comm, Errors errors) {
	SeedsCommand command = (SeedsCommand) comm;
	
	// Linking new seeds.
	if(command.isAction(SeedsCommand.ACTION_LINK_NEW_CONFIRM)) {
		if(command.getLinkPermIdentity() == null ||
		   command.getLinkPermIdentity().length == 0) {
			errors.reject("target.errors.link.noneselected");
		}
	}
	
	// Adding seeds.
	if(command.isAction(SeedsCommand.ACTION_ADD)) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "seed", "required", getObjectArrayForLabel("seed"), "Seed is a required field");
		
           if (command.getSeed() != null && command.getSeed().length() > 0) {
               ValidatorUtil.validateURL(errors, command.getSeed(), "target.errors.badUrl", getObjectArrayForLabel("seed"),"Invalid URL");
           }
	}
	
	// Searching for Permissions
	if( command.isAction(SeedsCommand.ACTION_LINK_NEW_SEARCH)) {
		validateLinkSearch(command, errors);
	}
}
 
Example 3
Source File: ErrorsTagTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * https://jira.spring.io/browse/SPR-4005
 */
@Test
public void omittedPathMatchesObjectErrorsOnly() throws Exception {
	this.tag.setPath(null);
	Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
	errors.reject("some.code", "object error");
	errors.rejectValue("name", "some.code", "field error");
	exposeBindingResult(errors);
	this.tag.doStartTag();
	assertNotNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
	this.tag.doEndTag();
	String output = getOutput();
	assertTrue(output.contains("id=\"testBean.errors\""));
	assertTrue(output.contains("object error"));
	assertFalse(output.contains("field error"));
}
 
Example 4
Source File: RoleValidator.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void validateJsonPatch(JsonNode jsonPatch, Errors errors) {
    try {
        jsonPatchValidator.validatePatch(jsonPatch);
    } catch (PatchException e) {
        errors.reject(ERRCODE_INVALID_PATCH, "jsonPatch.invalid");
    }

    for (JsonNode node : jsonPatch) {
        String operationPath = node.get("path").asText();

        if (operationPath.equals("/code")) {
            errors.reject(ERRCODE_INVALID_PATCH, new String[]{"code"}, "jsonPatch.field.protected");
        }
    }

}
 
Example 5
Source File: DataObjectModelValidator.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void validateDataObjectModelJsonPatch(JsonNode jsonPatch, Errors errors) {
    try {
        jsonPatchValidator.validatePatch(jsonPatch);
    } catch (PatchException e) {
        errors.reject(ERRCODE_INVALID_PATCH, "jsonPatch.invalid");
    }

    for (JsonNode node : jsonPatch) {
        String operationPath = node.get("path").asText();

        if (operationPath.equals("/modelId")) {
            errors.reject(ERRCODE_INVALID_PATCH, new String[]{"modelId"}, "jsonPatch.field.protected");
        }
    }

}
 
Example 6
Source File: WebMvcConfigurationSupportExtensionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Validator getValidator() {
	return new Validator() {
		@Override
		public void validate(@Nullable Object target, Errors errors) {
			errors.reject("invalid");
		}
		@Override
		public boolean supports(Class<?> clazz) {
			return true;
		}
	};
}
 
Example 7
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Object target, Errors errors) {
	String value = (String) target;
	if (invalidValue.equals(value)) {
		errors.reject("invalid value '"+invalidValue+"'");
	}
}
 
Example 8
Source File: EntityValidator.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void validate(Object target, Errors errors) {
    EntityDto request = (EntityDto) target;
    if (this.existEntity(request.getId())) {
        errors.reject(ERRCODE_ENTITY_ALREADY_EXISTS, new String[]{request.getId()}, "entity.exists");
    }
}
 
Example 9
Source File: MethodJmsListenerEndpointTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Validator testValidator(final String invalidValue) {
	return new Validator() {
		@Override
		public boolean supports(Class<?> clazz) {
			return String.class.isAssignableFrom(clazz);
		}
		@Override
		public void validate(Object target, Errors errors) {
			String value = (String) target;
			if (invalidValue.equals(value)) {
				errors.reject("not a valid value");
			}
		}
	};
}
 
Example 10
Source File: ApiConsumerValidator.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void validateGrantTypes(List<String> grantTypes, Errors errors) {

        List<String> validGrantTypes = Arrays.asList(IOAuthConsumerManager.GRANT_TYPES);

        for (String grantType : grantTypes) {
            if (!validGrantTypes.contains(grantType)) {
                errors.reject(ERRCODE_INVALID_GRANT_TYPE, new String[]{grantType}, "api.consumer.grantType.invalid");
            }
        }
    }
 
Example 11
Source File: AbstractJmsAnnotationDrivenTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Object target, Errors errors) {
	String value = (String) target;
	if ("failValidation".equals(value)) {
		errors.reject("TEST: expected invalid value");
	}
}
 
Example 12
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 13
Source File: MoveTargetsValidator.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/** @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) */
public void validate(Object comm, Errors errors) {
	MoveTargetsCommand command = (MoveTargetsCommand) comm;
	
	
	if(MoveTargetsCommand.ACTION_MOVE_TARGETS.equals(command.getActionCmd())) {
		if((command.getParentOids() == null || command.getParentOids().length == 0) &&
				command.getSelectedCount() == 0) {
			errors.reject("target.errors.addparents.must_select");
		}
	}
}
 
Example 14
Source File: PayloadMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Validator testValidator() {
	return new Validator() {
		@Override
		public boolean supports(Class<?> clazz) {
			return String.class.isAssignableFrom(clazz);
		}
		@Override
		public void validate(Object target, Errors errors) {
			String value = (String) target;
			if ("invalidValue".equals(value)) {
				errors.reject("invalid value");
			}
		}
	};
}
 
Example 15
Source File: EscapedErrorsTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testEscapedErrors() {
	TestBean tb = new TestBean();
	tb.setName("empty &");

	Errors errors = new EscapedErrors(new BindException(tb, "tb"));
	errors.rejectValue("name", "NAME_EMPTY &", null, "message: &");
	errors.rejectValue("age", "AGE_NOT_SET <tag>", null, "message: <tag>");
	errors.rejectValue("age", "AGE_NOT_32 <tag>", null, "message: <tag>");
	errors.reject("GENERAL_ERROR \" '", null, "message: \" '");

	assertTrue("Correct errors flag", errors.hasErrors());
	assertTrue("Correct number of errors", errors.getErrorCount() == 4);
	assertTrue("Correct object name", "tb".equals(errors.getObjectName()));

	assertTrue("Correct global errors flag", errors.hasGlobalErrors());
	assertTrue("Correct number of global errors", errors.getGlobalErrorCount() == 1);
	ObjectError globalError = errors.getGlobalError();
	assertTrue("Global error message escaped", "message: &quot; &#39;".equals(globalError.getDefaultMessage()));
	assertTrue("Global error code not escaped", "GENERAL_ERROR \" '".equals(globalError.getCode()));
	ObjectError globalErrorInList = errors.getGlobalErrors().get(0);
	assertTrue("Same global error in list", globalError.getDefaultMessage().equals(globalErrorInList.getDefaultMessage()));
	ObjectError globalErrorInAllList = errors.getAllErrors().get(3);
	assertTrue("Same global error in list", globalError.getDefaultMessage().equals(globalErrorInAllList.getDefaultMessage()));

	assertTrue("Correct field errors flag", errors.hasFieldErrors());
	assertTrue("Correct number of field errors", errors.getFieldErrorCount() == 3);
	assertTrue("Correct number of field errors in list", errors.getFieldErrors().size() == 3);
	FieldError fieldError = errors.getFieldError();
	assertTrue("Field error code not escaped", "NAME_EMPTY &".equals(fieldError.getCode()));
	assertTrue("Field value escaped", "empty &amp;".equals(errors.getFieldValue("name")));
	FieldError fieldErrorInList = errors.getFieldErrors().get(0);
	assertTrue("Same field error in list", fieldError.getDefaultMessage().equals(fieldErrorInList.getDefaultMessage()));

	assertTrue("Correct name errors flag", errors.hasFieldErrors("name"));
	assertTrue("Correct number of name errors", errors.getFieldErrorCount("name") == 1);
	assertTrue("Correct number of name errors in list", errors.getFieldErrors("name").size() == 1);
	FieldError nameError = errors.getFieldError("name");
	assertTrue("Name error message escaped", "message: &amp;".equals(nameError.getDefaultMessage()));
	assertTrue("Name error code not escaped", "NAME_EMPTY &".equals(nameError.getCode()));
	assertTrue("Name value escaped", "empty &amp;".equals(errors.getFieldValue("name")));
	FieldError nameErrorInList = errors.getFieldErrors("name").get(0);
	assertTrue("Same name error in list", nameError.getDefaultMessage().equals(nameErrorInList.getDefaultMessage()));

	assertTrue("Correct age errors flag", errors.hasFieldErrors("age"));
	assertTrue("Correct number of age errors", errors.getFieldErrorCount("age") == 2);
	assertTrue("Correct number of age errors in list", errors.getFieldErrors("age").size() == 2);
	FieldError ageError = errors.getFieldError("age");
	assertTrue("Age error message escaped", "message: &lt;tag&gt;".equals(ageError.getDefaultMessage()));
	assertTrue("Age error code not escaped", "AGE_NOT_SET <tag>".equals(ageError.getCode()));
	assertTrue("Age value not escaped", (new Integer(0)).equals(errors.getFieldValue("age")));
	FieldError ageErrorInList = errors.getFieldErrors("age").get(0);
	assertTrue("Same name error in list", ageError.getDefaultMessage().equals(ageErrorInList.getDefaultMessage()));
	FieldError ageError2 = errors.getFieldErrors("age").get(1);
	assertTrue("Age error 2 message escaped", "message: &lt;tag&gt;".equals(ageError2.getDefaultMessage()));
	assertTrue("Age error 2 code not escaped", "AGE_NOT_32 <tag>".equals(ageError2.getCode()));
}
 
Example 16
Source File: PayloadMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void validate(@Nullable Object target, Errors errors) {
	if (target instanceof String && ((String) target).length() < 8) {
		errors.reject("Invalid length");
	}
}
 
Example 17
Source File: SitePermissionValidator.java    From webcurator with Apache License 2.0 4 votes vote down vote up
public void validate(Object aCmd, Errors aErrors) {
	SitePermissionCommand cmd = (SitePermissionCommand) aCmd;
	
	if(cmd.isAction(SitePermissionCommand.ACTION_SAVE) || cmd.isAction(SitePermissionCommand.ACTION_ADD_EXCLUSION)) {
		ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "authorisingAgent", "required", new Object[] {"Authorising Agent"}, "Authorising Agent is a required field.");
		ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "startDate", "required", new Object[] {"Start date"}, "Start date is a required field.");
		if (cmd.isQuickPick()) {
			ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "displayName", "required", new Object[] {"Display name"}, "Display name is a required field.");
		}
		
		if (cmd.getUrls() == null || cmd.getUrls().isEmpty()) {		
			//aErrors.reject("required", new Object[] {"Urls"}, "Urls is a required field.");
			aErrors.reject("", new Object[] {"Urls"}, "Choose at least one Url pattern.");
		}
		
		if(cmd.isCreateSeekPermissionTask() && cmd.getStatus() != Permission.STATUS_PENDING) {
			aErrors.reject("permission.errors.create_task");
		}
		
		if (!aErrors.hasErrors()) {
			ValidatorUtil.validateStartBeforeEndTime(aErrors, cmd.getStartDate(), cmd.getEndDate(), "time.range", new Object[] {"End date", "Start date"}, "The end date is before the start date");
			ValidatorUtil.validateStringMaxLength(aErrors, cmd.getAuthResponse(), 32000, "string.maxlength", new Object[] {"Auth. Agency Response", "32000"}, "Auth. Agency Response is too long");
			ValidatorUtil.validateStringMaxLength(aErrors, cmd.getSpecialRequirements(), 2048, "string.maxlength", new Object[] {"Special Requirements", "2048"}, "Special Requirements is too long");
			ValidatorUtil.validateStringMaxLength(aErrors, cmd.getDisplayName(), 32, "string.maxlength", new Object[] {"Display name", "32"}, "Display name is too long");
			ValidatorUtil.validateStringMaxLength(aErrors, cmd.getCopyrightStatement(), 2048, "string.maxlength", new Object[] {"Copyright Statement", "2048"}, "Copyright Statement is too long");
			ValidatorUtil.validateStringMaxLength(aErrors, cmd.getCopyrightUrl(), 2048, "string.maxlength", new Object[] {"Copyright URL", "2048"}, "Copyright URL is too long");
			ValidatorUtil.validateStringMaxLength(aErrors, cmd.getFileReference(), Permission.MAX_FILE_REF_LENGTH, "string.maxlength", new Object[] {"File Reference", Permission.MAX_FILE_REF_LENGTH}, "File Reference is too long");
		}
	}
	
	if(cmd.isAction(SitePermissionCommand.ACTION_ADD_EXCLUSION)) {
		ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "exclusionUrl", "required", new Object[] {"Exclusion URL"}, "Exclusion URL is a required field.");
		ValidatorUtil.validateStringMaxLength(aErrors, cmd.getExclusionUrl(), 1024, "string.maxlength", new Object[] {"Exclusion URL", "1024"}, "Exclusion URL is too long");
		ValidatorUtil.validateStringMaxLength(aErrors, cmd.getExclusionReason(), 1024, "string.maxlength", new Object[] {"Exclusion Reason", "1024"}, "Exclusion Reason is too long");			
	}
	
	if(cmd.isAction(SitePermissionCommand.ACTION_ADD_NOTE) ||
			cmd.isAction(SitePermissionCommand.ACTION_MODIFY_NOTE)) {
		ValidationUtils.rejectIfEmptyOrWhitespace(aErrors, "note", "required", new Object[] {"Annotation"}, "Annotation is a required field.");
		ValidatorUtil.validateStringMaxLength(aErrors, cmd.getNote(), SitePermissionCommand.CNST_MAX_NOTE_LENGTH, "string.maxlength", getObjectArrayForLabelAndInt(SitePermissionCommand.PARAM_NOTE, SitePermissionCommand.CNST_MAX_NOTE_LENGTH), "Annotation is too long");
	}
}
 
Example 18
Source File: ValidatorUtil.java    From webcurator with Apache License 2.0 3 votes vote down vote up
/**
 * Helper function to validate the length of a string input field.
 * @param aErrors the errors object to populate
 * @param aField the field to check the length of
 * @param aMaxLength the length to check against
 * @param aErrorCode the code for the message resource value
 * @param aValues the list of values to replace in the i8n messages
 * @param aFailureMessage the default failure message
 */
public static void validateStringMaxLength(Errors aErrors, String aField, int aMaxLength, String aErrorCode, Object[] aValues, String aFailureMessage) {
    if (aField != null && !aField.trim().equals("")) {
        if (aField.length() > aMaxLength) {
            aErrors.reject(aErrorCode, aValues, aFailureMessage);
        }
    }
}
 
Example 19
Source File: ValidatorUtil.java    From webcurator with Apache License 2.0 3 votes vote down vote up
/**
 * Helper method to validated that a start time is before or equal to the 
 * end time.
 * @param aErrors the errors object to populate 
 * @param aStart the start time
 * @param aEnd the end time
 * @param aErrorCode the error code
 * @param aValues the values to set in the error message
 * @param aFailureMessage the default failure message
 */
public static void validateStartBeforeOrEqualEndTime(Errors aErrors, Date aStart, Date aEnd, String aErrorCode, Object[] aValues, String aFailureMessage) {
    if (aStart != null && aEnd != null) {
        if (aStart.after(aEnd)) {
            aErrors.reject(aErrorCode, aValues, aFailureMessage);
        }
    }
}
 
Example 20
Source File: ValidatorUtil.java    From webcurator with Apache License 2.0 2 votes vote down vote up
/**
 * Helper method to validate a supplied URL is correctly formatted
 * @param aErrors The errors object to populate
 * @param aURL The URL to check
 * @param aErrorCode the error code for getting the i8n failure message
 * @param aValues the list of values to replace in the i8n messages
 * @param aFailureMessage the default error message
 */
public static void validateURL(Errors aErrors, String aURL, String aErrorCode, Object[] aValues, String aFailureMessage) {        
    if(!UrlUtils.isUrl(aURL)) {
        aErrors.reject(aErrorCode, aValues, aFailureMessage);
    }
}