Java Examples for org.springframework.validation.ObjectError

The following java examples will help you to understand the usage of org.springframework.validation.ObjectError. These source code samples are taken from different open source projects.

Example 1
Project: geoserver-master  File: ValidationException.java View source code
private static String buildMessage(Errors errors) {
    StringBuilder sb = new StringBuilder("Validation failed for input '").append(errors.getObjectName()).append("': ");
    for (ObjectError error : errors.getGlobalErrors()) {
        sb.append(error.getDefaultMessage());
        sb.append("\n");
    }
    for (FieldError error : errors.getFieldErrors()) {
        sb.append(error.getField()).append("[").append(error.getDefaultMessage()).append("]");
        sb.append("\n");
    }
    sb.setLength(sb.length() - 1);
    return sb.toString();
}
Example 2
Project: spring-reference-master  File: ObjectErrorAdapterTest.java View source code
@Test
public void marshalObjectError() throws Exception {
    XmlFriendlyError result = adapter.marshal(new ObjectError("order", "msg"));
    assertEquals("order", result.getObjectName());
    assertNull(result.getField());
    assertEquals("msg", result.getDefaultMessage());
    assertNull(result.getRejectedValue());
    assertNull(result.getCodes());
    assertNull(result.getArguments());
}
Example 3
Project: spring4-showcase-master  File: AjaxError.java View source code
public static AjaxError from(Errors errors, Locale locale) {
    AjaxError ajaxError = new AjaxError();
    if (errors.hasGlobalErrors()) {
        ajaxError.globalErrors = new ArrayList<>();
        for (ObjectError error : errors.getGlobalErrors()) {
            ajaxError.globalErrors.add(getMessage(error, locale));
        }
    }
    if (errors.hasFieldErrors()) {
        ajaxError.fieldErrors = new ArrayList<>();
        for (FieldError error : errors.getFieldErrors()) {
            Map<String, String> errorData = new HashMap<>();
            errorData.put(error.getField(), getMessage(error, locale));
            ajaxError.fieldErrors.add(errorData);
        }
    }
    return ajaxError;
}
Example 4
Project: appfuse-light-master  File: UserFormController.java View source code
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult result, HttpServletRequest request) throws Exception {
    if (request.getParameter("cancel") != null) {
        return "redirect:users";
    }
    if (validator != null && request.getParameter("delete") == null) {
        // validator is null during testing
        validator.validate(user, result);
        if (result.hasErrors()) {
            return "userform";
        }
    }
    log.debug("entering 'onSubmit' method...");
    if (request.getParameter("delete") != null) {
        userManager.removeUser(user.getId().toString());
        saveMessage(request, getText("user.deleted", user.getFullName(), request.getLocale()));
    } else {
        try {
            userManager.saveUser(user);
        } catch (UserExistsException uex) {
            result.addError(new ObjectError("user", uex.getMessage()));
            return "userform";
        }
        saveMessage(request, getText("user.saved", user.getFullName(), request.getLocale()));
    }
    return "redirect:users";
}
Example 5
Project: categolj2-backend-master  File: ApiErrorCreator.java View source code
public ApiError createBindingResultApiError(WebRequest request, String errorCode, BindingResult bindingResult, String defaultErrorMessage) {
    ApiError apiError = createApiError(request, errorCode, defaultErrorMessage);
    for (FieldError fieldError : bindingResult.getFieldErrors()) {
        apiError.addDetail(createApiError(request, fieldError, fieldError.getField()));
    }
    for (ObjectError objectError : bindingResult.getGlobalErrors()) {
        apiError.addDetail(createApiError(request, objectError, objectError.getObjectName()));
    }
    return apiError;
}
Example 6
Project: demo-application-master  File: ApiErrorCreator.java View source code
public ApiError createBindingResultApiError(final WebRequest request, final String errorCode, final BindingResult bindingResult, final String defaultErrorMessage) {
    final ApiError apiError = createApiError(request, errorCode, defaultErrorMessage);
    for (final FieldError fieldError : bindingResult.getFieldErrors()) {
        apiError.addDetail(createApiError(request, fieldError, fieldError.getField()));
    }
    for (final ObjectError objectError : bindingResult.getGlobalErrors()) {
        apiError.addDetail(createApiError(request, objectError, objectError.getObjectName()));
    }
    return apiError;
}
Example 7
Project: head-master  File: LoanProductFormBeanValidator.java View source code
private void validateInterestRateRange(LoanProductFormBean loanProductFormBean, BindingResult result) {
    if (!result.hasErrors()) {
        if (loanProductFormBean.getMinInterestRate() > loanProductFormBean.getMaxInterestRate()) {
            ObjectError error = new ObjectError("loanProduct", new String[] { "Range.loanProduct.maxInterestRate" }, new Object[] {}, "The min must be less than max.");
            result.addError(error);
        }
        if (loanProductFormBean.getDefaultInterestRate() < loanProductFormBean.getMinInterestRate() || loanProductFormBean.getDefaultInterestRate() > loanProductFormBean.getMaxInterestRate()) {
            ObjectError error = new ObjectError("loanProduct", new String[] { "Range.loanProduct.defaultInterestRate" }, new Object[] {}, "The min must be less than max.");
            result.addError(error);
        }
    }
}
Example 8
Project: Hygieia-master  File: ErrorResponse.java View source code
public static ErrorResponse fromBindException(BindException bindException) {
    ErrorResponse errorResponse = new ErrorResponse();
    for (ObjectError objectError : bindException.getGlobalErrors()) {
        List<String> errors = errorResponse.getGlobalErrors().get(objectError.getObjectName());
        if (errors == null) {
            errors = new ArrayList<String>();
            errorResponse.getGlobalErrors().put(objectError.getObjectName(), errors);
        }
        errors.add(objectError.getDefaultMessage());
    }
    for (FieldError fieldError : bindException.getFieldErrors()) {
        List<String> errors = errorResponse.getFieldErrors().get(fieldError.getField());
        if (errors == null) {
            errors = new ArrayList<String>();
            errorResponse.getFieldErrors().put(fieldError.getField(), errors);
        }
        errors.add(fieldError.getDefaultMessage());
    }
    return errorResponse;
}
Example 9
Project: jdal-master  File: ViewSupport.java View source code
/**
	 * Build a error message with all errors.
	 * @return String with error message
	 */
public String getErrorMessage() {
    StringBuilder sb = new StringBuilder();
    if (errors.hasErrors()) {
        sb.append("\n");
        Iterator<ObjectError> iter = errors.getAllErrors().iterator();
        while (iter.hasNext()) {
            ObjectError oe = (ObjectError) iter.next();
            sb.append("- ");
            sb.append(getMessage(oe));
            sb.append("\n");
        }
    }
    sb.append("\n");
    return sb.toString();
}
Example 10
Project: mifos-head-master  File: LoanProductFormBeanValidator.java View source code
private void validateInterestRateRange(LoanProductFormBean loanProductFormBean, BindingResult result) {
    if (!result.hasErrors()) {
        if (loanProductFormBean.getMinInterestRate() > loanProductFormBean.getMaxInterestRate()) {
            ObjectError error = new ObjectError("loanProduct", new String[] { "Range.loanProduct.maxInterestRate" }, new Object[] {}, "The min must be less than max.");
            result.addError(error);
        }
        if (loanProductFormBean.getDefaultInterestRate() < loanProductFormBean.getMinInterestRate() || loanProductFormBean.getDefaultInterestRate() > loanProductFormBean.getMaxInterestRate()) {
            ObjectError error = new ObjectError("loanProduct", new String[] { "Range.loanProduct.defaultInterestRate" }, new Object[] {}, "The min must be less than max.");
            result.addError(error);
        }
    }
}
Example 11
Project: molgenis-master  File: OptionsWizardPage.java View source code
@Override
public String handleRequest(HttpServletRequest request, BindingResult result, Wizard wizard) {
    ImportWizardUtil.validateImportWizard(wizard);
    ImportWizard importWizard = (ImportWizard) wizard;
    String entityImportOption = request.getParameter("entity_option");
    importWizard.setEntityImportOption(entityImportOption);
    if (importWizard.getMustChangeEntityName()) {
        String userGivenName = request.getParameter("name");
        if (StringUtils.isEmpty(userGivenName)) {
            result.addError(new ObjectError("wizard", "Please enter an entity name"));
            return null;
        }
        try {
            NameValidator.validateName(userGivenName);
            if (dataService.hasRepository(userGivenName)) {
                result.addError(new ObjectError("wizard", "An entity with this name already exists."));
                return null;
            }
        } catch (MolgenisDataException e) {
            ImportWizardUtil.handleException(e, importWizard, result, LOG, entityImportOption);
            return null;
        }
        File tmpFile = importWizard.getFile();
        String fileName = tmpFile.getName();
        // FIXME: can this be done a bit cleaner?
        String extension = FileExtensionUtils.findExtensionFromPossibilities(fileName, fileRepositoryCollectionFactory.createFileRepositoryCollection(tmpFile).getFileNameExtensions());
        File file = new File(tmpFile.getParent(), userGivenName + "." + extension);
        tmpFile.renameTo(file);
        importWizard.setFile(file);
    }
    try {
        return validateInput(importWizard.getFile(), importWizard, result);
    } catch (Exception e) {
        ImportWizardUtil.handleException(e, importWizard, result, LOG, entityImportOption);
    }
    return null;
}
Example 12
Project: okmakeover-master  File: UserController.java View source code
/**
     * 회� 가입 Processing
     * @param user
     * @return
     */
@RequestMapping(value = "/sign_up", method = RequestMethod.POST)
public String signUp(@ModelAttribute("userForm") @Valid User user, BindingResult bindingResult, RedirectAttributes ra) {
    if (bindingResult.hasErrors()) {
        user.setPassword("");
        user.setPasswordConfirm("");
        return "user/sign_up";
    }
    try {
        boolean success = userService.create(user);
        ra.addFlashAttribute("result", new Result(success, "가입� 완료�었습니다."));
    } catch (Exception e) {
        bindingResult.addError(new ObjectError("", e.getMessage()));
        return "user/sign_up";
    }
    return "redirect:/user/login";
}
Example 13
Project: opentides3-master  File: CrudUtil.java View source code
/**
	 * Converts the binding error messages to list of MessageResponse
	 * 
	 * @param bindingResult
	 */
public static List<MessageResponse> convertErrorMessage(final BindingResult bindingResult, final Locale locale, final MessageSource messageSource) {
    final List<MessageResponse> errorMessages = new ArrayList<MessageResponse>();
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            MessageResponse message = null;
            if (error instanceof FieldError) {
                final FieldError ferror = (FieldError) error;
                message = new MessageResponse(MessageResponse.Type.error, error.getObjectName(), ferror.getField(), error.getCodes(), error.getArguments());
            } else {
                message = new MessageResponse(MessageResponse.Type.error, error.getObjectName(), null, error.getCodes(), error.getArguments());
            }
            message.setMessage(messageSource.getMessage(message, locale));
            errorMessages.add(message);
        }
    }
    return errorMessages;
}
Example 14
Project: spring-framework-master  File: ValidatorFactoryTests.java View source code
@Test
public void testSpringValidationWithClassLevel() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.setName("Juergen");
    person.getAddress().setStreet("Juergen's Street");
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(1, result.getErrorCount());
    ObjectError globalError = result.getGlobalError();
    List<String> errorCodes = Arrays.asList(globalError.getCodes());
    assertEquals(2, errorCodes.size());
    assertTrue(errorCodes.contains("NameAddressValid.person"));
    assertTrue(errorCodes.contains("NameAddressValid"));
}
Example 15
Project: spring-rest-exception-handler-master  File: MethodArgumentNotValidExceptionHandler.java View source code
@Override
public ValidationErrorMessage createBody(MethodArgumentNotValidException ex, HttpServletRequest req) {
    ErrorMessage tmpl = super.createBody(ex, req);
    ValidationErrorMessage msg = new ValidationErrorMessage(tmpl);
    BindingResult result = ex.getBindingResult();
    for (ObjectError err : result.getGlobalErrors()) {
        msg.addError(err.getDefaultMessage());
    }
    for (FieldError err : result.getFieldErrors()) {
        msg.addError(err.getField(), err.getRejectedValue(), err.getDefaultMessage());
    }
    return msg;
}
Example 16
Project: taxii-log-adapter-master  File: BindExceptionHandler.java View source code
@Override
public void handle(BindException e) {
    for (ObjectError error : e.getAllErrors()) {
        StringBuilder b = new StringBuilder().append("Error in application.yml").append(", section ").append(error.getObjectName());
        if (error instanceof FieldError) {
            FieldError fieldError = (FieldError) error;
            b.append(", ").append(fieldError.getField()).append(" has illegal value ").append(fieldError.getRejectedValue());
        }
        err.println(b.toString());
    }
}
Example 17
Project: terasoluna-batch-master  File: ValidationUtil.java View source code
/**
     * Errors�らObjectError�リストを�得�る
     * @param errors Errors
     * @return List<ObjectError>
     */
public static List<ObjectError> getObjectErrorList(Errors errors) {
    List<ObjectError> resultList = new ArrayList<ObjectError>();
    List<?> errs = errors.getAllErrors();
    for (Object errObj : errs) {
        if (errObj instanceof ObjectError) {
            ObjectError oe = (ObjectError) errObj;
            resultList.add(oe);
        }
    }
    return resultList;
}
Example 18
Project: toobs-master  File: ValidationException.java View source code
public String getMessage() {
    StringBuffer sb = new StringBuffer();
    if (this.errors != null) {
        Iterator errIter = errors.iterator();
        while (errIter.hasNext()) {
            Errors err = (Errors) errIter.next();
            sb.append("Validation error for object " + err.getObjectName() + "\n");
            for (int i = 0; i < err.getAllErrors().size(); i++) {
                ObjectError objErr = (ObjectError) err.getAllErrors().get(i);
                sb.append(objErr.getDefaultMessage() + "\n");
            }
        }
    }
    return sb.toString();
}
Example 19
Project: hospitalcore-master  File: DiagnosisImporterController.java View source code
@RequestMapping(method = RequestMethod.POST)
public String create(UploadFile uploadFile, BindingResult result, Model model) {
    if (result.hasErrors()) {
        for (ObjectError obj : result.getAllErrors()) {
            ObjectError error = (ObjectError) obj;
            System.err.println("Error: " + error.toString());
        }
        return "/module/hospitalcore/concept/uploadForm";
    }
    System.out.println("Begin importing");
    Integer diagnosisNo = 0;
    try {
        HospitalCoreService hcs = (HospitalCoreService) Context.getService(HospitalCoreService.class);
        diagnosisNo = hcs.importConcepts(uploadFile.getDiagnosisFile().getInputStream(), uploadFile.getMappingFile().getInputStream(), uploadFile.getSynonymFile().getInputStream());
        model.addAttribute("diagnosisNo", diagnosisNo);
        System.out.println("Diagnosis imported " + diagnosisNo);
    } catch (Exception e) {
        e.printStackTrace();
        model.addAttribute("fail", true);
        model.addAttribute("error", e.toString());
    }
    return "/module/hospitalcore/concept/uploadForm";
}
Example 20
Project: jcommune-master  File: AdministrationControllerTest.java View source code
@Test
public void invalidForumInformationShouldProduceFailResponse() {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(new Object(), "");
    bindingResult.addError(new ObjectError("name", "message"));
    JsonResponse response = administrationController.setForumInformation(new ComponentInformation(), bindingResult, Locale.UK);
    assertEquals(response.getStatus(), JsonResponseStatus.FAIL);
}
Example 21
Project: jTalk-master  File: AdministrationControllerTest.java View source code
@Test
public void invalidForumInformationShouldProduceFailResponse() {
    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(new Object(), "");
    bindingResult.addError(new ObjectError("name", "message"));
    JsonResponse response = administrationController.setForumInformation(new ComponentInformation(), bindingResult, Locale.UK);
    assertEquals(response.getStatus(), JsonResponseStatus.FAIL);
}
Example 22
Project: onboard-master  File: TrialSignupController.java View source code
@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
public Boolean signUp(@ModelAttribute(NEW_COMMAND) @Valid RegistrationForm form, BindingResult result) {
    if (result.hasErrors()) {
        for (ObjectError error : result.getAllErrors()) {
            logger.warn("this is a hack request: {}", error);
        }
        return false;
    }
    CompanyApplication application = companyApplicationService.getCompanyApplicationByToken(form.getTrialToken());
    if (application == null) {
        return false;
    }
    userService.signUp(form, form.getCompanyName());
    companyApplicationService.disableCompanyApplicationToken(application.getId());
    User user = userService.getUserByEmail(form.getEmail());
    session.setCurrentUser(user);
    int companyId = companyService.getCompaniesByUserId(user.getId()).get(0).getId();
    sampleProjectService.createSampleProjectByCompanyId(companyId, user);
    return true;
}
Example 23
Project: OpenESPI-DataCustodian-java-master  File: UploadControllerTests.java View source code
@Test
@Ignore
public void uploadPost_givenInvalidFile_displaysUploadViewWithErrors() throws Exception {
    Mockito.doThrow(new SAXException("Unable to process file")).when(importService).importData(any(InputStream.class), null);
    String view = controller.uploadPost(form, result);
    assertEquals("/custodian/upload", view);
    verify(result).addError(new ObjectError("uploadForm", "Unable to process file"));
}
Example 24
Project: openmrs_gsoc-master  File: ShortPatientFormController.java View source code
/**
	 * Handles the form submission by validating the form fields and saving it
	 * to the DB
	 * 
	 * @param request
	 *            the webRequest object
	 * @param patientModel
	 *            the modelObject containing the patient info collected from the
	 *            form fields
	 * @param result
	 * @param status
	 * @return the view to forward to
	 * @should pass if all the form data is valid
	 * @should create a new patient
	 * @should send the user back to the form in case of validation errors
	 * @should void a name and replace it with a new one if it is changed to a
	 *         unique value
	 * @should void an address and replace it with a new one if it is changed to
	 *         a unique value
	 * @should add a new name if the person had no names
	 * @should add a new address if the person had none
	 * @should ignore a new address that was added and voided at same time
	 * @should set the cause of death as none a coded concept
	 * @should set the cause of death as a none coded concept
	 * @should void the cause of death obs that is none coded
	 */
