Search in sources :

Example 6 with BindException

use of org.springframework.validation.BindException in project spring-framework by spring-projects.

the class EscapedErrorsTests method testEscapedErrors.

@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()));
}
Also used : Errors(org.springframework.validation.Errors) ObjectError(org.springframework.validation.ObjectError) TestBean(org.springframework.tests.sample.beans.TestBean) BindException(org.springframework.validation.BindException) FieldError(org.springframework.validation.FieldError) Test(org.junit.Test)

Example 7 with BindException

use of org.springframework.validation.BindException in project spring-framework by spring-projects.

the class RequestContext method getErrors.

/**
	 * Retrieve the Errors instance for the given bind object.
	 * @param name name of the bind object
	 * @param htmlEscape create an Errors instance with automatic HTML escaping?
	 * @return the Errors instance, or {@code null} if not found
	 */
public Optional<Errors> getErrors(String name, boolean htmlEscape) {
    if (this.errorsMap == null) {
        this.errorsMap = new HashMap<>();
    }
    // Since there is no Optional orElse + flatMap...
    Optional<Errors> optional = Optional.ofNullable(this.errorsMap.get(name));
    optional = optional.isPresent() ? optional : getModelObject(BindingResult.MODEL_KEY_PREFIX + name);
    return optional.map(errors -> {
        if (errors instanceof BindException) {
            return ((BindException) errors).getBindingResult();
        } else {
            return errors;
        }
    }).map(errors -> {
        if (htmlEscape && !(errors instanceof EscapedErrors)) {
            errors = new EscapedErrors(errors);
        } else if (!htmlEscape && errors instanceof EscapedErrors) {
            errors = ((EscapedErrors) errors).getSource();
        }
        this.errorsMap.put(name, errors);
        return errors;
    });
}
Also used : Errors(org.springframework.validation.Errors) UriTemplate(org.springframework.web.util.UriTemplate) NoSuchMessageException(org.springframework.context.NoSuchMessageException) TimeZone(java.util.TimeZone) HashMap(java.util.HashMap) BindingResult(org.springframework.validation.BindingResult) HtmlUtils(org.springframework.web.util.HtmlUtils) ServerWebExchange(org.springframework.web.server.ServerWebExchange) List(java.util.List) Locale(java.util.Locale) Map(java.util.Map) EscapedErrors(org.springframework.web.bind.EscapedErrors) Optional(java.util.Optional) MessageSourceResolvable(org.springframework.context.MessageSourceResolvable) BindException(org.springframework.validation.BindException) MessageSource(org.springframework.context.MessageSource) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Assert(org.springframework.util.Assert) Errors(org.springframework.validation.Errors) EscapedErrors(org.springframework.web.bind.EscapedErrors) BindException(org.springframework.validation.BindException) EscapedErrors(org.springframework.web.bind.EscapedErrors)

Example 8 with BindException

use of org.springframework.validation.BindException in project grails-core by grails.

the class AbstractConstraintTests method validateConstraint.

protected Errors validateConstraint(Constraint constraint, Object value, Boolean shouldVeto) {
    BeanWrapper constrainedBean = new BeanWrapperImpl(new TestClass());
    constrainedBean.setPropertyValue(constraint.getPropertyName(), value);
    Errors errors = new BindException(constrainedBean.getWrappedInstance(), constrainedBean.getWrappedClass().getName());
    if (!(constraint instanceof VetoingConstraint) || shouldVeto == null) {
        constraint.validate(constrainedBean.getWrappedInstance(), value, errors);
    } else {
        boolean vetoed = ((VetoingConstraint) constraint).validateWithVetoing(constrainedBean.getWrappedInstance(), value, errors);
        if (shouldVeto.booleanValue() && !vetoed)
            fail("Constraint should veto");
        else if (!shouldVeto.booleanValue() && vetoed)
            fail("Constraint shouldn't veto");
    }
    return errors;
}
Also used : Errors(org.springframework.validation.Errors) BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) BindException(org.springframework.validation.BindException)

Example 9 with BindException

use of org.springframework.validation.BindException in project grails-core by grails.

the class ConstrainedPropertyTests method testConstraintBuilder.

