Search in sources :

Example 21 with MapBindingResult

use of org.springframework.validation.MapBindingResult in project spring-boot by spring-projects.

the class DefaultErrorAttributesTests method extractBindingResultErrors.

@Test
public void extractBindingResultErrors() throws Exception {
    BindingResult bindingResult = new MapBindingResult(Collections.singletonMap("a", "b"), "objectName");
    bindingResult.addError(new ObjectError("c", "d"));
    Exception ex = new BindException(bindingResult);
    testBindingResult(bindingResult, ex);
}
Also used : BindingResult(org.springframework.validation.BindingResult) MapBindingResult(org.springframework.validation.MapBindingResult) ObjectError(org.springframework.validation.ObjectError) BindException(org.springframework.validation.BindException) MapBindingResult(org.springframework.validation.MapBindingResult) ServletException(javax.servlet.ServletException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) BindException(org.springframework.validation.BindException) Test(org.junit.Test)

Example 22 with MapBindingResult

use of org.springframework.validation.MapBindingResult in project ORCID-Source by ORCID.

the class RegistrationController method regEmailValidate.

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");
    }
    String emailAddress = reg.getEmail().getValue();
    MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email");
    // Validate the email address is ok        
    if (!validateEmailAddress(emailAddress)) {
        String[] codes = { "Email.personalInfoForm.email" };
        String[] args = { emailAddress };
        mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Not vaild"));
    } else {
        //If email exists
        if (emailManager.emailExists(emailAddress)) {
            String orcid = emailManager.findOrcidIdByEmail(emailAddress);
            String[] args = { emailAddress };
            //If it is claimed, should return a duplicated exception
            if (profileEntityManager.isProfileClaimedByEmail(emailAddress)) {
                String[] codes = null;
                if (profileEntityManager.isDeactivated(orcid)) {
                    codes = new String[] { "orcid.frontend.verify.deactivated_email" };
                } else {
                    codes = new String[] { "orcid.frontend.verify.duplicate_email" };
                }
                mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Email already exists"));
            } else {
                if (profileEntityManager.isDeactivated(orcid)) {
                    String[] codes = new String[] { "orcid.frontend.verify.deactivated_email" };
                    mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Email already exists"));
                } else if (!emailManager.isAutoDeprecateEnableForEmail(emailAddress)) {
                    //If the email is not eligible for auto deprecate, we should show an email duplicated exception                        
                    String resendUrl = createResendClaimUrl(emailAddress, request);
                    String[] codes = { "orcid.frontend.verify.unclaimed_email" };
                    args = new String[] { emailAddress, resendUrl };
                    mbr.addError(new FieldError("email", "email", emailAddress, false, codes, args, "Unclaimed record exists"));
                } else {
                    LOGGER.info("Email " + emailAddress + " belongs to a unclaimed record and can be auto deprecated");
                }
            }
        }
    }
    for (ObjectError oe : mbr.getAllErrors()) {
        Object[] arguments = oe.getArguments();
        if (isOauthRequest && oe.getCode().equals("orcid.frontend.verify.duplicate_email")) {
            // XXX
            reg.getEmail().getErrors().add(getMessage("oauth.registration.duplicate_email", arguments));
        } else if (oe.getCode().equals("orcid.frontend.verify.duplicate_email")) {
            Object email = "";
            if (arguments != null && arguments.length > 0) {
                email = arguments[0];
            }
            String link = "/signin";
            String linkType = reg.getLinkType();
            if ("social".equals(linkType)) {
                link = "/social/access";
            } else if ("shibboleth".equals(linkType)) {
                link = "/shibboleth/signin";
            }
            reg.getEmail().getErrors().add(getMessage(oe.getCode(), email, orcidUrlManager.getBaseUrl() + link));
        } else if (oe.getCode().equals("orcid.frontend.verify.deactivated_email")) {
            // Handle this message in angular to allow AJAX action
            reg.getEmail().getErrors().add(oe.getCode());
        } 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;
}
Also used : ObjectError(org.springframework.validation.ObjectError) MapBindingResult(org.springframework.validation.MapBindingResult) FieldError(org.springframework.validation.FieldError)

Example 23 with MapBindingResult

use of org.springframework.validation.MapBindingResult in project openmrs-core by openmrs.

the class RelationshipValidatorTest method validate_shouldPassIfStartDateIsEmpty.