@RequestMapping(method = RequestMethod.POST, value = SHORT_PATIENT_FORM_URL)
public String saveShortPatient(WebRequest request, @ModelAttribute("personNameCache") PersonName personNameCache, @ModelAttribute("personAddressCache") PersonAddress personAddressCache, @ModelAttribute("patientModel") ShortPatientModel patientModel, BindingResult result) {
    if (Context.isAuthenticated()) {
        // First do form validation so that we can easily bind errors to
        // fields
        new ShortPatientFormValidator().validate(patientModel, result);
        if (result.hasErrors())
            return SHORT_PATIENT_FORM_URL;
        Patient patient = null;
        patient = getPatientFromFormData(patientModel);
        Errors patientErrors = new BindException(patient, "patient");
        patientValidator.validate(patient, patientErrors);
        if (patientErrors.hasErrors()) {
            // Patient in ShortPatientModel
            for (ObjectError error : patientErrors.getAllErrors()) result.reject(error.getCode(), error.getArguments(), "Validation errors found");
            return SHORT_PATIENT_FORM_URL;
        }
        // check if name/address were edited, void them and replace them
        boolean foundChanges = hasPersonNameOrAddressChanged(patient, personNameCache, personAddressCache);
        try {
            patient = Context.getPatientService().savePatient(patient);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, Context.getMessageSourceService().getMessage("Patient.saved"), WebRequest.SCOPE_SESSION);
            // TODO do we really still need this, besides ensuring that the
            // cause of death is provided?
            // process and save the death info
            saveDeathInfo(patientModel, request);
            if (!patient.getVoided()) {
                // save the relationships to the database
                Map<String, Relationship> relationships = getRelationshipsMap(patientModel, request);
                for (Relationship relationship : relationships.values()) {
                    // it
                    if (relationship.getPersonA() != null && relationship.getPersonB() != null)
                        Context.getPersonService().saveRelationship(relationship);
                }
            }
        } catch (APIException e) {
            log.error("Error occurred while attempting to save patient", e);
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, Context.getMessageSourceService().getMessage("Patient.save.error"), WebRequest.SCOPE_SESSION);
            if (!foundChanges)
                return SHORT_PATIENT_FORM_URL;
        }
        return "redirect:" + PATIENT_DASHBOARD_URL + "?patientId=" + patient.getPatientId();
    }
    return FIND_PATIENT_PAGE;
}
Example 25
Project: Openmrs_old-master  File: ShortPatientFormController.java View source code
/**
	 * Handles the form submission by validating the form fields and saving it to the DB
	 * 
	 * @param request the webRequest object
	 * @param patientModel the modelObject containing the patient info collected from the form
	 *            fields
	 * @param result
	 * @param status
	 * @return the view to forward to
	 * @should pass if all the form data is valid
	 * @should create a new patient
	 * @should send the user back to the form in case of validation errors
	 * @should void a name and replace it with a new one if it is changed to a unique value
	 * @should void an address and replace it with a new one if it is changed to a unique value
	 * @should add a new name if the person had no names
	 * @should add a new address if the person had none
	 * @should ignore a new address that was added and voided at same time
	 */
@RequestMapping(method = RequestMethod.POST, value = SHORT_PATIENT_FORM_URL)
public String saveShortPatient(WebRequest request, @ModelAttribute("personNameCache") PersonName personNameCache, @ModelAttribute("personAddressCache") PersonAddress personAddressCache, @ModelAttribute("patientModel") ShortPatientModel patientModel, BindingResult result, SessionStatus status) {
    if (Context.isAuthenticated()) {
        // First do form validation so that we can easily bind errors to
        // fields
        new ShortPatientFormValidator().validate(patientModel, result);
        if (result.hasErrors())
            return SHORT_PATIENT_FORM_URL;
        Patient patient = null;
        patient = getPatientFromFormData(patientModel);
        Errors patientErrors = new BindException(patient, "patient");
        patientValidator.validate(patient, patientErrors);
        if (patientErrors.hasErrors()) {
            //so that spring doesn't try to look for getters/setters for Patient in ShortPatientModel
            for (ObjectError error : patientErrors.getAllErrors()) result.reject(error.getCode(), error.getArguments(), "Validation errors found");
            return SHORT_PATIENT_FORM_URL;
        }
        //check if name/address were edited, void them and replace them
        boolean foundChanges = hasPersonNameOrAddressChanged(patient, personNameCache, personAddressCache);
        try {
            patient = Context.getPatientService().savePatient(patient);
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, Context.getMessageSourceService().getMessage("Patient.saved"), WebRequest.SCOPE_SESSION);
            // TODO do we really still need this, besides ensuring that the
            // cause of death is provided?
            // process and save the death info
            saveDeathInfo(patientModel, request);
            if (!patient.getVoided()) {
                // save the relationships to the database
                Map<String, Relationship> relationships = getRelationshipsMap(patient, request);
                for (Relationship relationship : relationships.values()) {
                    // if the user added a person to this relationship, save it
                    if (relationship.getPersonA() != null && relationship.getPersonB() != null)
                        Context.getPersonService().saveRelationship(relationship);
                }
            }
        } catch (APIException e) {
            log.error("Error occurred while attempting to save patient", e);
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, Context.getMessageSourceService().getMessage("Patient.save.error"), WebRequest.SCOPE_SESSION);
            if (foundChanges) {
                status.setComplete();
                return "redirect:" + PATIENT_DASHBOARD_URL + "?patientId=" + patient.getPatientId();
            }
            return SHORT_PATIENT_FORM_URL;
        }
        // clear the session attributes
        status.setComplete();
        return "redirect:" + PATIENT_DASHBOARD_URL + "?patientId=" + patient.getPatientId();
    }
    return FIND_PATIENT_PAGE;
}
Example 26
Project: quadriga-master  File: AccountApprovalController.java View source code
@RequestMapping(value = "auth/users/access/handleRequest", method = RequestMethod.POST)
public String handleApprovalRequest(Model model, @Validated @ModelAttribute("approveAccount") ApproveAccount approveAccount, BindingResult result, Locale locale, RedirectAttributes attr, Principal principal) throws QuadrigaStorageException, QuadrigaNotificationException {
    if (result.hasErrors()) {
        StringBuffer errors = new StringBuffer();
        for (ObjectError error : result.getAllErrors()) {
            errors.append(messageSource.getMessage(error, locale) + "<br>");
        }
        attr.addFlashAttribute("show_error_alert", true);
        attr.addFlashAttribute("error_alert_msg", errors.toString());
        return "redirect:/auth/users/manage";
    }
    if (approveAccount.getAction().equalsIgnoreCase("approve")) {
        //User Request has been approved by the admin
        StringBuilder sRoles = new StringBuilder();
        String[] roles = approveAccount.getRoles();
        for (int i = 0; i < roles.length; i++) {
            if (i == 0) {
                sRoles.append(roles[i]);
            } else {
                sRoles.append(",");
                sRoles.append(roles[i]);
            }
        }
        usermanager.approveUserRequest(approveAccount.getUsername(), sRoles.toString(), principal.getName());
    } else {
        //User Request denied by the admin
        usermanager.denyUserRequest(approveAccount.getUsername(), principal.getName());
    }
    return "redirect:/auth/users/manage";
}
Example 27
Project: spring-modules-master  File: DefaultValidationHandler.java View source code
/*** Class internals ***/
private void removeOldErrors(AjaxSubmitEvent event, AjaxResponseImpl response) {
    HttpServletRequest request = event.getHttpRequest();
    ErrorsContainer errorsContainer = (ErrorsContainer) request.getSession(true).getAttribute(this.getErrorsAttributeName(request));
    if (errorsContainer != null) {
        logger.debug("Found errors for URL: " + request.getRequestURL().toString());
        logger.debug("Removing old errors.");
        // Remove old errors from session:
        request.getSession(true).removeAttribute(this.getErrorsAttributeName(request));
        // Remove old errors from HTML:
        ObjectError[] errors = errorsContainer.getErrors();
        for (ObjectError error : errors) {
            if (this.rendersError(error)) {
                ElementMatcher matcher = this.getElementMatcherForError(error);
                RemoveContentAction removeAction = new RemoveContentAction(matcher);
                response.addAction(removeAction);
            }
        }
    }
}
Example 28
Project: spring-security-master  File: MessageJsonController.java View source code
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<?> create(@Valid @RequestBody Message message, BindingResult result, RedirectAttributes redirect) {
    if (result.hasErrors()) {
        List<String> errors = new ArrayList<String>(result.getErrorCount());
        for (ObjectError r : result.getAllErrors()) {
            errors.add(r.getDefaultMessage());
        }
        return new ResponseEntity<List<String>>(errors, HttpStatus.BAD_REQUEST);
    }
    message = messageRepository.save(message);
    return new ResponseEntity<Message>(message, HttpStatus.OK);
}
Example 29
Project: dungproxy-master  File: RestApiResponseEntityExceptionHandler.java View source code
protected ResponseEntity<Object> handleBeanValidationException(BeanValidationException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    RestApiError restApiError = new RestApiError();
    restApiError.setStatusCode(ex.getErrorCode());
    ValidationError validationError = new ValidationError();
    Errors errors = ex.getErrors();
    if (errors.hasGlobalErrors()) {
        Map<String, String> globalErrors = new HashMap<String, String>();
        List<ObjectError> objectErrorList = errors.getGlobalErrors();
        for (ObjectError objectError : objectErrorList) {
            globalErrors.put(objectError.getObjectName(), objectError.getDefaultMessage());
        }
        validationError.setGlobalErrors(globalErrors);
    }
    if (errors.hasFieldErrors()) {
        Map<String, String> fieldErrors = new HashMap<String, String>();
        List<FieldError> fieldErroList = errors.getFieldErrors();
        for (FieldError fieldError : fieldErroList) {
            fieldErrors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        validationError.setFieldErrors(fieldErrors);
    }
    restApiError.setValidationError(validationError);
    ResponseEnvelope<Object> envelope = new ResponseEnvelope<Object>(restApiError, false);
    return handleExceptionInternal(ex, envelope, headers, status, request);
}
Example 30
Project: graniteds-master  File: SpringValidationExceptionConverter.java View source code
public static org.granite.tide.validators.InvalidValue[] convertErrors(Errors errors) {
    Object bean = null;
    GraniteContext context = GraniteContext.getCurrentInstance();
    ServletContext sc = ((HttpGraniteContext) context).getServletContext();
    ApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sc);
    BindingResult bindingResult = null;
    if (errors instanceof BindingResult) {
        bindingResult = (BindingResult) errors;
        bean = bindingResult.getTarget();
    }
    org.granite.tide.validators.InvalidValue[] converted = new org.granite.tide.validators.InvalidValue[errors.getErrorCount()];
    List<? extends ObjectError> allErrors = errors.getAllErrors();
    int i = 0;
    for (ObjectError error : allErrors) {
        if (error instanceof FieldError) {
            FieldError ferror = (FieldError) error;
            converted[i++] = new org.granite.tide.validators.InvalidValue(bean != null ? bean : ferror.getObjectName(), ferror.getField(), ferror.getRejectedValue(), springContext.getMessage(ferror, Locale.FRENCH));
        } else {
            converted[i++] = new org.granite.tide.validators.InvalidValue(bean != null ? bean : error.getObjectName(), null, null, springContext.getMessage(error, Locale.FRENCH));
        }
    }
    return converted;
}
Example 31
Project: hdiv-master  File: EditableParameterValidatorTest.java View source code
public void testEditableValidator() {
    MockHttpServletRequest request = getMockRequest();
    request.setMethod("POST");
    dataComposer.beginRequest(Method.POST, targetName);
    dataComposer.compose("paramName", "", true, "text");
    String pageState = dataComposer.endRequest();
    dataComposer.endPage();
    request.addParameter(hdivParameter, pageState);
    request.addParameter("paramName", "<script>storeCookie()</script>");
    RequestContext context = new RequestContext(request, getMockResponse());
    context.setHdivParameterName(hdivParameter);
    HttpServletRequest requestWrapper = new RequestWrapper(context);
    ValidatorHelperResult result = helper.validate(new ValidationContextImpl(context, helper, false));
    assertFalse(result.isValid());
    // Editable errors in request?
    List<ValidatorError> validationErrors = result.getErrors();
    requestWrapper.setAttribute(Constants.EDITABLE_PARAMETER_ERROR, validationErrors);
    assertEquals(1, validationErrors.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());
    ObjectError err = errors.getAllErrors().get(0);
    assertEquals("<script>storeCookie(... has not allowed characters", err.getDefaultMessage());
    assertEquals("hdiv.editable.error", err.getCode());
}
Example 32
Project: openmrs-master  File: ChangePasswordFormControllerTest.java View source code
/**
	 * @see {@link ChangePasswordFormController#formBackingObject()} 
	 */