@SuppressWarnings("rawtypes")
public void testConstraintBuilder() throws Exception {
    GroovyClassLoader gcl = new GroovyClassLoader();
    Class groovyClass = gcl.parseClass("class TestClass {\n" + "Long id\n" + "Long version\n" + "String login\n" + "String other\n" + "String email\n" + "static constraints = {\n" + "login(size:5..15,nullable:false,blank:false)\n" + "other(blank:false,size:5..15,nullable:false)\n" + "email(email:true)\n" + "}\n" + "}");
    GrailsApplication ga = new DefaultGrailsApplication(groovyClass);
    ga.initialise();
    new MappingContextBuilder(ga).build(groovyClass);
    GrailsDomainClass domainClass = (GrailsDomainClass) ga.getArtefact(DomainClassArtefactHandler.TYPE, "TestClass");
    Map constrainedProperties = domainClass.getConstrainedProperties();
    assert constrainedProperties.size() == 3;
    grails.gorm.validation.ConstrainedProperty loginConstraint = (grails.gorm.validation.ConstrainedProperty) constrainedProperties.get("login");
    Collection appliedConstraints = loginConstraint.getAppliedConstraints();
    assertTrue(appliedConstraints.size() == 3);
    // Check the order of the constraints for the 'login' property...
    int index = 0;
    String[] constraintNames = new String[] { "size", "nullable", "blank" };
    for (Iterator iter = appliedConstraints.iterator(); iter.hasNext(); ) {
        Constraint c = (Constraint) iter.next();
        assertEquals(constraintNames[index], c.getName());
        index++;
    }
    // ...and for the 'other' property.
    appliedConstraints = ((grails.gorm.validation.ConstrainedProperty) constrainedProperties.get("other")).getAppliedConstraints();
    index = 0;
    constraintNames = new String[] { "blank", "size", "nullable" };
    for (Iterator iter = appliedConstraints.iterator(); iter.hasNext(); ) {
        Constraint c = (Constraint) iter.next();
        assertEquals(constraintNames[index], c.getName());
        index++;
    }
    grails.gorm.validation.ConstrainedProperty emailConstraint = (grails.gorm.validation.ConstrainedProperty) constrainedProperties.get("email");
    assertEquals(2, emailConstraint.getAppliedConstraints().size());
    GroovyObject go = (GroovyObject) groovyClass.newInstance();
    go.setProperty("email", "rubbish_email");
    Errors errors = new BindException(go, "TestClass");
    emailConstraint.validate(go, go.getProperty("email"), errors);
    assertTrue(errors.hasErrors());
    go.setProperty("email", "valid@email.com");
    errors = new BindException(go, "TestClass");
    emailConstraint.validate(go, go.getProperty("email"), errors);
    assertFalse(errors.hasErrors());
}
Also used : GrailsDomainClass(grails.core.GrailsDomainClass) BindException(org.springframework.validation.BindException) DefaultGrailsApplication(grails.core.DefaultGrailsApplication) GroovyObject(groovy.lang.GroovyObject) GroovyClassLoader(groovy.lang.GroovyClassLoader) Errors(org.springframework.validation.Errors) DefaultGrailsApplication(grails.core.DefaultGrailsApplication) GrailsApplication(grails.core.GrailsApplication) Iterator(java.util.Iterator) Collection(java.util.Collection) GrailsDomainClass(grails.core.GrailsDomainClass) Map(java.util.Map)

Example 10 with BindException

use of org.springframework.validation.BindException in project opennms by OpenNMS.

the class DefaultDistributedPollerServiceTest method testDeleteLocationMonitorNullCommand.

public void testDeleteLocationMonitorNullCommand() {
    ThrowableAnticipator ta = new ThrowableAnticipator();
    ta.anticipate(new IllegalStateException("command argument cannot be null"));
    LocationMonitorIdCommand command = new LocationMonitorIdCommand();
    BindException errors = new BindException(command, "command");
    replayMocks();
    try {
        m_distributedPollerService.deleteLocationMonitor(null, errors);
    } catch (Throwable t) {
        ta.throwableReceived(t);
    }
    ta.verifyAnticipated();
    verifyMocks();
}
Also used : LocationMonitorIdCommand(org.opennms.web.svclayer.model.LocationMonitorIdCommand) BindException(org.springframework.validation.BindException) ThrowableAnticipator(org.opennms.test.ThrowableAnticipator)

Aggregations

BindException (org.springframework.validation.BindException)40 Errors (org.springframework.validation.Errors)15 LocationMonitorIdCommand (org.opennms.web.svclayer.model.LocationMonitorIdCommand)11 Test (org.junit.Test)9 ObjectError (org.springframework.validation.ObjectError)9 ThrowableAnticipator (org.opennms.test.ThrowableAnticipator)8 DistributedStatusDetailsCommand (org.opennms.web.svclayer.model.DistributedStatusDetailsCommand)8 OnmsLocationMonitor (org.opennms.netmgt.model.OnmsLocationMonitor)6 Map (java.util.Map)3 SimpleWebTable (org.opennms.web.svclayer.model.SimpleWebTable)3 BindingResult (org.springframework.validation.BindingResult)3 ModelAndView (org.springframework.web.servlet.ModelAndView)3 HashMap (java.util.HashMap)2 List (java.util.List)2 OnmsLocationSpecificStatus (org.opennms.netmgt.model.OnmsLocationSpecificStatus)2 StatisticsReportCommand (org.opennms.web.svclayer.model.StatisticsReportCommand)2 BeanWrapper (org.springframework.beans.BeanWrapper)2 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)2 TypeMismatchException (org.springframework.beans.TypeMismatchException)2 FieldError (org.springframework.validation.FieldError)2