/**
 * @see RelationshipValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldPassIfStartDateIsEmpty() {
    Map<String, String> map = new HashMap<>();
    MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName());
    Relationship relationship = new Relationship(1);
    relationship.setStartDate(null);
    new RelationshipValidator().validate(relationship, errors);
    Assert.assertFalse(errors.hasErrors());
}
Also used : HashMap(java.util.HashMap) Relationship(org.openmrs.Relationship) MapBindingResult(org.springframework.validation.MapBindingResult) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Example 24 with MapBindingResult

use of org.springframework.validation.MapBindingResult in project openmrs-core by openmrs.

the class RelationshipValidatorTest method validate_shouldFailIfStartDateIsInFuture.

/**
 * @see RelationshipValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldFailIfStartDateIsInFuture() {
    Relationship relationship = new Relationship(1);
    Map<String, String> map = new HashMap<>();
    MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName());
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.YEAR, 1);
    Date nextYear = cal.getTime();
    relationship.setStartDate(nextYear);
    new RelationshipValidator().validate(relationship, errors);
    Assert.assertTrue(errors.hasErrors());
}
Also used : HashMap(java.util.HashMap) Relationship(org.openmrs.Relationship) Calendar(java.util.Calendar) MapBindingResult(org.springframework.validation.MapBindingResult) Date(java.util.Date) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Example 25 with MapBindingResult

use of org.springframework.validation.MapBindingResult in project spring-integration by spring-projects.

the class HttpRequestHandlingController method handleRequest.

/**
 * Handles the HTTP request by generating a Message and sending it to the request channel. If this gateway's
 * 'expectReply' property is true, it will also generate a response from the reply Message once received.
 */
@Override
public final ModelAndView handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception {
    ModelAndView modelAndView = new ModelAndView();
    try {
        Message<?> replyMessage = super.doHandleRequest(servletRequest, servletResponse);
        ServletServerHttpResponse response = new ServletServerHttpResponse(servletResponse);
        if (replyMessage != null) {
            Object reply = setupResponseAndConvertReply(response, replyMessage);
            response.close();
            modelAndView.addObject(this.replyKey, reply);
        } else {
            setStatusCodeIfNeeded(response);
        }
        if (this.viewExpression != null) {
            Object view;
            if (replyMessage != null) {
                view = this.viewExpression.getValue(this.evaluationContext, replyMessage);
            } else {
                view = this.viewExpression.getValue(this.evaluationContext);
            }
            if (view instanceof View) {
                modelAndView.setView((View) view);
            } else if (view instanceof String) {
                modelAndView.setViewName((String) view);
            } else {
                throw new IllegalStateException("view expression must resolve to a View or String");
            }
        }
    } catch (Exception e) {
        MapBindingResult errors = new MapBindingResult(new HashMap<String, Object>(), "dummy");
        PrintWriter stackTrace = new PrintWriter(new StringWriter());
        e.printStackTrace(stackTrace);
        errors.reject(this.errorCode, new Object[] { e, e.getMessage(), stackTrace.toString() }, "A Spring Integration handler raised an exception while handling an HTTP request.  The exception is of type " + e.getClass() + " and it has a message: (" + e.getMessage() + ")");
        modelAndView.addObject(this.errorsKey, errors);
    }
    return modelAndView;
}
Also used : StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse) MapBindingResult(org.springframework.validation.MapBindingResult) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) PrintWriter(java.io.PrintWriter)

Aggregations

MapBindingResult (org.springframework.validation.MapBindingResult)40 Test (org.junit.Test)22 ObjectError (org.springframework.validation.ObjectError)12 BindingResult (org.springframework.validation.BindingResult)11 HashMap (java.util.HashMap)10 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)9 Test (org.junit.jupiter.api.Test)6 Relationship (org.openmrs.Relationship)6 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)6 Method (java.lang.reflect.Method)5 GuiFragmentRequestBody (org.entando.entando.web.guifragment.model.GuiFragmentRequestBody)5 MethodParameter (org.springframework.core.MethodParameter)5 BindException (org.springframework.validation.BindException)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 ServletException (jakarta.servlet.ServletException)3 RestAccessControl (org.entando.entando.web.common.annotation.RestAccessControl)3 ValidationGenericException (org.entando.entando.web.common.exceptions.ValidationGenericException)3 ResponseEntity (org.springframework.http.ResponseEntity)3 FieldError (org.springframework.validation.FieldError)3 WebExchangeBindException (org.springframework.web.bind.support.WebExchangeBindException)3