@Test
@Verifies(value = "remain on the changePasswordForm page if there are errors", method = "formBackingObject()")
public void formBackingObject_shouldRemainOnChangePasswordFormPageIfThereAreErrors() throws Exception {
    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");
    errors.addError(new ObjectError("Test", "Test Error"));
    String result = controller.handleSubmission(new MockHttpSession(), "password", "differentPassword", "", "", "", Context.getAuthenticatedUser(), errors);
    assertEquals("/admin/users/changePasswordForm", result);
}
Example 33
Project: openmrs-maven-master  File: MergePatientsFormController.java View source code
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws Exception {
    //ModelAndView view = super.processFormSubmission(request, response, object, errors);
    log.debug("Number of errors: " + errors.getErrorCount());
    for (Object o : errors.getAllErrors()) {
        ObjectError e = (ObjectError) o;
        log.debug("Error name: " + e.getObjectName());
        log.debug("Error code: " + e.getCode());
        log.debug("Error message: " + e.getDefaultMessage());
        log.debug("Error args: " + e.getArguments());
        log.debug("Error codes: " + e.getCodes());
    }
    // super.processFormSubmission()
    return onSubmit(request, response, object, errors);
}
Example 34
Project: openmrs-module-webservices.rest-master  File: RestUtil.java View source code
public static SimpleObject wrapValidationErrorResponse(ValidationException ex) {
    MessageSourceService messageSourceService = Context.getMessageSourceService();
    SimpleObject errors = new SimpleObject();
    errors.add("message", messageSourceService.getMessage("webservices.rest.error.invalid.submission"));
    errors.add("code", "webservices.rest.error.invalid.submission");
    List<SimpleObject> globalErrors = new ArrayList<SimpleObject>();
    SimpleObject fieldErrors = new SimpleObject();
    if (ex.getErrors().hasGlobalErrors()) {
        for (Object errObj : ex.getErrors().getGlobalErrors()) {
            ObjectError err = (ObjectError) errObj;
            String message = messageSourceService.getMessage(err.getCode());
            SimpleObject globalError = new SimpleObject();
            globalError.put("code", err.getCode());
            globalError.put("message", message);
            globalErrors.add(globalError);
        }
    }
    if (ex.getErrors().hasFieldErrors()) {
        for (Object errObj : ex.getErrors().getFieldErrors()) {
            FieldError err = (FieldError) errObj;
            String message = messageSourceService.getMessage(err.getCode());
            SimpleObject fieldError = new SimpleObject();
            fieldError.put("code", err.getCode());
            fieldError.put("message", message);
            if (!fieldErrors.containsKey(err.getField())) {
                fieldErrors.put(err.getField(), new ArrayList<SimpleObject>());
            }
            ((List<SimpleObject>) fieldErrors.get(err.getField())).add(fieldError);
        }
    }
    errors.put("globalErrors", globalErrors);
    errors.put("fieldErrors", fieldErrors);
    return new SimpleObject().add("error", errors);
}
Example 35
Project: radiology-master  File: RadiologyModalityValidatorTest.java View source code
@Test
public void shouldFailValidationIfFieldLengthsAreNotCorrect() throws Exception {
    radiologyModality.setAeTitle(StringUtils.repeat("1", 17));
    radiologyModality.setName(StringUtils.repeat("1", 256));
    radiologyModality.setDescription(StringUtils.repeat("1", 256));
    radiologyModality.setRetireReason(StringUtils.repeat("1", 256));
    radiologyModalityValidator.validate(radiologyModality, errors);
    assertTrue(errors.hasErrors());
    ObjectError err = (errors.getAllErrors()).get(0);
    for (ObjectError error : errors.getAllErrors()) {
        assertThat(error.getCode(), is("error.exceededMaxLengthOfField"));
    }
    assertTrue(errors.hasFieldErrors("aeTitle"));
    assertTrue(errors.hasFieldErrors("name"));
    assertTrue(errors.hasFieldErrors("description"));
    assertTrue(errors.hasFieldErrors("retireReason"));
}
Example 36
Project: shept-master  File: FormCompletionInterceptor.java View source code
/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    // do not apply model attributes to redirections
    if (modelAndView == null || modelAndView.getView() instanceof RedirectView) {
        return;
    }
    RequestContext rc = new RequestContext(request);
    BindingResult res = null;
    for (String name : modelAndView.getModel().keySet()) {
        if (name.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
            res = BindingResultUtils.getBindingResult(modelAndView.getModel(), name.substring(BindingResult.MODEL_KEY_PREFIX.length()));
        }
    }
    HashMap<String, String> controlModel = new HashMap<String, String>();
    String errStr = "";
    if (res != null && res.hasErrors()) {
        // list errors
        @SuppressWarnings("rawtypes") List errList = res.getAllErrors();
        Iterator it = errList.iterator();
        if (it.hasNext()) {
            ObjectError error = (ObjectError) it.next();
            String myErrCode = error.getCode();
            // check all possible Errorcodes
            for (String eStr : error.getCodes()) {
                String errMsg = rc.getMessage(eStr, "");
                if (errMsg.length() > 0) {
                    myErrCode = eStr;
                    break;
                }
            }
            errStr = errStr + rc.getMessage(myErrCode, error.getArguments(), error.getDefaultMessage());
        // rc.getMessage(error.getCode(), error.rejectedValue,
        // error.getDefaultMessage());
        }
        if (it.hasNext()) {
            errStr = errStr + "  ...";
        }
    }
    controlModel.put(ERROR_MSG, errStr);
    modelAndView.addAllObjects(controlModel);
}
Example 37
Project: spring-batch-admin-master  File: ContentTypeInterceptor.java View source code
private void exposeErrors(ModelMap modelMap) {
    if (modelMap.containsAttribute("errors")) {
        return;
    }
    BindException errors = new BindException(new Object(), "target");
    boolean hasErrors = false;
    for (Object value : modelMap.values()) {
        if (value instanceof Errors) {
            for (ObjectError error : ((Errors) value).getGlobalErrors()) {
                errors.addError(error);
                hasErrors = true;
            }
        }
    }
    if (hasErrors) {
        modelMap.addAttribute("errors", errors);
    }
}
Example 38
Project: spring-boot-master  File: ResourceServerPropertiesTests.java View source code
@Override
public boolean matches(Object item) {
    BindException ex = (BindException) ((Exception) item).getCause();
    ObjectError error = ex.getAllErrors().get(0);
    boolean messageMatches = message.equals(error.getDefaultMessage());
    if (field == null) {
        return messageMatches;
    }
    String fieldErrors = ((FieldError) error).getField();
    return messageMatches && fieldErrors.equals(field);
}
Example 39
Project: spring-insight-plugins-master  File: ValidationOperationCollectionAspectTest.java View source code
private static OperationList assertValidationErrors(OperationList errDetails, Errors errors) {
    assertEquals("Mismatched number of errors", errors.getErrorCount(), errDetails.size());
    List<? extends ObjectError> errList = errors.getAllErrors();
    for (int index = 0; index < errList.size(); index++) {
        ObjectError expected = errList.get(index);
        OperationMap actual = errDetails.get(index, OperationMap.class);
        assertNotNull("Missing encoded value for error #" + index + ": " + expected, actual);
        String objName = actual.get(OperationUtils.NAME_KEY, String.class);
        assertEquals("Mismatched object name at entry #" + index, expected.getObjectName(), objName);
        String errExpected = StringUtil.chopTailAndEllipsify(expected.toString(), ValidationJoinPointFinalizer.MAX_ERROR_TEXT_LENGTH);
        String errActual = actual.get(OperationUtils.VALUE_KEY, String.class);
        assertEquals("Mismatched error text at entry #" + index, errExpected, errActual);
    }
    return errDetails;
}
Example 40
Project: XCoLab-master  File: UserProfileController.java View source code
@PostMapping("{memberId}/edit")
public String updateUserProfile(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable long memberId, @ModelAttribute UserBean updatedUserBean, BindingResult result, Member loggedInMember) throws IOException, MemberNotFoundException {
    UserProfilePermissions permissions = new UserProfilePermissions(loggedInMember);
    model.addAttribute("permissions", permissions);
    model.addAttribute("_activePageLink", "community");
    model.addAttribute("countrySelectItems", CountryUtil.getSelectOptions());
    if (!permissions.getCanEditMemberProfile(updatedUserBean.getUserId()) || memberId != updatedUserBean.getUserId()) {
        return ErrorText.NOT_FOUND.flashAndReturnView(request);
    }
    UserProfileWrapper currentUserProfile = new UserProfileWrapper(updatedUserBean.getUserId(), request);
    model.addAttribute("currentUserProfile", currentUserProfile);
    model.addAttribute("messageBean", new MessageBean());
    model.addAttribute("userBean", updatedUserBean);
    boolean changedUserPart = false;
    boolean validationError = false;
    if (StringUtils.isNotBlank(updatedUserBean.getPassword())) {
        final boolean isAdminEditingOtherProfile = permissions.getCanAdmin() && !currentUserProfile.isViewingOwnProfile();
        final String currentPassword = updatedUserBean.getCurrentPassword();
        if (MembersClient.validatePassword(currentPassword.trim(), currentUserProfile.getUser().getUserId()) || isAdminEditingOtherProfile) {
            validator.validate(updatedUserBean, result, UserBean.PasswordChanged.class);
            if (!result.hasErrors()) {
                final String newPassword = updatedUserBean.getPassword().trim();
                MembersClient.updatePassword(memberId, newPassword);
                changedUserPart = true;
            } else {
                validationError = true;
                return EDIT_PROFILE_VIEW;
            }
        } else {
            result.addError(new ObjectError("currentPassword", "Password change failed: Current password is incorrect."));
            validationError = true;
            return EDIT_PROFILE_VIEW;
        }
    }
    boolean eMailChanged = false;
    if (updatedUserBean.getEmail() != null && !updatedUserBean.getEmail().trim().isEmpty() && !updatedUserBean.getEmail().equals(currentUserProfile.getUserBean().getEmailStored())) {
        validator.validate(updatedUserBean, result, UserBean.EmailChanged.class);
        if (!result.hasErrors()) {
            currentUserProfile.getUser().setEmailAddress(updatedUserBean.getEmail());
            changedUserPart = true;
            eMailChanged = true;
        } else {
            validationError = true;
            return EDIT_PROFILE_VIEW;
        }
    }
    if (updatedUserBean.getFirstName() != null && !updatedUserBean.getFirstName().equals(currentUserProfile.getUserBean().getFirstName())) {
        validator.validate(updatedUserBean, result);
        if (!result.hasErrors()) {
            currentUserProfile.getUser().setFirstName(HtmlUtil.cleanAll(updatedUserBean.getFirstName()));
            changedUserPart = true;
        } else {
            validationError = true;
            _log.warn("First name change failed for userId: {}", currentUserProfile.getUser().getId_());
        }
    }
    if (updatedUserBean.getLastName() != null && !updatedUserBean.getLastName().equals(currentUserProfile.getUserBean().getLastName())) {
        validator.validate(updatedUserBean, result);
        if (!result.hasErrors()) {
            currentUserProfile.getUser().setLastName(HtmlUtil.cleanAll(updatedUserBean.getLastName()));
            changedUserPart = true;
        } else {
            validationError = true;
            _log.warn("Last name change failed for userId: {}", currentUserProfile.getUser().getId_());
        }
    }
    if (updatedUserBean.getCountryName() != null) {
        validator.validate(updatedUserBean, result);
        if (!result.hasErrors() && !updatedUserBean.getCountryName().isEmpty()) {
            currentUserProfile.getUser().setCountry(HtmlUtil.cleanAll(updatedUserBean.getCountryName()));
            changedUserPart = true;
        } else {
            validationError = true;
            _log.warn("Country name change failed for userId: {}", currentUserProfile.getUser().getId_());
        }
    }
    changedUserPart = changedUserPart | updateUserProfile(currentUserProfile, updatedUserBean);
    if (validationError) {
        updatedUserBean.setImageId(currentUserProfile.getUserBean().getImageId());
        return EDIT_PROFILE_VIEW;
    } else if (changedUserPart) {
        updatedUserBean.setImageId(currentUserProfile.getUser().getPortraitFileEntryId());
        MembersClient.updateMember(currentUserProfile.getUser());
        if (eMailChanged) {
            updatedUserBean.setEmailStored(updatedUserBean.getEmail());
            sendUpdatedEmail(currentUserProfile.getUser());
        }
        AlertMessage.CHANGES_SAVED.flash(request);
        return EDIT_PROFILE_VIEW;
    } else {
        response.sendRedirect("/web/guest/member/-/member/userId/" + memberId);
        return EDIT_PROFILE_VIEW;
    }
}
Example 41
Project: appfuse-master  File: FileUploadController.java View source code
@RequestMapping(method = RequestMethod.POST)
public void onSubmit(@ModelAttribute FileUpload fileUpload, BindingResult errors, HttpServletRequest request, HttpServletResponse response) throws Exception {
    JSONObject jsonObject = new JSONObject();
    if (StringUtils.isBlank(fileUpload.getName())) {
        Object[] args = new Object[] { messages.getMessage("uploadForm.name", request.getLocale()) };
        errors.rejectValue("name", "errors.required", args, "Name");
    }
    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
        Object[] args = new Object[] { messages.getMessage("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");
    }
    if (errors.hasErrors()) {
        List<String> errorMessages = new ArrayList<String>();
        for (ObjectError error : errors.getAllErrors()) {
            errorMessages.add(messages.getMessage(error));
        }
        jsonObject.put("errorMessages", errorMessages);
        sendResponse(response, jsonObject);
        return;
    }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
    // the directory to upload to
    String uploadDir = servletContext.getRealPath("/resources") + "/" + request.getRemoteUser() + "/";
    // Create the directory if it doesn't exist
    File dirPath = new File(uploadDir);
    if (!dirPath.exists()) {
        dirPath.mkdirs();
    }
    // retrieve the file data
    InputStream stream = file.getInputStream();
    // write the file to the file specified
    OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename());
    int bytesRead;
    byte[] buffer = new byte[8192];
    while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
        bos.write(buffer, 0, bytesRead);
    }
    bos.close();
    // close the stream
    stream.close();
    // place the data into the request for retrieval on next page
    jsonObject.put("name", fileUpload.getName());
    jsonObject.put("fileName", file.getOriginalFilename());
    jsonObject.put("contentType", file.getContentType());
    jsonObject.put("size", file.getSize() + " bytes");
    jsonObject.put("location", dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename());
    String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/";
    jsonObject.put("link", link + file.getOriginalFilename());
    sendResponse(response, jsonObject);
}
Example 42
Project: Fudan-Sakai-master  File: XsltArtifactView.java View source code
protected Source createXsltSource(Map map, String string, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    httpServletResponse.setContentType(getContentType());
    WebApplicationContext context = getWebApplicationContext();
    setUriResolver((URIResolver) context.getBean(uriResolverBeanName));
    ToolSession toolSession = SessionManager.getCurrentToolSession();
    String homeType = null;
    ElementBean bean = (ElementBean) map.get("bean");
    Element root = null;
    Map paramsMap = new Hashtable();
    for (Enumeration e = httpServletRequest.getParameterNames(); e.hasMoreElements(); ) {
        String k = e.nextElement().toString();
        // Do not allow reserved parameter names to be overwritten
        if (!reservedParams.contains(k)) {
            paramsMap.put(k, httpServletRequest.getParameter(k));
        }
    }
    httpServletRequest.setAttribute(STYLESHEET_PARAMS, paramsMap);
    if (toolSession.getAttribute(FormHelper.PREVIEW_HOME_TAG) != null) {
        paramsMap.put("preview", "true");
    }
    if (toolSession.getAttribute(ResourceToolAction.ACTION_PIPE) != null) {
        paramsMap.put("fromResources", "true");
    }
    if (httpServletRequest.getAttribute(FormHelper.URL_DECORATION) != null) {
        paramsMap.put("urlDecoration", httpServletRequest.getAttribute(FormHelper.URL_DECORATION));
    }
    HashMap<String, String> xslParams = new HashMap<String, String>();
    xslParams.put(FormHelper.XSL_PRESENTATION_ID, FormHelper.PRESENTATION_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_TYPE, FormHelper.PRESENTATION_TEMPLATE_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_ID, FormHelper.PRESENTATION_ITEM_DEF_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_NAME, FormHelper.PRESENTATION_ITEM_DEF_NAME);
    xslParams.put(FormHelper.XSL_FORM_TYPE, ResourceEditingHelper.CREATE_SUB_TYPE);
    xslParams.put(FormHelper.XSL_ARTIFACT_REFERENCE, ResourceEditingHelper.ATTACHMENT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_ID, FormHelper.XSL_OBJECT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_TITLE, FormHelper.XSL_OBJECT_TITLE);
    xslParams.put(FormHelper.XSL_WIZARD_PAGE_ID, FormHelper.XSL_WIZARD_PAGE_ID);
    // Note that this is not always one-to-one due to some string/key inconsistencies around the tools.
    for (Entry<String, String> item : xslParams.entrySet()) {
        Object val = toolSession.getAttribute(item.getValue());
        if (val != null) {
            paramsMap.put(item.getKey(), val);
        }
    }
    boolean edit = false;
    if (bean instanceof Artifact) {
        root = getStructuredArtifactDefinitionManager().createFormViewXml((Artifact) bean, null);
        homeType = getHomeType((Artifact) bean);
        edit = ((Artifact) bean).getId() != null;
    } else {
        EditedArtifactStorage sessionBean = (EditedArtifactStorage) httpServletRequest.getSession().getAttribute(EditedArtifactStorage.EDITED_ARTIFACT_STORAGE_SESSION_KEY);
        if (sessionBean != null) {
            root = getStructuredArtifactDefinitionManager().createFormViewXml((Artifact) sessionBean.getRootArtifact(), null);
            replaceNodes(root, bean, sessionBean);
            paramsMap.put("subForm", "true");
            homeType = getHomeType(sessionBean.getRootArtifact());
            edit = sessionBean.getRootArtifact().getId() != null;
        } else {
            return new javax.xml.transform.dom.DOMSource();
        }
    }
    if (edit) {
        paramsMap.put("edit", "true");
        paramsMap.put(FormHelper.XSL_ARTIFACT_ID, ((Artifact) bean).getId().getValue());
    }
    httpServletRequest.setAttribute(STYLESHEET_LOCATION, getStructuredArtifactDefinitionManager().getTransformer(homeType, readOnly));
    Errors errors = BindingResultUtils.getBindingResult(map, "bean");
    if (errors != null && errors.hasErrors()) {
        Element errorsElement = new Element("errors");
        List errorsList = errors.getAllErrors();
        for (Iterator i = errorsList.iterator(); i.hasNext(); ) {
            Element errorElement = new Element("error");
            ObjectError error = (ObjectError) i.next();
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                errorElement.setAttribute("field", fieldError.getField());
                Element rejectedValue = new Element("rejectedValue");
                if (fieldError.getRejectedValue() != null) {
                    rejectedValue.addContent(fieldError.getRejectedValue().toString());
                }
                errorElement.addContent(rejectedValue);
            }
            Element message = new Element("message");
            message.addContent(context.getMessage(error, getResourceLoader().getLocale()));
            errorElement.addContent(message);
            errorsElement.addContent(errorElement);
        }
        root.addContent(errorsElement);
    }
    if (httpServletRequest.getParameter("success") != null) {
        Element success = new Element("success");
        success.setAttribute("messageKey", httpServletRequest.getParameter("success"));
        root.addContent(success);
    }
    if (toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS) != null) {
        Element uri = new Element("uri");
        uri.setText((String) toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS));
        root.getChild("css").addContent(uri);
        uri.setAttribute("order", "100");
    }
    if (toolSession.getAttribute(FormHelper.FORM_STYLES) != null) {
        List styles = (List) toolSession.getAttribute(FormHelper.FORM_STYLES);
        int index = 101;
        for (Iterator<String> i = styles.iterator(); i.hasNext(); ) {
            Element uri = new Element("uri");
            uri.setText(i.next());
            root.getChild("css").addContent(uri);
            uri.setAttribute("order", "" + index);
            index++;
        }
    }
    Document doc = new Document(root);
    return new JDOMSource(doc);
}
Example 43
Project: openmrs-core-master  File: ValidateUtil.java View source code
/**
	 * Test the given object against all validators that are registered as compatible with the
	 * object class
	 *
	 * @param obj the object to validate
	 * @throws ValidationException thrown if a binding exception occurs
	 * @should throw APIException if errors occur during validation
	 * @should return immediately if validation is disabled
	 */
public static void validate(Object obj) throws ValidationException {
    if (disableValidation) {
        return;
    }
    Errors errors = new BindException(obj, "");
    Context.getAdministrationService().validate(obj, errors);
    if (errors.hasErrors()) {
        Set<String> uniqueErrorMessages = new LinkedHashSet<>();
        for (Object objerr : errors.getAllErrors()) {
            ObjectError error = (ObjectError) objerr;
            String message = Context.getMessageSourceService().getMessage(error.getCode());
            if (error instanceof FieldError) {
                message = ((FieldError) error).getField() + ": " + message;
            }
            uniqueErrorMessages.add(message);
        }
        String exceptionMessage = "'" + obj + "' failed to validate with reason: ";
        exceptionMessage += StringUtils.join(uniqueErrorMessages, ", ");
        throw new ValidationException(exceptionMessage, errors);
    }
}
Example 44
Project: podcastpedia-master  File: InsertController.java View source code
@RequestMapping(value = "upload_file", method = RequestMethod.POST)
public String create(@ModelAttribute("uploadItem") UploadFileForm uploadItem, BindingResult result) throws UnsupportedEncodingException, IOException {
    if (result.hasErrors()) {
        for (ObjectError error : result.getAllErrors()) {
            LOG.error("Error: " + error.getCode() + " - " + error.getDefaultMessage());
        }
    } else {
        // build logic here to parse
        MultipartFile file = uploadItem.getFileData();
        BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
        String strLine = null;
        // # starts a comments line, like in properties files
        while ((strLine = in.readLine()) != null) {
            if (strLine.trim().startsWith("#") || strLine.trim().isEmpty()) {
                // behaviour for empty lines
                continue;
            } else {
                LOG.debug("Parsing line : " + strLine);
                try {
                    ProposedPodcast proposedPodcast = insertService.getPodcastFromStringLine(strLine);
                    Podcast podcast = proposedPodcast.getPodcast();
                    String suggestedFeedUrl = podcast.getUrl();
                    Podcast podcastForUrl = readService.getPodcastAttributesByFeedUrl(suggestedFeedUrl);
                    if (podcastForUrl == null) {
                        // it means the podcast is not in the database
                        insertService.addPodcast(podcast);
                        notifySubmitterAndPostOnTwitterAboutNewInsertion(proposedPodcast);
                    } else {
                        LOG.warn("EXISTING url " + podcastForUrl.getUrl() + " with podcastId " + podcastForUrl.getPodcastId().toString());
                    }
                } catch (Exception e) {
                    LOG.error("**** ERROR ***** line " + strLine + " ", e);
                    continue;
                }
            }
        }
    }
    restClient.invokeRefreshNewestAndRecommendedPodcasts();
    restClient.invokeRefreshReferenceData();
    restClient.invokeFlushSearchResultsCache();
    return "redirect:/admin";
}
Example 45
Project: sakai-cle-master  File: XsltArtifactView.java View source code
protected Source createXsltSource(Map map, String string, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    httpServletResponse.setContentType(getContentType());
    WebApplicationContext context = getWebApplicationContext();
    setUriResolver((URIResolver) context.getBean(uriResolverBeanName));
    ToolSession toolSession = SessionManager.getCurrentToolSession();
    String homeType = null;
    ElementBean bean = (ElementBean) map.get("bean");
    Element root = null;
    Map paramsMap = new Hashtable();
    for (Enumeration e = httpServletRequest.getParameterNames(); e.hasMoreElements(); ) {
        String k = e.nextElement().toString();
        // Do not allow reserved parameter names to be overwritten
        if (!reservedParams.contains(k)) {
            paramsMap.put(k, httpServletRequest.getParameter(k));
        }
    }
    httpServletRequest.setAttribute(STYLESHEET_PARAMS, paramsMap);
    if (toolSession.getAttribute(FormHelper.PREVIEW_HOME_TAG) != null) {
        paramsMap.put("preview", "true");
    }
    if (toolSession.getAttribute(ResourceToolAction.ACTION_PIPE) != null) {
        paramsMap.put("fromResources", "true");
    }
    if (httpServletRequest.getAttribute(FormHelper.URL_DECORATION) != null) {
        paramsMap.put("urlDecoration", httpServletRequest.getAttribute(FormHelper.URL_DECORATION));
    }
    HashMap<String, String> xslParams = new HashMap<String, String>();
    xslParams.put(FormHelper.XSL_PRESENTATION_ID, FormHelper.PRESENTATION_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_TYPE, FormHelper.PRESENTATION_TEMPLATE_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_ID, FormHelper.PRESENTATION_ITEM_DEF_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_NAME, FormHelper.PRESENTATION_ITEM_DEF_NAME);
    xslParams.put(FormHelper.XSL_FORM_TYPE, ResourceEditingHelper.CREATE_SUB_TYPE);
    xslParams.put(FormHelper.XSL_ARTIFACT_REFERENCE, ResourceEditingHelper.ATTACHMENT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_ID, FormHelper.XSL_OBJECT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_TITLE, FormHelper.XSL_OBJECT_TITLE);
    xslParams.put(FormHelper.XSL_WIZARD_PAGE_ID, FormHelper.XSL_WIZARD_PAGE_ID);
    // Note that this is not always one-to-one due to some string/key inconsistencies around the tools.
    for (Entry<String, String> item : xslParams.entrySet()) {
        Object val = toolSession.getAttribute(item.getValue());
        if (val != null) {
            paramsMap.put(item.getKey(), val);
        }
    }
    Id id = null;
    if (bean instanceof Artifact) {
        root = getStructuredArtifactDefinitionManager().createFormViewXml((Artifact) bean, null);
        homeType = getHomeType((Artifact) bean);
        id = ((Artifact) bean).getId();
    } else {
        EditedArtifactStorage sessionBean = (EditedArtifactStorage) httpServletRequest.getSession().getAttribute(EditedArtifactStorage.EDITED_ARTIFACT_STORAGE_SESSION_KEY);
        if (sessionBean != null) {
            root = getStructuredArtifactDefinitionManager().createFormViewXml((Artifact) sessionBean.getRootArtifact(), null);
            replaceNodes(root, bean, sessionBean);
            paramsMap.put("subForm", "true");
            homeType = getHomeType(sessionBean.getRootArtifact());
            id = sessionBean.getRootArtifact().getId();
        } else {
            return new javax.xml.transform.dom.DOMSource();
        }
    }
    if (id != null) {
        paramsMap.put("edit", "true");
        paramsMap.put(FormHelper.XSL_ARTIFACT_ID, id.getValue());
    }
    httpServletRequest.setAttribute(STYLESHEET_LOCATION, getStructuredArtifactDefinitionManager().getTransformer(homeType, readOnly));
    Errors errors = BindingResultUtils.getBindingResult(map, "bean");
    if (errors != null && errors.hasErrors()) {
        Element errorsElement = new Element("errors");
        List errorsList = errors.getAllErrors();
        for (Iterator i = errorsList.iterator(); i.hasNext(); ) {
            Element errorElement = new Element("error");
            ObjectError error = (ObjectError) i.next();
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                errorElement.setAttribute("field", fieldError.getField());
                Element rejectedValue = new Element("rejectedValue");
                if (fieldError.getRejectedValue() != null) {
                    rejectedValue.addContent(fieldError.getRejectedValue().toString());
                }
                errorElement.addContent(rejectedValue);
            }
            Element message = new Element("message");
            message.addContent(context.getMessage(error, getResourceLoader().getLocale()));
            errorElement.addContent(message);
            errorsElement.addContent(errorElement);
        }
        root.addContent(errorsElement);
    }
    if (httpServletRequest.getParameter("success") != null) {
        Element success = new Element("success");
        success.setAttribute("messageKey", httpServletRequest.getParameter("success"));
        root.addContent(success);
    }
    if (toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS) != null) {
        Element uri = new Element("uri");
        uri.setText((String) toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS));
        root.getChild("css").addContent(uri);
        uri.setAttribute("order", "100");
    }
    if (toolSession.getAttribute(FormHelper.FORM_STYLES) != null) {
        List styles = (List) toolSession.getAttribute(FormHelper.FORM_STYLES);
        int index = 101;
        for (Iterator<String> i = styles.iterator(); i.hasNext(); ) {
            Element uri = new Element("uri");
            uri.setText(i.next());
            root.getChild("css").addContent(uri);
            uri.setAttribute("order", "" + index);
            index++;
        }
    }
    Document doc = new Document(root);
    return new JDOMSource(doc);
}
Example 46
Project: shopizer-master  File: OrderFacadeImpl.java View source code
@Override
public void validateOrder(ShopOrder order, BindingResult bindingResult, Map<String, String> messagesResult, MerchantStore store, Locale locale) throws ServiceException {
    Validate.notNull(messagesResult, "messagesResult should not be null");
    try {
        //validate order shipping and billing
        if (StringUtils.isBlank(order.getCustomer().getBilling().getFirstName())) {
            FieldError error = new FieldError("customer.billing.firstName", "customer.billing.firstName", messages.getMessage("NotEmpty.customer.firstName", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.firstName", messages.getMessage("NotEmpty.customer.firstName", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getBilling().getLastName())) {
            FieldError error = new FieldError("customer.billing.lastName", "customer.billing.lastName", messages.getMessage("NotEmpty.customer.lastName", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.lastName", messages.getMessage("NotEmpty.customer.lastName", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getEmailAddress())) {
            FieldError error = new FieldError("customer.emailAddress", "customer.emailAddress", messages.getMessage("NotEmpty.customer.emailAddress", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.emailAddress", messages.getMessage("NotEmpty.customer.emailAddress", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getBilling().getAddress())) {
            FieldError error = new FieldError("customer.billing.address", "customer.billing.address", messages.getMessage("NotEmpty.customer.billing.address", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.address", messages.getMessage("NotEmpty.customer.billing.address", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getBilling().getCity())) {
            FieldError error = new FieldError("customer.billing.city", "customer.billing.city", messages.getMessage("NotEmpty.customer.billing.city", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.city", messages.getMessage("NotEmpty.customer.billing.city", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getBilling().getCountry())) {
            FieldError error = new FieldError("customer.billing.country", "customer.billing.country", messages.getMessage("NotEmpty.customer.billing.country", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.country", messages.getMessage("NotEmpty.customer.billing.country", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getBilling().getZone()) && StringUtils.isBlank(order.getCustomer().getBilling().getStateProvince())) {
            FieldError error = new FieldError("customer.billing.stateProvince", "customer.billing.stateProvince", messages.getMessage("NotEmpty.customer.billing.stateProvince", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.stateProvince", messages.getMessage("NotEmpty.customer.billing.stateProvince", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getBilling().getPhone())) {
            FieldError error = new FieldError("customer.billing.phone", "customer.billing.phone", messages.getMessage("NotEmpty.customer.billing.phone", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.phone", messages.getMessage("NotEmpty.customer.billing.phone", locale));
        }
        if (StringUtils.isBlank(order.getCustomer().getBilling().getPostalCode())) {
            FieldError error = new FieldError("customer.billing.postalCode", "customer.billing.postalCode", messages.getMessage("NotEmpty.customer.billing.postalCode", locale));
            bindingResult.addError(error);
            messagesResult.put("customer.billing.postalCode", messages.getMessage("NotEmpty.customer.billing.postalCode", locale));
        }
        if (!order.isShipToBillingAdress()) {
            if (StringUtils.isBlank(order.getCustomer().getDelivery().getFirstName())) {
                FieldError error = new FieldError("customer.delivery.firstName", "customer.delivery.firstName", messages.getMessage("NotEmpty.customer.shipping.firstName", locale));
                bindingResult.addError(error);
                messagesResult.put("customer.delivery.firstName", messages.getMessage("NotEmpty.customer.shipping.firstName", locale));
            }
            if (StringUtils.isBlank(order.getCustomer().getDelivery().getLastName())) {
                FieldError error = new FieldError("customer.delivery.lastName", "customer.delivery.lastName", messages.getMessage("NotEmpty.customer.shipping.lastName", locale));
                bindingResult.addError(error);
                messagesResult.put("customer.delivery.lastName", messages.getMessage("NotEmpty.customer.shipping.lastName", locale));
            }
            if (StringUtils.isBlank(order.getCustomer().getDelivery().getAddress())) {
                FieldError error = new FieldError("customer.delivery.address", "customer.delivery.address", messages.getMessage("NotEmpty.customer.shipping.address", locale));
                bindingResult.addError(error);
                messagesResult.put("customer.delivery.address", messages.getMessage("NotEmpty.customer.shipping.address", locale));
            }
            if (StringUtils.isBlank(order.getCustomer().getDelivery().getCity())) {
                FieldError error = new FieldError("customer.delivery.city", "customer.delivery.city", messages.getMessage("NotEmpty.customer.shipping.city", locale));
                bindingResult.addError(error);
                messagesResult.put("customer.delivery.city", messages.getMessage("NotEmpty.customer.shipping.city", locale));
            }
            if (StringUtils.isBlank(order.getCustomer().getDelivery().getCountry())) {
                FieldError error = new FieldError("customer.delivery.country", "customer.delivery.country", messages.getMessage("NotEmpty.customer.shipping.country", locale));
                bindingResult.addError(error);
                messagesResult.put("customer.delivery.country", messages.getMessage("NotEmpty.customer.shipping.country", locale));
            }
            if (StringUtils.isBlank(order.getCustomer().getDelivery().getZone()) && StringUtils.isBlank(order.getCustomer().getDelivery().getStateProvince())) {
                FieldError error = new FieldError("customer.delivery.stateProvince", "customer.delivery.stateProvince", messages.getMessage("NotEmpty.customer.shipping.stateProvince", locale));
                bindingResult.addError(error);
                messagesResult.put("customer.delivery.stateProvince", messages.getMessage("NotEmpty.customer.shipping.stateProvince", locale));
            }
            if (StringUtils.isBlank(order.getCustomer().getDelivery().getPostalCode())) {
                FieldError error = new FieldError("customer.delivery.postalCode", "customer.delivery.postalCode", messages.getMessage("NotEmpty.customer.shipping.postalCode", locale));
                bindingResult.addError(error);
                messagesResult.put("customer.delivery.postalCode", messages.getMessage("NotEmpty.customer.shipping.postalCode", locale));
            }
        }
        if (bindingResult.hasErrors()) {
            return;
        }
        String paymentType = order.getPaymentMethodType();
        if (!shoppingCartService.isFreeShoppingCart(order.getShoppingCartItems()) && paymentType == null) {
        }
        //validate payment
        if (paymentType == null) {
            ServiceException serviceException = new ServiceException(ServiceException.EXCEPTION_VALIDATION, "payment.required");
            throw serviceException;
        }
        //validate shipping
        if (shippingService.requiresShipping(order.getShoppingCartItems(), store) && order.getSelectedShippingOption() == null) {
            ServiceException serviceException = new ServiceException(ServiceException.EXCEPTION_VALIDATION, "shipping.required");
            throw serviceException;
        }
        //pre-validate credit card
        if (PaymentType.CREDITCARD.name().equals(paymentType)) {
            String cco = order.getPayment().get("creditcard_card_holder");
            String cvv = order.getPayment().get("creditcard_card_cvv");
            String ccn = order.getPayment().get("creditcard_card_number");
            String ccm = order.getPayment().get("creditcard_card_expirationmonth");
            String ccd = order.getPayment().get("creditcard_card_expirationyear");
            if (StringUtils.isBlank(cco) || StringUtils.isBlank(cvv) || StringUtils.isBlank(ccn) || StringUtils.isBlank(ccm) || StringUtils.isBlank(ccd)) {
                ObjectError error = new ObjectError("creditcard_card_holder", messages.getMessage("NotEmpty.customer.shipping.stateProvince", locale));
                bindingResult.addError(error);
                messagesResult.put("creditcard_card_holder", messages.getMessage("NotEmpty.customer.shipping.stateProvince", locale));
                return;
            }
            CreditCardType creditCardType = null;
            String cardType = order.getPayment().get("creditcard_card_type");
            if (cardType.equalsIgnoreCase(CreditCardType.AMEX.name())) {
                creditCardType = CreditCardType.AMEX;
            } else if (cardType.equalsIgnoreCase(CreditCardType.VISA.name())) {
                creditCardType = CreditCardType.VISA;
            } else if (cardType.equalsIgnoreCase(CreditCardType.MASTERCARD.name())) {
                creditCardType = CreditCardType.MASTERCARD;
            } else if (cardType.equalsIgnoreCase(CreditCardType.DINERS.name())) {
                creditCardType = CreditCardType.DINERS;
            } else if (cardType.equalsIgnoreCase(CreditCardType.DISCOVERY.name())) {
                creditCardType = CreditCardType.DISCOVERY;
            }
            if (creditCardType == null) {
                ServiceException serviceException = new ServiceException(ServiceException.EXCEPTION_VALIDATION, "cc.type");
                throw serviceException;
            }
        }
    } catch (ServiceException se) {
        LOGGER.error("Error while commiting order", se);
        throw se;
    }
}
Example 47
Project: songjhh_blog-master  File: UserController.java View source code
//注册账�
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Model model, @Valid UserCustom userCustom, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for (ObjectError objectError : allErrors) {
            //输出错误信�
            System.out.println(objectError.getDefaultMessage());
        }
        model.addAttribute("allErrors", allErrors);
        model.addAttribute("user", userCustom);
        return "/user/register";
    }
    if (userService.getByUserName(userCustom.getUsername()) == null) {
        userService.insertUser(userCustom);
        //3为普通用户 待改善
        userService.giveRole(userCustom, 3);
        return "redirect:/";
    } else {
        model.addAttribute("user", userCustom);
        model.addAttribute("errormessage", "userName has been registered!");
        return "/user/register";
    }
}
Example 48
Project: spring-framework-2.5.x-master  File: FormControllerTests.java View source code
public void testSubmit1Mismatch1Invalidated() throws Exception {
    String formView = "fred";
    String successView = "tony";
    TestController mc = new TestController();
    mc.setFormView(formView);
    mc.setSuccessView(successView);
    mc.setValidators(new Validator[] { new TestValidator(), new TestValidator2() });
    String name = "Rod";
    // will be rejected
    String age = "xxx";
    MockHttpServletRequest request = new MockHttpServletRequest("POST", "/foo.html");
    request.addParameter("name", name);
    request.addParameter("age", "" + age);
    HttpServletResponse response = new MockHttpServletResponse();
    ModelAndView mv = mc.handleRequest(request, response);
    assertTrue("returned correct view name: expected '" + formView + "', not '" + mv.getViewName() + "'", mv.getViewName().equals(formView));
    TestBean person = (TestBean) mv.getModel().get(TestController.BEAN_NAME);
    assertTrue("model is non null", person != null);
    // yes, but it was rejected after binding by the validator
    assertTrue("bean name bound ok", person.getName().equals(name));
    assertTrue("bean age is default", person.getAge() == TestController.DEFAULT_AGE);
    Errors errors = (Errors) mv.getModel().get(BindException.MODEL_KEY_PREFIX + mc.getCommandName());
    assertTrue("errors returned in model", errors != null);
    assertTrue("3 errors", errors.getErrorCount() == 3);
    FieldError fe = errors.getFieldError("age");
    assertTrue("Saved invalid value", fe.getRejectedValue().equals(age));
    assertTrue("Correct field", fe.getField().equals("age"));
    // raised by first validator
    fe = errors.getFieldError("name");
    assertTrue("Saved invalid value", fe.getRejectedValue().equals(name));
    assertTrue("Correct field", fe.getField().equals("name"));
    assertTrue("Correct validation code: expected '" + TestValidator.TOOSHORT + "', not '" + fe.getCode() + "'", fe.getCode().equals(TestValidator.TOOSHORT));
    // raised by second validator
    ObjectError oe = errors.getGlobalError();
    assertEquals("test", oe.getCode());
    assertEquals("testmessage", oe.getDefaultMessage());
}
Example 49
Project: spring-js-master  File: ValidatorFactoryTests.java View source code
@Test
public void testSpringValidationWithClassLevel() throws Exception {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.afterPropertiesSet();
    ValidPerson person = new ValidPerson();
    person.setName("Juergen");
    person.getAddress().setStreet("Juergen's Street");
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
    validator.validate(person, result);
    assertEquals(1, result.getErrorCount());
    ObjectError fieldError = result.getGlobalError();
    System.out.println(Arrays.asList(fieldError.getCodes()));
    System.out.println(fieldError.getDefaultMessage());
}
Example 50
Project: spring-rest-server-master  File: DefaultExceptionHandler.java View source code
private Map<String, Map<String, Object>> convertConstraintViolation(MethodArgumentNotValidException ex) {
    Map<String, Map<String, Object>> result = Maps.newHashMap();
    for (ObjectError error : ex.getBindingResult().getAllErrors()) {
        Map<String, Object> violationMap = Maps.newHashMap();
        violationMap.put("target", ex.getBindingResult().getTarget());
        violationMap.put("type", ex.getBindingResult().getTarget().getClass());
        violationMap.put("message", error.getDefaultMessage());
        result.put(error.getObjectName(), violationMap);
    }
    return result;
}
Example 51
Project: stability-utils-master  File: StatisticsProvider.java View source code
public synchronized void logValidationFailures(BindingResult errors) {
    for (ObjectError error : (List<ObjectError>) errors.getAllErrors()) {
        String errorName = error.getCode();
        if (errorHistogram.containsKey(errorName)) {
            // error exists in map -- update!
            AtomicLong count = errorHistogram.get(errorName);
            count.addAndGet(1L);
        } else {
            // add error type to map
            AtomicLong count = new AtomicLong();
            count.set(1L);
            errorHistogram.put(errorName, count);
        }
    }
}
Example 52
Project: stormpath-spring-samples-master  File: SignUpController.java View source code
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("customer") User user, ModelMap model, BindingResult result, SessionStatus status) {
    singUpValidator.validate(user, result);
    Map<String, String> groupMap = null;
    try {
        if (result.hasErrors()) {
            model.addAttribute("ADMINISTRATOR_URL", administratorGroupURL);
            model.addAttribute("PREMIUM_URL", premiumGroupURL);
            setGroupsToModel(groupMap, model);
            return "signUp";
        }
        String userName = user.getFirstName().toLowerCase() + user.getLastName().toLowerCase();
        // For account creation, we should get an instance of Account from the DataStore,
        // set the account properties and create it in the proper directory.
        Account account = stormpath.getDataStore().instantiate(Account.class);
        account.setEmail(user.getEmail());
        account.setGivenName(user.getFirstName());
        account.setSurname(user.getLastName());
        account.setPassword(user.getPassword());
        account.setUsername(userName);
        // Saving the account to the Directory where the Tooter application belongs.
        Directory directory = stormpath.getDirectory();
        directory.createAccount(account);
        if (user.getGroupUrl() != null && !user.getGroupUrl().isEmpty()) {
            account.addGroup(stormpath.getDataStore().getResource(user.getGroupUrl(), Group.class));
        }
        user.setUserName(userName);
        customerDao.saveCustomer(user);
        status.setComplete();
    } catch (RuntimeException re) {
        model.addAttribute("ADMINISTRATOR_URL", administratorGroupURL);
        model.addAttribute("PREMIUM_URL", premiumGroupURL);
        setGroupsToModel(groupMap, model);
        result.addError(new ObjectError("password", re.getMessage()));
        re.printStackTrace();
        return "signUp";
    } catch (Exception e) {
        e.printStackTrace();
    }
    //form success
    return "redirect:/login/message?loginMsg=registered";
}
Example 53
Project: summer-master  File: ErrorResolver.java View source code
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
    if (e instanceof BindException) {
        BindException be = (BindException) e;
        Map<String, Map<String, Object>> errors = new HashMap<String, Map<String, Object>>();
        for (FieldError fe : (List<FieldError>) be.getFieldErrors()) {
            Map<String, Object> error = new HashMap<String, Object>();
            Object[] args = fe.getArguments();
            String key = fe.isBindingFailure() ? fe.getCodes()[2].replaceFirst("typeMismatch", "conversion") : "validation." + fe.getCodes()[2];
            String message = ResourceUtils.getMessage(key, args);
            if (message == null) {
                if (!fe.isBindingFailure()) {
                    if (key.split("\\.").length > 3) {
                        message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args);
                    }
                    if (message == null && key.split("\\.").length > 2) {
                        message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args);
                    }
                } else if (fe.isBindingFailure() && key.split("\\.").length > 2) {
                    message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".")) + key.substring(key.lastIndexOf(".")), args);
                } else {
                    message = fe.getDefaultMessage();
                }
            }
            error.put("message", message != null ? message : "Error (" + key + ")");
            error.put("value", fe.getRejectedValue());
            errors.put(fe.getField(), error);
        }
        for (ObjectError oe : (List<ObjectError>) be.getGlobalErrors()) {
            Map<String, Object> error = new HashMap<String, Object>();
            Object[] args = oe.getArguments();
            String key = "global" + (oe.getCodes() != null ? "." + oe.getCodes()[2] : "");
            String message = ResourceUtils.getMessage(key, args);
            if (message == null) {
                if (key.split("\\.").length > 3) {
                    message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)) + key.substring(key.lastIndexOf(".")), args);
                }
                if (message == null && key.split("\\.").length > 2) {
                    message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args);
                }
                if (message == null) {
                    message = oe.getDefaultMessage();
                }
            }
            error.put("message", message != null ? message : "Error (" + key + ")");
            error.put("value", oe.getObjectName());
            errors.put(oe.getObjectName(), error);
        }
        String form = (String) RequestUtils.getParameter("_form");
        if (form != null) {
            if (request.getAttribute(ERRORS) == null) {
                request.setAttribute(ERRORS, errors);
                request.setAttribute(be.getObjectName(), be.getTarget());
                return new ModelAndView(new InternalResourceView(form.concat(form.contains("?") ? "&" : "?").concat("_error=true")));
            }
        } else {
            List<String> pairs = new ArrayList<String>();
            for (String key : errors.keySet()) {
                pairs.add(key + "=" + errors.get(key).get("message"));
            }
            try {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, StringUtils.join(pairs, ";"));
            } catch (IOException ioe) {
                logger.error(ioe.getMessage(), ioe);
            }
        }
    }
    return null;
}
Example 54
Project: Broadleaf-eCommerce-master  File: AdminBasicEntityController.java View source code
/**
     * Populates the given <b>json</b> response object based on the given <b>form</b> and <b>result</b>
     * @return the same <b>result</b> that was passed in
     */
protected JsonResponse populateJsonValidationErrors(EntityForm form, BindingResult result, JsonResponse json) {
    List<Map<String, Object>> errors = new ArrayList<Map<String, Object>>();
    for (FieldError e : result.getFieldErrors()) {
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("errorType", "field");
        String fieldName = e.getField().substring(e.getField().indexOf("[") + 1, e.getField().indexOf("]")).replace("_", "-");
        errorMap.put("field", fieldName);
        errorMap.put("message", translateErrorMessage(e));
        errorMap.put("code", e.getCode());
        String tabFieldName = fieldName.replaceAll("-+", ".");
        Tab errorTab = form.findTabForField(tabFieldName);
        if (errorTab != null) {
            errorMap.put("tab", errorTab.getTitle());
        }
        errors.add(errorMap);
    }
    for (ObjectError e : result.getGlobalErrors()) {
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("errorType", "global");
        errorMap.put("code", e.getCode());
        errorMap.put("message", translateErrorMessage(e));
        errors.add(errorMap);
    }
    json.with("errors", errors);
    return json;
}
Example 55
Project: BroadleafCommerce-master  File: AdminBasicEntityController.java View source code
/**
     * Populates the given <b>json</b> response object based on the given <b>form</b> and <b>result</b>
     * @return the same <b>result</b> that was passed in
     */
protected JsonResponse populateJsonValidationErrors(EntityForm form, BindingResult result, JsonResponse json) {
    List<Map<String, Object>> errors = new ArrayList<Map<String, Object>>();
    for (FieldError e : result.getFieldErrors()) {
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("errorType", "field");
        String fieldName = e.getField().substring(e.getField().indexOf("[") + 1, e.getField().indexOf("]")).replace("_", "-");
        errorMap.put("field", fieldName);
        errorMap.put("message", translateErrorMessage(e));
        errorMap.put("code", e.getCode());
        String tabFieldName = fieldName.replaceAll("-+", ".");
        Tab errorTab = form.findTabForField(tabFieldName);
        if (errorTab != null) {
            errorMap.put("tab", errorTab.getTitle());
        }
        errors.add(errorMap);
    }
    for (ObjectError e : result.getGlobalErrors()) {
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("errorType", "global");
        errorMap.put("code", e.getCode());
        errorMap.put("message", translateErrorMessage(e));
        errors.add(errorMap);
    }
    json.with("errors", errors);
    return json;
}
Example 56
Project: cloud-rest-service-master  File: DefaultHandlerExceptionResolver.java View source code
protected MainError handleBindException(BindException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    List<ObjectError> errorList = ex.getBindingResult().getAllErrors();
    //将Bean数�绑定时产生的错误转�为Rop的错误
    MainError mainError = null;
    if (errorList != null && errorList.size() > 0) {
        mainError = toMainErrorOfSpringValidateErrors(errorList, (Locale) request.getAttribute(Constants.SYS_PARAM_KEY_LOCALE));
    }
    return mainError;
}
Example 57
Project: commerce-master  File: AdminBasicEntityController.java View source code
/**
     * Populates the given <b>json</b> response object based on the given <b>form</b> and <b>result</b>
     * @return the same <b>result</b> that was passed in
     */
protected JsonResponse populateJsonValidationErrors(EntityForm form, BindingResult result, JsonResponse json) {
    List<Map<String, Object>> errors = new ArrayList<Map<String, Object>>();
    for (FieldError e : result.getFieldErrors()) {
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("errorType", "field");
        String fieldName = e.getField().substring(e.getField().indexOf("[") + 1, e.getField().indexOf("]")).replace("_", "-");
        errorMap.put("field", fieldName);
        errorMap.put("message", translateErrorMessage(e));
        errorMap.put("code", e.getCode());
        String tabFieldName = fieldName.replaceAll("-+", ".");
        Tab errorTab = form.findTabForField(tabFieldName);
        if (errorTab != null) {
            errorMap.put("tab", errorTab.getTitle());
        }
        errors.add(errorMap);
    }
    for (ObjectError e : result.getGlobalErrors()) {
        Map<String, Object> errorMap = new HashMap<String, Object>();
        errorMap.put("errorType", "global");
        errorMap.put("code", e.getCode());
        errorMap.put("message", translateErrorMessage(e));
        errors.add(errorMap);
    }
    json.with("errors", errors);
    return json;
}
Example 58
Project: easyrec-code-master  File: ConfigurationHelperTests.java View source code
@Test
public void testCustomValidator() {
    MutablePropertyValues values = new MutablePropertyValues();
    values.addPropertyValue("stringField", "the quick brown fox");
    values.addPropertyValue("doubleObjectField", "57.5434d");
    values.addPropertyValue("doublePrimitiveField", "58.5434d");
    Configuration config = new SameValuesTestConfiguration();
    ConfigurationHelper helper = new ConfigurationHelper(config);
    BindingResult result = helper.setValues(values);
    assertEquals(1, result.getGlobalErrorCount());
    assertEquals("error.sameValue", ((ObjectError) result.getGlobalErrors().get(0)).getCode());
    // now set different values:
    values = new MutablePropertyValues();
    values.addPropertyValue("stringField", "the quick brown fox");
    values.addPropertyValue("doubleObjectField", null);
    values.addPropertyValue("doublePrimitiveField", "58.5434d");
    helper.reset();
    result = helper.setValues(values);
    assertEquals(1, result.getFieldErrorCount());
    assertEquals("error.sameValue", ((ObjectError) result.getFieldErrors("doublePrimitiveField").get(0)).getCode());
    values = new MutablePropertyValues();
    values.addPropertyValue("stringField", "the quick brown fox");
    values.addPropertyValue("doubleObjectField", "58.5434d");
    values.addPropertyValue("doublePrimitiveField", "58.5434d");
    helper.reset();
    result = helper.setValues(values);
    assertEquals(0, result.getErrorCount());
}
Example 59
Project: fiware-cepheus-master  File: AdminController.java View source code
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<StatusCode> validationExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException exception) {
    StringBuffer sb = new StringBuffer();
    for (ObjectError error : exception.getBindingResult().getAllErrors()) {
        if (sb.length() != 0) {
            sb.append(", ");
        }
        sb.append(error.getDefaultMessage());
    }
    logger.error("Configuration validation error: {}", sb.toString());
    StatusCode statusCode = new StatusCode();
    statusCode.setCode("400");
    statusCode.setReasonPhrase("Configuration validation error");
    statusCode.setDetail(sb.toString());
    return new ResponseEntity<>(statusCode, HttpStatus.BAD_REQUEST);
}
Example 60
Project: jetbrick-template-extend-master  File: SpringMvcFunctions.java View source code
/**
	 * 获�所有的全局错误信�
	 */
public static List<String> globalErrors(JetPageContext ctx) {
    Errors errors = FunctionUtils.findErrors(ctx.getContext());
    if (errors == null) {
        return EMPTY_STRING_LIST;
    }
    List<ObjectError> oes = errors.getGlobalErrors();
    List<String> msgs = new ArrayList<String>(0);
    for (ObjectError oe : oes) {
        String[] codes = oe.getCodes();
        String defaultMsg = oe.getDefaultMessage();
        Object[] args = oe.getArguments();
        Locale locale = getLocale(ctx);
        MessageSource ms = getMessageSource(ctx);
        if (codes == null || codes.length == 0 || ms == null) {
            msgs.add(defaultMsg);
        } else {
            String msg = null;
            for (int i = 0; i < codes.length; i++) {
                try {
                    msg = ms.getMessage(codes[i], args, locale);
                } catch (NoSuchMessageException e) {
                }
                if (msg == null) {
                    msg = defaultMsg;
                }
            }
            msgs.add(msg);
        }
    }
    return Collections.unmodifiableList(msgs);
}
Example 61
Project: Katari-master  File: FreemarkerTestEngineTest.java View source code
public void testRunAndValidate_springErrors() throws Exception {
    // Creates the basic model.
    Map<String, Object> model = buildModel();
    // Adds some validation errors to the model.
    BeanPropertyBindingResult result;
    result = new BeanPropertyBindingResult(command, "command");
    result.addError(new ObjectError("command.profile.name", new String[] { "1" }, null, "This is the error message for the user name"));
    result.addError(new ObjectError("command.profile.email", new String[] { "1" }, null, "This is the error message for the user email"));
    model.putAll(result.getModel());
    FreemarkerTestEngine engine;
    engine = new FreemarkerTestEngine("/com/globant/katari/tools", model);
    List<String> valid = new ArrayList<String>();
    valid.add(".*This is the error message for the user name.*");
    valid.add(".*This is the error message for the user email.*");
    engine.runAndValidate("freemarkerTestEngineTest.ftl", valid, Collections.<String>emptyList());
}
Example 62
Project: mateo-master  File: EntradaController.java View source code
@Transactional
@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo, @ModelAttribute Entrada entrada, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    log.debug("Elimina entrada");
    try {
        String nombre = entradaDao.elimina(id, ambiente.obtieneUsuario());
        redirectAttributes.addFlashAttribute("message", "entrada.eliminada.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar la entrada " + id, e);
        bindingResult.addError(new ObjectError("entrada", new String[] { "entrada.no.eliminada.message" }, null, null));
        return "inventario/entrada/ver";
    }
    return "redirect:/inventario/entrada";
}
Example 63
Project: MavenOneCMDB-master  File: SiteController.java View source code
@Override
protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
    super.onBindAndValidate(request, command, errors);
    SiteCommand site = (SiteCommand) command;
    // data is here bound into site, including the current action 
    SiteAction action = site.getAction();
    if (action == null) {
        // we are coming here without having an action 
        errors.addError(new ObjectError("SiteController", null, null, "No Action set!"));
        return;
    }
    // initiate the action, via the parameters in the request
    ServletRequestDataBinder binder = new ServletRequestDataBinder(action);
    binder.bind(request);
}
Example 64
Project: OpenClinica-master  File: StudySubjectEndpoint.java View source code
private Element mapConfirmation(String confirmation, String studySubjectLabel, Errors errors, String label, List<String> error_messages) throws Exception {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document document = docBuilder.newDocument();
    Element responseElement = document.createElementNS(NAMESPACE_URI_V1, "createResponse");
    Element resultElement = document.createElementNS(NAMESPACE_URI_V1, "result");
    resultElement.setTextContent(confirmation);
    responseElement.appendChild(resultElement);
    if (studySubjectLabel != null) {
        Element labelElement = document.createElementNS(NAMESPACE_URI_V1, label);
        labelElement.setTextContent(studySubjectLabel);
        responseElement.appendChild(labelElement);
    }
    if (errors != null) {
        for (ObjectError error : errors.getAllErrors()) {
            Element errorElement = document.createElementNS(NAMESPACE_URI_V1, "error");
            String theMessage = messages.getMessage(error.getCode(), error.getArguments(), locale);
            errorElement.setTextContent(theMessage);
            responseElement.appendChild(errorElement);
        }
    }
    if (error_messages != null && error_messages.size() > 0) {
        StringBuilder output_msg = new StringBuilder();
        for (String mes : error_messages) {
            output_msg.append(mes);
        }
        Element msgElement = document.createElementNS(NAMESPACE_URI_V1, "error");
        msgElement.setTextContent(output_msg.toString());
        responseElement.appendChild(msgElement);
    }
    return responseElement;
}
Example 65
Project: opennms_dashboard-master  File: DefaultDistributedStatusServiceTest.java View source code
public void testCreateStatusNoLocationMonitor() {
    DistributedStatusDetailsCommand command = new DistributedStatusDetailsCommand();
    Errors errors = new BindException(command, "command");
    command.setLocation(m_locationDefinition3.getName());
    command.setApplication(m_application2.getName());
    expect(m_applicationDao.findByName("Application 2")).andReturn(m_application2);
    expect(m_locationMonitorDao.findMonitoringLocationDefinition(m_locationDefinition3.getName())).andReturn(m_locationDefinition3);
    expect(m_locationMonitorDao.findByLocationDefinition(m_locationDefinition3)).andReturn(new HashSet<OnmsLocationMonitor>());
    m_easyMockUtils.replayAll();
    SimpleWebTable table = m_service.createStatusTable(command, errors);
    Errors errorsOut = table.getErrors();
    assertEquals("Number of errors", 1, errorsOut.getErrorCount());
    assertEquals("Number of global errors", 1, errorsOut.getGlobalErrorCount());
    assertEquals("Number of field errors", 0, errorsOut.getFieldErrorCount());
    ObjectError e = (ObjectError) errorsOut.getGlobalErrors().get(0);
    assertEquals("Error code 0", "location.no-monitors", e.getCode());
    assertEquals("Error 0 argument count", 2, e.getArguments().length);
    assertEquals("Error argument 0.0", "Application 2", e.getArguments()[0]);
    assertEquals("Error argument 0.0", "Columbus", e.getArguments()[1]);
    m_easyMockUtils.verifyAll();
}
Example 66
Project: riot-master  File: FormErrors.java View source code
private List<String> getErrorMessages(List<? extends ObjectError> errors) {
    ArrayList<String> messages = Generics.newArrayList();
    for (ObjectError error : errors) {
        String message = form.getFormContext().getMessageResolver().getMessage(error);
        if (!StringUtils.hasLength(message)) {
            message = StringUtils.arrayToCommaDelimitedString(error.getCodes());
        }
        messages.add(message);
    }
    return messages;
}
Example 67
Project: rop-master  File: DefaultSecurityManager.java View source code
private MainError validateBusinessParams(RopRequestContext context) {
    List<ObjectError> errorList = (List<ObjectError>) context.getAttribute(SimpleRopRequestContext.SPRING_VALIDATE_ERROR_ATTRNAME);
    //将Bean数�绑定时产生的错误转�为Rop的错误
    if (errorList != null && errorList.size() > 0) {
        return toMainErrorOfSpringValidateErrors(errorList, context.getLocale(), context);
    } else {
        return null;
    }
}
Example 68
Project: spring-webflow-master  File: MessageContextErrors.java View source code
public void addAllErrors(Errors errors) {
    for (ObjectError error : errors.getAllErrors()) {
        MessageBuilder builder = new MessageBuilder().error().codes(error.getCodes()).args(error.getArguments()).defaultText(error.getDefaultMessage());
        if (error instanceof FieldError) {
            FieldError fieldError = (FieldError) error;
            builder.source(fieldError.getField());
        }
        messageContext.addMessage(builder.build());
    }
}
Example 69
Project: spring-ws-master  File: AbstractFaultCreatingValidatingMarshallingPayloadEndpoint.java View source code
/**
	 * This implementation logs all errors, returns {@code false}, and creates a {@link
	 * SoapBody#addClientOrSenderFault(String,Locale) client or sender} {@link SoapFault}, adding a {@link
	 * SoapFaultDetail} with all errors if the {@code addValidationErrorDetail} property is {@code true}.
	 *
	 * @param messageContext the message context
	 * @param errors		 the validation errors
	 * @return {@code true} to continue processing the request, {@code false} (the default) otherwise
	 * @see Errors#getAllErrors()
	 */
@Override
protected final boolean onValidationErrors(MessageContext messageContext, Object requestObject, Errors errors) {
    for (ObjectError objectError : errors.getAllErrors()) {
        String msg = messageSource.getMessage(objectError, getFaultLocale());
        logger.warn("Validation error on request object[" + requestObject + "]: " + msg);
    }
    if (messageContext.getResponse() instanceof SoapMessage) {
        SoapMessage response = (SoapMessage) messageContext.getResponse();
        SoapBody body = response.getSoapBody();
        SoapFault fault = body.addClientOrSenderFault(getFaultStringOrReason(), getFaultLocale());
        if (getAddValidationErrorDetail()) {
            SoapFaultDetail detail = fault.addFaultDetail();
            for (ObjectError objectError : errors.getAllErrors()) {
                String msg = messageSource.getMessage(objectError, getFaultLocale());
                SoapFaultDetailElement detailElement = detail.addFaultDetailElement(getDetailElementName());
                detailElement.addText(msg);
            }
        }
    }
    return false;
}
Example 70
Project: thredds-master  File: LocalCatalogServiceController.java View source code
@RequestMapping(value = { "/**/*.xml" }, method = { RequestMethod.GET, RequestMethod.HEAD })
protected ModelAndView handleXmlRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        // Bind HTTP request to a LocalCatalogRequest.
        BindingResult bindingResult = CatalogServiceUtils.bindAndValidateLocalCatalogRequest(request, false);
        // If any binding or validation errors, return BAD_REQUEST.
        if (bindingResult.hasErrors()) {
            StringBuilder msg = new StringBuilder("Bad request");
            List<ObjectError> oeList = bindingResult.getAllErrors();
            for (ObjectError e : oeList) msg.append(": ").append(e.getDefaultMessage() != null ? e.getDefaultMessage() : e.toString());
            log.info("handleRequestInternal(): " + msg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg.toString());
            return null;
        }
        // Retrieve the resulting LocalCatalogRequest.
        LocalCatalogRequest catalogServiceRequest = (LocalCatalogRequest) bindingResult.getTarget();
        // Determine path and catalogPath
        String catalogPath = catalogServiceRequest.getPath();
        // Check for matching catalog.
        DataRootHandler drh = DataRootHandler.getInstance();
        InvCatalog catalog = null;
        String baseUriString = request.getRequestURL().toString();
        try {
            catalog = drh.getCatalog(catalogPath, new URI(baseUriString));
        } catch (URISyntaxException e) {
            String msg = "Bad URI syntax [" + baseUriString + "]: " + e.getMessage();
            log.error("handleRequestInternal(): " + msg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return null;
        }
        // If no catalog found, handle as a publicDoc request.
        if (catalog == null)
            return handlePublicDocumentRequest(request, response, catalogPath);
        // Otherwise, handle catalog as indicated by "command".
        if (catalogServiceRequest.getCommand().equals(Command.SHOW)) {
            return new ModelAndView("threddsInvCatXmlView", "catalog", catalog);
        } else if (catalogServiceRequest.getCommand().equals(Command.SUBSET)) {
            String datasetId = catalogServiceRequest.getDataset();
            InvDataset dataset = catalog.findDatasetByID(datasetId);
            if (dataset == null) {
                String msg = "Did not find dataset [" + datasetId + "] in catalog [" + baseUriString + "].";
                response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
                return null;
            }
            InvCatalog subsetCat = DeepCopyUtils.subsetCatalogOnDataset(catalog, dataset);
            return new ModelAndView("threddsInvCatXmlView", "catalog", subsetCat);
        } else {
            String msg = "Unsupported request command [" + catalogServiceRequest.getCommand() + "].";
            log.error("handleRequestInternal(): " + msg + " -- NOTE: Should have been caught on input validation.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return null;
        }
    } catch (IOException e) {
        log.error("handleRequestInternal(): Trouble writing to response.", e);
        return null;
    } catch (Throwable e) {
        log.error("handleRequestInternal(): Problem handling request.", e);
        if (!response.isCommitted())
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }
}
Example 71
Project: ajah-master  File: AutoFormTag.java View source code
/**
	 * {@inheritDoc}
	 */
@Override
public int doStartTag() throws JspException {
    if (this.autoForm == null) {
        setAutoForm(this.pageContext.getRequest().getAttribute("ajahAutoForm"));
    }
    AjahUtils.requireParam(this.autoForm, "autoForm");
    try (JspWriter out = this.pageContext.getOut()) {
        final Div div = new Div().css("asm-auto");
        final Enumeration<String> attributes = this.pageContext.getRequest().getAttributeNames();
        while (attributes.hasMoreElements()) {
            final String attribute = attributes.nextElement();
            if (attribute.startsWith("org.springframework.validation.BindingResult.")) {
                final BindingResult result = (BindingResult) this.pageContext.getRequest().getAttribute(attribute);
                log.fine("Found " + result.getErrorCount() + " global errors");
                if (result.getErrorCount() > 0) {
                    final Div alertBox = div.add(new Div().css("alert").css("alert-error"));
                    final UnorderedList errs = alertBox.add(new UnorderedList().css("asm-err"));
                    for (final ObjectError error : result.getAllErrors()) {
                        errs.add(new ListItem(getMessage(error)));
                    }
                }
            }
        }
        final Form form = new Form(FormMethod.POST).css("well").css("asm-auto");
        if (!StringUtils.isBlank(getId())) {
            form.setId(getId());
        }
        for (final Field field : this.autoForm.getClass().getFields()) {
            log.fine(field.getName() + " has a value of " + field.get(this.autoForm));
            final Input<?> input = getInput(field, this.autoForm.getClass().getFields());
            form.getInputs().add(input);
        }
        String submitText = null;
        Icon iconLeft = null;
        Icon iconRight = null;
        if (this.autoForm.getClass().isAnnotationPresent(Submit.class)) {
            final Submit submit = this.autoForm.getClass().getAnnotation(Submit.class);
            submitText = submit.value();
            if (submit.iconLeft() != null && submit.iconLeft() != Icon.NONE) {
                iconLeft = submit.iconLeft();
            }
            if (submit.iconRight() != null && submit.iconRight() != Icon.NONE) {
                iconRight = submit.iconRight();
            }
        }
        if (StringUtils.isBlank(submitText)) {
            submitText = StringUtils.capitalize(StringUtils.splitCamelCase(this.autoForm.getClass().getSimpleName().replaceAll("Form$", "")));
        }
        final Button submitButton = new Button().text(submitText).type(ButtonType.SUBMIT).css("btn").css("btn-primary");
        if (iconLeft != null) {
            submitButton.addBeforeText(new Italic().css(iconLeft.getBootstrapClass()));
        }
        if (iconRight != null) {
            submitButton.add(new Italic().css(iconRight.getBootstrapClass()));
        }
        form.getInputs().add(submitButton);
        div.add(form);
        final Script script = new Script();
        final StringBuffer code = new StringBuffer();
        code.append("\n$(document).ready(function() {\n");
        for (final Input<?> child : form.getInputs()) {
            if (child instanceof TextArea && ((TextArea) child).isHtml()) {
                this.pageContext.getRequest().setAttribute("jjScriptHtmlEditor", Boolean.TRUE);
                code.append("\t$(\".rich-text" + "\").cleditor({width:\"95%\", height:\"100%\", controls: \"style bold italic strikethrough | bullets numbering | outdent indent | rule image link unlink | removeformat source\"});\n");
                break;
            }
        }
        code.append("\t$(\"#" + form.getInputs().get(0).getId() + "\").focus();\n");
        code.append("});\n");
        script.setText(code.toString());
        div.add(script);
        div.render(out, isCompact() ? -1 : 0);
    } catch (final IOException e) {
        throw new JspException(e);
    } catch (final IllegalArgumentException e) {
        throw new JspException(e);
    } catch (final IllegalAccessException e) {
        throw new JspException(e);
    }
    return Tag.EVAL_PAGE;
}
Example 72
Project: eGov-master  File: ComplaintUpdationController.java View source code
private void validateUpdate(final Complaint complaint, final BindingResult errors, final HttpServletRequest request) {
    if (complaint.getStatus() == null)
        errors.rejectValue("status", "status.requried");
    if (request.getParameter("approvalComent") == null || request.getParameter("approvalComent").trim().isEmpty())
        errors.addError(new ObjectError("approvalComent", messageSource.getMessage("comment.not.null", null, null)));
    if (complaint.getLocation() == null && complaint.getLat() != 0 && complaint.getLng() != 0)
        errors.rejectValue("location", "location.info.not.found");
    if ((complaint.getLocation() == null || complaint.getChildLocation() == null) && complaint.getLat() == 0 && complaint.getLng() == 0)
        errors.rejectValue("location", "location.info.not.found");
}
Example 73
Project: perecoder-master  File: ControllerTemplate.java View source code
/**
     * Формируем декоратор ошибок валидации объекта
     *
     * @param errors ошибки валидации
     * @param locale локализациÑ?
     * @return Возвращает декоратор ошибок валидации
     */
protected ErrorBean doHandleValidationException(Errors errors, final Locale locale) {
    Collection<String> globalErrors = Collections2.transform(errors.getGlobalErrors(), new Function<ObjectError, String>() {

        @Override
        public String apply(ObjectError input) {
            return messageSource.getMessage(input, locale);
        }
    });
    ImmutableMap.Builder<String, String> fieldErrors = ImmutableMap.builder();
    for (FieldError error : errors.getFieldErrors()) {
        fieldErrors.put(error.getField(), messageSource.getMessage(error, locale));
    }
    return new ErrorBean(globalErrors, fieldErrors.build());
}
Example 74
Project: solarnetwork-central-master  File: WebServiceControllerSupport.java View source code
private String generateErrorsMessage(Errors e, Locale locale, MessageSource msgSrc) {
    String msg = (msgSrc == null ? "Validation error" : msgSrc.getMessage("error.validation", null, "Validation error", locale));
    if (msgSrc != null && e.hasErrors()) {
        StringBuilder buf = new StringBuilder();
        for (ObjectError error : e.getAllErrors()) {
            if (buf.length() > 0) {
                buf.append(" ");
            }
            buf.append(msgSrc.getMessage(error, locale));
        }
        msg = buf.toString();
    }
    return msg;
}
Example 75
Project: GeneDB-master  File: QueryController.java View source code
@SuppressWarnings("unchecked")
public String processForm(String queryName, String suppress, boolean redirect, HttpServletRequest request, HttpSession session, Model model) throws QueryException {
    logger.info("PROCESSING FORM");
    HistoryManager hm = hmFactory.getHistoryManager(session);
    String key = generateKey(session.getId(), (Map<String, String[]>) request.getParameterMap());
    logger.info("Query key: " + key);
    PagedQuery query = null;
    QueryHistoryItem item = hm.getQueryHistoryItem(key);
    if (item == null) {
        logger.info("Could not find existing query for this session, creating ...");
        query = findQueryType(queryName, session);
        if (query == null) {
            logger.error(String.format("Unable to find query of name '%s'", queryName));
            return "redirect:/Query";
        }
    } else {
        query = item.getQuery();
    }
    logger.info("Using query " + query.getQueryName());
    // Initialise query form
    Errors errors = initialiseQueryForm(query, request);
    if (errors.hasErrors()) {
        model.addAttribute(BindingResult.MODEL_KEY_PREFIX + "query", errors);
        logger.debug("Returning due to binding error");
        for (ObjectError error : errors.getAllErrors()) {
            logger.error(error);
        }
        return "search/" + queryName;
    }
    /*
         * Bodge to make sure organism lucene queries have a taxon.
         * */
    if (query instanceof OrganismLuceneQuery) {
        OrganismLuceneQuery oq = (OrganismLuceneQuery) query;
        if (oq.getTaxons() == null) {
            TaxonNodeManager tnm = (TaxonNodeManager) applicationContext.getBean("taxonNodeManager", TaxonNodeManager.class);
            oq.setTaxons(new TaxonNodeList(tnm.getTaxonNodeByString("Root", false)));
        }
    }
    // Validate initialised form
    query.validate(query, errors);
    if (errors.hasErrors()) {
        logger.debug("Validator found errors");
        model.addAttribute(BindingResult.MODEL_KEY_PREFIX + "query", errors);
        return "search/" + queryName;
    }
    logger.debug("Validator found no errors");
    // Initialise model data
    populateModelData(model, query);
    logger.info(String.format("Adding %s with key %s to history manager", query, key));
    item = hm.addQueryHistoryItem(key, query);
    model.addAttribute("query", query);
    Bounds bounds = getQueryBounds(request);
    int start = bounds.page * bounds.length;
    int end = start + bounds.length - 1;
    //logger.info("Query page " + bounds.page + ", length " + bounds.length);
    logger.info(String.format("Page: %s, Length: %s, Start-End: %s-%s", bounds.page, bounds.length, start, end));
    List<String> ids = query.getResults(start, end);
    model.addAttribute("bounds", bounds);
    logger.info("Size :: ");
    logger.info(ids.size());
    //        for (String id : ids) {
    //    		logger.info(id);
    //    	}
    List<GeneSummary> results = summaries(ids);
    logger.info(results.size());
    //        QueryHistoryItem qhi = hm.getQueryHistoryItem(key);
    //        logger.info(String.format("Fished history item? %s", qhi));
    //
    //        List<String> uniqueNames = qhi.getIds();
    //        logger.info(qhi.getIds().size());
    //        logger.info(qhi.getIds());
    // Suppress item in results
    // suppressResultItem(suppress, results);
    String taxonName = findTaxonName(query);
    logger.info("TaxonNodeName is " + taxonName);
    model.addAttribute("taxonNodeName", taxonName);
    int totalResultsSize = query.getTotalResultsSize();
    logger.info("Total result size " + totalResultsSize);
    model.addAttribute("resultsSize", totalResultsSize);
    if (queryName.equals("quickSearch")) {
        QuickSearchQuery quickSearchQuery = (QuickSearchQuery) query;
        logger.info("Fetching quick search taxons");
        model.addAttribute("taxonGroup", quickSearchQuery.getQuickSearchQueryResults().getTaxonGroup());
    }
    if (queryName.equals("motif")) {
        MotifQuery motifQuery = (MotifQuery) query;
        logger.info("motif query, let's get motif results for " + bounds.page + " " + bounds.length);
        @SuppressWarnings("rawtypes") Map motifs = motifQuery.getMotifResults(bounds.page, bounds.length);
        model.addAttribute("motifs", motifs);
    }
    if (results.size() == 1 && redirect) {
        GeneSummary geneSummary = results.get(0);
        return "redirect:/gene/" + geneSummary.getDisplayId();
    } else if (results.size() > 0) {
        model.addAttribute("results", results);
        model.addAttribute("queryName", queryName);
        model.addAttribute("actionName", request.getContextPath() + "/Query/" + queryName);
        return "search/" + queryName;
    }
    // if the search yielded any results, we should now have been redirected
    // remove unsuccessful search term, no point in hanging onto this
    hm.removeItem(key);
    logger.warn("No results found for query");
    model.addAttribute("noResultFound", Boolean.TRUE);
    if (queryName.equals("quickSearch")) {
        QuickSearchQuery quickSearchQuery = (QuickSearchQuery) query;
        logger.info("Running suggest query as no result found");
        SuggestQuery squery = (SuggestQuery) queryFactory.retrieveQuery("suggest", NumericQueryVisibility.PRIVATE);
        squery.setSearchText(quickSearchQuery.getSearchText());
        squery.setTaxons(quickSearchQuery.getTaxons());
        squery.setMax(30);
        List<String> sResults = squery.getResults();
        model.addAttribute("suggestions", sResults);
    }
    return "search/" + queryName;
}
Example 76
Project: spring-integration-master  File: HttpRequestHandlingControllerTests.java View source code
@Test
public void testSendWithError() throws Exception {
    QueueChannel requestChannel = new QueueChannel() {

        @Override
        protected boolean doSend(Message<?> message, long timeout) {
            throw new RuntimeException("Planned");
        }
    };
    HttpRequestHandlingController controller = new HttpRequestHandlingController(false);
    controller.setBeanFactory(mock(BeanFactory.class));
    controller.setRequestChannel(requestChannel);
    controller.afterPropertiesSet();
    controller.start();
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setContent("hello".getBytes());
    request.setContentType("text/plain");
    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView modelAndView = controller.handleRequest(request, response);
    assertEquals(1, modelAndView.getModel().size());
    Errors errors = (Errors) modelAndView.getModel().get("errors");
    assertEquals(1, errors.getErrorCount());
    ObjectError error = errors.getAllErrors().get(0);
    assertEquals(3, error.getArguments().length);
    assertTrue("Wrong message: " + error, ((String) error.getArguments()[1]).startsWith("failed to send Message"));
}
Example 77
Project: Consent2Share-master  File: AccountController.java View source code
/**
	 * Login trouble.
	 * 
	 * @param loginTroubleDto
	 *            the login trouble dto
	 * @param result
	 *            the result
	 * @param request
	 *            the request
	 * @param model
	 *            the model
	 * @return the string
	 */
@RequestMapping(value = "loginTrouble.html", method = RequestMethod.POST)
public String loginTrouble(@Valid LoginTroubleDto loginTroubleDto, BindingResult result, HttpServletRequest request, Model model) {
    fieldValidatorTroubleSelection.validate(loginTroubleDto, result);
    if (result.hasErrors()) {
        return "views/loginTrouble";
    }
    String handleTroublePage = null;
    if (loginTroubleDto.getTroubleTypeId() == TroubleType.UNKNOWN_PASSWORD.getValue()) {
        handleTroublePage = "redirect:/loginTroublePassword.html";
    } else if (loginTroubleDto.getTroubleTypeId() == TroubleType.UNKNOWN_USERNAME.getValue()) {
        handleTroublePage = "redirect:/loginTroubleUsername.html";
    } else if (loginTroubleDto.getTroubleTypeId() == TroubleType.DIFFICULTY_SIGNING_IN.getValue()) {
        handleTroublePage = "redirect:/loginTroubleOther.html";
    } else {
        handleTroublePage = null;
    }
    if (handleTroublePage == null) {
        result.addError(new ObjectError(StringUtils.uncapitalize(LoginTroubleDto.class.getSimpleName()), "Please select from one of the options below."));
        handleTroublePage = "views/loginTrouble";
    }
    return handleTroublePage;
}
Example 78
Project: eMonocot-master  File: ResourceController.java View source code
/**
	  * @param organisationId
	  *            Set the source identifier
	  * @param resourceId
	  *            Set the job identifier
	  * @param model
	  *            Set the model
	  * @param session
	  *            Set the session
	  * @param resource
	  *            Set the job
	  * @param result
	  *            Set the binding results
	  * @return the view name
	  */
@RequestMapping(value = "/{resourceId}", method = RequestMethod.POST, produces = "text/html", params = { "!parameters" })
public String update(@PathVariable Long resourceId, Model model, @Validated({ Default.class, ReadResource.class }) Resource resource, BindingResult result, RedirectAttributes redirectAttributes) {
    Resource persistedResource = getService().load(resourceId);
    if (result.hasErrors()) {
        for (ObjectError objectError : result.getAllErrors()) {
            logger.error(objectError.getDefaultMessage());
        }
        populateForm(model, resource, new ResourceParameterDto());
        return "resource/update";
    }
    persistedResource.setUri(resource.getUri());
    persistedResource.setTitle(resource.getTitle());
    persistedResource.setResourceType(resource.getResourceType());
    persistedResource.setLastHarvested(resource.getLastHarvested());
    persistedResource.setJobId(resource.getJobId());
    persistedResource.setLastHarvestedJobId(resource.getLastHarvestedJobId());
    persistedResource.setStatus(resource.getStatus());
    persistedResource.setStartTime(resource.getStartTime());
    persistedResource.setDuration(resource.getDuration());
    persistedResource.setExitCode(resource.getExitCode());
    persistedResource.setExitDescription(resource.getExitDescription());
    persistedResource.setRecordsRead(resource.getRecordsRead());
    persistedResource.setReadSkip(resource.getReadSkip());
    persistedResource.setProcessSkip(resource.getProcessSkip());
    persistedResource.setWriteSkip(resource.getWriteSkip());
    persistedResource.setWritten(resource.getWritten());
    persistedResource.setParameters(resource.getParameters());
    persistedResource.setScheduled(resource.getScheduled());
    persistedResource.setSchedulingPeriod(resource.getSchedulingPeriod());
    persistedResource.updateNextAvailableDate();
    getService().saveOrUpdate(persistedResource);
    String[] codes = new String[] { "resource.was.updated" };
    Object[] args = new Object[] { resource.getTitle() };
    DefaultMessageSourceResolvable message = new DefaultMessageSourceResolvable(codes, args);
    redirectAttributes.addFlashAttribute("info", message);
    return "redirect:/resource/{resourceId}";
}
Example 79
Project: grails-core-master  File: DataBindingUtils.java View source code
/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult if there were errors or null if it was successful
     *
     * @deprecated Use {@link #bindObjectToDomainInstance(PersistentEntity, Object, Object, List, List, String)} instead
     */
@SuppressWarnings("unchecked")
@Deprecated
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Example 80
Project: grails-master  File: DataBindingUtils.java View source code
/**
     * Binds the given source object to the given target object performing type conversion if necessary
     *
     * @param domain The GrailsDomainClass instance
     * @param object The object to bind to
     * @param source The source object
     * @param include The list of properties to include
     * @param exclude The list of properties to exclude
     * @param filter The prefix to filter by
     *
     * @see grails.core.GrailsDomainClass
     *
     * @return A BindingResult if there were errors or null if it was successful
     *
     * @deprecated Use {@link #bindObjectToDomainInstance(PersistentEntity, Object, Object, List, List, String)} instead
     */
@SuppressWarnings("unchecked")
@Deprecated
public static BindingResult bindObjectToDomainInstance(GrailsDomainClass domain, Object object, Object source, List include, List exclude, String filter) {
    BindingResult bindingResult = null;
    GrailsApplication grailsApplication = null;
    if (domain != null) {
        grailsApplication = domain.getApplication();
    }
    if (grailsApplication == null) {
        grailsApplication = Holders.findApplication();
    }
    try {
        final DataBindingSource bindingSource = createDataBindingSource(grailsApplication, object.getClass(), source);
        final DataBinder grailsWebDataBinder = getGrailsWebDataBinder(grailsApplication);
        grailsWebDataBinder.bind(object, bindingSource, filter, include, exclude);
    } catch (InvalidRequestBodyException e) {
        String messageCode = "invalidRequestBody";
        Class objectType = object.getClass();
        String defaultMessage = "An error occurred parsing the body of the request";
        String[] codes = getMessageCodes(messageCode, objectType);
        bindingResult = new BeanPropertyBindingResult(object, objectType.getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), codes, null, defaultMessage));
    } catch (Exception e) {
        bindingResult = new BeanPropertyBindingResult(object, object.getClass().getName());
        bindingResult.addError(new ObjectError(bindingResult.getObjectName(), e.getMessage()));
    }
    if (domain != null && bindingResult != null) {
        BindingResult newResult = new ValidationErrors(object);
        for (Object error : bindingResult.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                final boolean isBlank = BLANK.equals(fieldError.getRejectedValue());
                if (!isBlank) {
                    newResult.addError(fieldError);
                } else if (domain.hasPersistentProperty(fieldError.getField())) {
                    final boolean isOptional = domain.getPropertyByName(fieldError.getField()).isOptional();
                    if (!isOptional) {
                        newResult.addError(fieldError);
                    }
                } else {
                    newResult.addError(fieldError);
                }
            } else {
                newResult.addError((ObjectError) error);
            }
        }
        bindingResult = newResult;
    }
    MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(object.getClass());
    if (mc.hasProperty(object, "errors") != null && bindingResult != null) {
        ValidationErrors errors = new ValidationErrors(object);
        errors.addAllErrors(bindingResult);
        mc.setProperty(object, "errors", errors);
    }
    return bindingResult;
}
Example 81
Project: ORCID-Source-master  File: ManageProfileController.java View source code
@RequestMapping(value = "/addEmail.json", method = RequestMethod.POST)
@ResponseBody
public org.orcid.pojo.ajaxForm.Email addEmails(HttpServletRequest request, @RequestBody org.orcid.pojo.AddEmail email) {
    List<String> errors = new ArrayList<String>();
    ProfileEntity profile = profileEntityCacheManager.retrieve(getCurrentUserOrcid());
    // Check password
    if (orcidSecurityManager.isPasswordConfirmationRequired() && (email.getPassword() == null || !encryptionManager.hashMatches(email.getPassword(), profile.getEncryptedPassword()))) {
        errors.add(getMessage("check_password_modal.incorrect_password"));
    }
    // if blank
    if (PojoUtil.isEmpty(email.getValue())) {
        errors.add(getMessage("Email.personalInfoForm.email"));
    }
    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()) {
        errors.add(getMessage(oe.getCode(), email.getValue()));
    }
    if (errors.isEmpty()) {
        // clear errors
        email.setErrors(new ArrayList<String>());
        String currentUserOrcid = getCurrentUserOrcid();
        emailManager.addEmail(request, currentUserOrcid, email.toV2Email());
    } else {
        email.setErrors(errors);
    }
    return email;
}
Example 82
Project: udaLib-master  File: ValidationManager.java View source code
/**
	 * Genera, a partir de unos errores indicados como parámetros, un mapa en el
	 * cual cada elemento está formado del siguiente modo:<br>
	 * <br>
	 * - El key del elemento del mapa está formado por el nombre de la propiedad
	 * sobre la que se ha producido el error de la validación o por el
	 * identificador que se ha asignado a la validación.<br>
	 * <br>
	 * - El objeto asociado al key está formado por una lista de mensajes de
	 * error internacionalizados a partir del key de error.
	 * 
	 * @param errors
	 *            Conjunto de errores que se desean procesar.
	 * @return Mapa resultante que contiene los errores procesados.
	 */
public Map<String, List<String>> getErrorsAsMap(Errors errors) {
    // Se obtiene la locale actual que va a ser utilizada para realizar la
    // internacionalización de los mensajes de error.
    Locale locale = LocaleContextHolder.getLocale();
    // Mapa en el que se van a almacenar los errores 
    Map<String, List<String>> errorsMap = new HashMap<String, List<String>>();
    // Lista de errores que se han producido al realizarse el databinding
    List<? extends ObjectError> fieldErrors = errors.getAllErrors();
    // Se recorre cada error
    for (Iterator<? extends ObjectError> iterator = fieldErrors.iterator(); iterator.hasNext(); ) {
        ObjectError objectError = (ObjectError) iterator.next();
        String errorMessage;
        String key;
        // propiedad de un bean
        if (objectError instanceof FieldError) {
            FieldError fieldError = (FieldError) objectError;
            // En caso de que se trate de un FieldError se toma el nombre
            // del campo como el key que se utilizará en el elemento del
            // mapa.
            key = fieldError.getField();
            // Se trata de obtener el mensaje internacionalizado a partir del key del error.
            try {
                // En caso de existir se toma el mensaje internacionalizado como el texto de error a mostrar.
                errorMessage = messageSource.getMessage(fieldError.getDefaultMessage(), null, locale);
            } catch (NoSuchMessageException e) {
                errorMessage = fieldError.getCode();
            }
        } else {
            // En caso de que se trate de un FieldError se toma el code
            // del error como el key que se utilizará en el elemento del
            // mapa.
            key = objectError.getCode();
            // Se trata de obtener el mensaje internacionalizado a partir del key del error.
            try {
                // En caso de existir se toma el mensaje internacionalizado como el texto de error a mostrar.
                errorMessage = messageSource.getMessage(objectError.getDefaultMessage(), null, locale);
            } catch (NoSuchMessageException e) {
                errorMessage = objectError.getDefaultMessage();
            }
        }
        // Se comprrueba si error se ha insertado y a en el mapa
        if (errorsMap.containsKey(key)) {
            // En caso de existir se añade el mensaje de error en la lista de errores.
            errorsMap.get(key).add(errorMessage);
        } else {
            // En caso de no existir se genera un nuevo elemento en el mapa
            // con una lista de errores en la cual se añade el mensaje de
            // error.
            List<String> listaErrores = new ArrayList<String>();
            listaErrores.add(errorMessage);
            errorsMap.put(key, listaErrores);
        }
    }
    // Se devuelve el mapa de errores
    return errorsMap;
}
Example 83
Project: xDams-core-master  File: xDamsController.java View source code
@RequestMapping(value = "/upload/{archive}/execute", method = RequestMethod.POST)
public String executeUpload(UploadBean uploadBean, BindingResult result, @PathVariable String archive, ModelMap modelMap, @ModelAttribute("userBean") UserBean userBean, @ModelAttribute("confBean") ConfBean confBean, HttpServletRequest request, HttpServletResponse response) throws Exception {
    common(confBean, userBean, archive, modelMap, request, response);
    if (result.hasErrors()) {
        for (ObjectError error : result.getAllErrors()) {
            System.err.println("Error in uploading: " + error.getCode() + " - " + error.getDefaultMessage());
        }
        return "upload/uploadMenu";
    }
    UploadCommand uploadCommand = new UploadCommand(request.getParameterMap(), modelMap);
    uploadCommand.execute();
    modelMap.put("uploadResponse", uploadBean);
    System.out.println("----------------uploadbean---------------------------" + uploadBean);
    System.out.println("uploading file: " + uploadBean.getFiledata().getFileItem().getContentType());
    System.out.println("-------------------------------------------");
    return "upload/uploadResult";
}
Example 84
Project: miracle-framework-master  File: ApiValidateErrorHandler.java View source code
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Feedbacks processInvalidData(final MethodArgumentNotValidException ex) {
    Feedbacks result = new Feedbacks();
    for (ObjectError each : ex.getBindingResult().getAllErrors()) {
        result.addFeedback(new Feedback(each.getCodes()[0], each.getDefaultMessage()));
    }
    return result;
}
Example 85
Project: problem-spring-web-master  File: BaseBindingResultAdviceTrait.java View source code
default Violation createViolation(final ObjectError error) {
    final String fieldName = formatFieldName(error.getObjectName());
    return new Violation(fieldName, error.getDefaultMessage());
}
Example 86
Project: helium-master  File: MissatgesHelper.java View source code
public static void error(HttpServletRequest request, BindingResult result, String textValidacio) {
    for (ObjectError error : result.getAllErrors()) {
        String errorText = (error.getDefaultMessage() == null || error.getDefaultMessage().isEmpty()) ? textValidacio : error.getDefaultMessage();
        error(request, errorText);
    }
}
Example 87
Project: spring-cloud-stream-modules-master  File: HamcrestMatchers.java View source code
public static Matcher<ObjectError> fieldErrorWith(String argument0, String defaultMessage) {
    return new FieldValidationMatcher(argument0, defaultMessage);
}
Example 88
Project: alf.io-master  File: Result.java View source code
public static <T> Result<T> validationError(List<ObjectError> errors) {
    return new Result<>(ResultStatus.VALIDATION_ERROR, null, errors.stream().map(ErrorDescriptor::fromObjectError).collect(Collectors.toList()));
}
Example 89
Project: comsat-master  File: MessageController.java View source code
private Map<String, ObjectError> getFieldErrors(BindingResult result) throws InterruptedException, SuspendExecution {
    Fiber.sleep(10);
    Map<String, ObjectError> map = new HashMap<String, ObjectError>();
    for (FieldError error : result.getFieldErrors()) {
        map.put(error.getField(), error);
    }
    return map;
}
Example 90
Project: mycar-master  File: BindingResultUtils.java View source code
public static List<String> getGlobalErrors(MessageSource messageSource, BindingResult bindingResult, Locale locale) {
    List<String> globalErrors = new ArrayList<String>();
    for (ObjectError oe : bindingResult.getGlobalErrors()) {
        String message = getMessage(messageSource, oe, locale);
        globalErrors.add(message);
    }
    return globalErrors;
}
Example 91
Project: obiba-commons-master  File: ValidationRuntimeException.java View source code
/**
   * Get the object errors in a flat list.
   *
   * @return
   */
public List<ObjectError> getAllObjectErrors() {
    List<ObjectError> allErrors = new ArrayList<ObjectError>();
    if (errors != null) {
        for (Errors err : errors) {
            for (ObjectError objectError : err.getAllErrors()) {
                allErrors.add(objectError);
            }
        }
    }
    return allErrors;
}
Example 92
Project: androGister-master  File: UserService.java View source code
/**
     * @see http 
     *      ://fcamblor.wordpress.com/2012/05/21/valider-ses-pojos-avec-bean-
     *      validation-spring-mvc-et-jquery/ Fait troublant : la validation est
     *      un rare cas où Spring n’a pas une gestion homogène des exceptions !
     *      Si vous validez un body content (annotation @RequestBody), vous
     *      obtiendrez une MethodArgumentNotValidException, à contrario, si vous
     *      validez des query parameters (pas d’annotation @RequestBody), vous
     *      obtiendrez une BindException. Ces 2 exceptions encapsulent toutefois
     *      un BindingResult, contenant les erreurs de validation.
     * 
     * @param exception
     * @return
     */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.PRECONDITION_FAILED)
@ResponseBody
public List<ObjectError> handleValidationFailure(MethodArgumentNotValidException exception) {
    return exception.getBindingResult().getAllErrors();
}
Example 93
Project: saos-master  File: ControllersEntityExceptionHandler.java View source code
private boolean causedByFieldError(BindException ex) {
    if (!ex.getAllErrors().isEmpty()) {
        ObjectError error = ex.getAllErrors().get(0);
        return error instanceof FieldError;
    } else {
        return false;
    }
}
Example 94
Project: jeffaschenk-commons-master  File: ErrorsImpl.java View source code
/**
     * Get all errors including both Field and Global Errors
     * <p/>
     * return List of all Field and Global Errors
     *
     * @return  {@link java.util.List} object.
     */
public List<ObjectError> getAllErrors() {
    List<ObjectError> objectErrorsList = new ArrayList<ObjectError>();
    objectErrorsList.addAll(this.fieldErrors);
    objectErrorsList.addAll(this.globalErrors);
    return objectErrorsList;
}
Example 95
Project: uaa-master  File: IdentityZoneEndpoints.java View source code
private String getErrorMessages(Errors errors) {
    List<String> messages = new ArrayList<>();
    for (ObjectError error : errors.getAllErrors()) {
        messages.add(messageSource.getMessage(error, Locale.getDefault()));
    }
    return String.join("\r\n", messages);
}