Example usage for org.springframework.validation BindingResult getFieldErrors

List of usage examples for org.springframework.validation BindingResult getFieldErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getFieldErrors.

Prototype

List<FieldError> getFieldErrors();

Source Link

Document

Get all errors associated with a field.

Usage

From source file:org.broadleafcommerce.openadmin.web.controller.entity.AdminBasicEntityController.java

/**
 * 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
 *///from  w w  w . jav  a  2s  .c  o m
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;
}

From source file:org.egov.api.controller.RestEventController.java

@PostMapping(path = "/event/interested", produces = APPLICATION_JSON_VALUE)
public ResponseEntity<String> saveUserEvent(@Valid @RequestBody UserEventRequest userEventRequest,
        BindingResult errors) {
    ApiResponse res = ApiResponse.newInstance();

    if (errors.hasErrors()) {
        String errorMessage = EMPTY;
        for (FieldError fieldError : errors.getFieldErrors())
            errorMessage = errorMessage.concat(
                    fieldError.getField().concat(" ").concat(fieldError.getDefaultMessage()).concat(" <br>"));
        return res.error(errorMessage);
    }//from   ww w  .j  a va 2 s. co  m

    UserEvent userEvent = userEventService.saveUserEvent(userEventRequest.getUserid(),
            userEventRequest.getEventid());
    if (userEvent == null)
        return res.error(getMessage("user.event.already.exists"));
    else {
        Long interestedCount = userEventService.countUsereventByEventId(userEvent.getEvent().getId());
        return res.setDataAdapter(new InterestedCountAdapter()).success(interestedCount);
    }
}

From source file:org.egov.api.controller.RestPushBoxController.java

@PostMapping(path = UPDATE_USER_TOKEN, consumes = APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<String> updateToken(@Valid @RequestBody UserTokenRequest userTokenRequest,
        BindingResult errors) {
    ApiResponse res = ApiResponse.newInstance();

    if (errors.hasErrors()) {
        String errorMessage = EMPTY;
        for (FieldError fieldError : errors.getFieldErrors())
            errorMessage = errorMessage.concat(
                    fieldError.getField().concat(" ").concat(fieldError.getDefaultMessage()).concat(" <br>"));
        return res.error(errorMessage);
    }/*w w w  . j  a v a  2 s.c  o  m*/

    UserFcmDevice responseObject = notificationService.saveUserDevice(userTokenRequest);
    return res.setDataAdapter(new UserDeviceAdapter()).success(responseObject,
            getMessage("msg.userdevice.update.success"));
}

From source file:org.egov.wtms.web.controller.application.ChangeOfUseController.java

@RequestMapping(value = "/changeOfUse/changeOfUse-create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute final WaterConnectionDetails changeOfUse,
        final BindingResult resultBinder, final RedirectAttributes redirectAttributes,
        final HttpServletRequest request, final Model model, @RequestParam final String workFlowAction,
        final BindingResult errors) {
    final Boolean isCSCOperator = waterTaxUtils.isCSCoperator(securityUtils.getCurrentUser());
    final Boolean citizenPortalUser = waterTaxUtils.isCitizenPortalUser(securityUtils.getCurrentUser());
    final Boolean loggedInMeesevaUser = waterTaxUtils.isMeesevaUser(securityUtils.getCurrentUser());
    final Boolean isAnonymousUser = waterTaxUtils.isAnonymousUser(securityUtils.getCurrentUser());
    model.addAttribute("isAnonymousUser", isAnonymousUser);
    if (loggedInMeesevaUser && request.getParameter("meesevaApplicationNumber") != null)
        changeOfUse.setMeesevaApplicationNumber(request.getParameter("meesevaApplicationNumber"));
    model.addAttribute("citizenPortalUser", citizenPortalUser);
    if (!isCSCOperator && !citizenPortalUser && !loggedInMeesevaUser && !isAnonymousUser) {
        final Boolean isJuniorAsstOrSeniorAsst = waterTaxUtils
                .isLoggedInUserJuniorOrSeniorAssistant(securityUtils.getCurrentUser().getId());
        if (!isJuniorAsstOrSeniorAsst)
            throw new ValidationException("err.creator.application");
    }/* w  w  w . jav  a2  s . com*/
    final List<ApplicationDocuments> applicationDocs = new ArrayList<>();
    final WaterConnectionDetails connectionUnderChange = waterConnectionDetailsService
            .findByConsumerCodeAndConnectionStatus(changeOfUse.getConnection().getConsumerCode(),
                    ConnectionStatus.ACTIVE);
    final WaterConnectionDetails parent = waterConnectionDetailsService.getParentConnectionDetails(
            connectionUnderChange.getConnection().getPropertyIdentifier(), ConnectionStatus.ACTIVE);
    String message = "";
    if (parent != null)
        message = changeOfUseService.validateChangeOfUseConnection(parent);
    String consumerCode = "";
    if (!message.isEmpty() && !"".equals(message)) {
        if (changeOfUse.getConnection().getParentConnection() != null)
            consumerCode = changeOfUse.getConnection().getParentConnection().getConsumerCode();
        else
            consumerCode = changeOfUse.getConnection().getConsumerCode();
        return "redirect:/application/changeOfUse/" + consumerCode;
    }
    int i = 0;
    if (!changeOfUse.getApplicationDocs().isEmpty())
        for (final ApplicationDocuments applicationDocument : changeOfUse.getApplicationDocs()) {
            if (applicationDocument.getDocumentNumber() == null
                    && applicationDocument.getDocumentDate() != null) {
                final String fieldError = "applicationDocs[" + i + "].documentNumber";
                resultBinder.rejectValue(fieldError, "documentNumber.required");
            }
            if (applicationDocument.getDocumentNumber() != null
                    && applicationDocument.getDocumentDate() == null) {
                final String fieldError = "applicationDocs[" + i + "].documentDate";
                resultBinder.rejectValue(fieldError, "documentDate.required");
            } else if (connectionDetailService.validApplicationDocument(applicationDocument))
                applicationDocs.add(applicationDocument);
            i++;
        }
    if (ConnectionType.NON_METERED.equals(changeOfUse.getConnectionType()))
        waterConnectionDetailsService.validateWaterRateAndDonationHeader(changeOfUse);
    if (resultBinder.hasErrors()) {
        final WaterConnectionDetails parentConnectionDetails = waterConnectionDetailsService
                .getActiveConnectionDetailsByConnection(changeOfUse.getConnection());
        loadBasicData(model, parentConnectionDetails, changeOfUse, changeOfUse,
                changeOfUse.getMeesevaApplicationNumber());
        final WorkflowContainer workflowContainer = new WorkflowContainer();
        workflowContainer.setAdditionalRule(changeOfUse.getApplicationType().getCode());
        prepareWorkflow(model, changeOfUse, workflowContainer);
        model.addAttribute("approvalPosOnValidate", request.getParameter(APPROVAL_POSITION));
        model.addAttribute("additionalRule", changeOfUse.getApplicationType().getCode());
        model.addAttribute("validationmessage", resultBinder.getFieldErrors().get(0).getField() + " = "
                + resultBinder.getFieldErrors().get(0).getDefaultMessage());
        model.addAttribute("stateType", changeOfUse.getClass().getSimpleName());
        model.addAttribute("currentUser", waterTaxUtils.getCurrentUserRole(securityUtils.getCurrentUser()));

        return CHANGEOFUSE_FORM;

    }
    if (changeOfUse.getState() == null)
        changeOfUse.setStatus(waterTaxUtils.getStatusByCodeAndModuleType(
                WaterTaxConstants.APPLICATION_STATUS_CREATED, WaterTaxConstants.MODULETYPE));

    changeOfUse.getApplicationDocs().clear();
    changeOfUse.setApplicationDocs(applicationDocs);

    processAndStoreApplicationDocuments(changeOfUse);

    Long approvalPosition = 0l;
    String approvalComent = "";

    if (request.getParameter("approvalComent") != null)
        approvalComent = request.getParameter("approvalComent");

    if (request.getParameter(APPROVAL_POSITION) != null && !request.getParameter(APPROVAL_POSITION).isEmpty())
        approvalPosition = Long.valueOf(request.getParameter(APPROVAL_POSITION));
    final Boolean applicationByOthers = waterTaxUtils.getCurrentUserRole(securityUtils.getCurrentUser());

    if (applicationByOthers != null && applicationByOthers.equals(true) || citizenPortalUser
            || isAnonymousUser) {
        final Position userPosition = waterTaxUtils
                .getZonalLevelClerkForLoggedInUser(changeOfUse.getConnection().getPropertyIdentifier());
        if (userPosition != null)
            approvalPosition = userPosition.getId();
        else {
            final WaterConnectionDetails parentConnectionDetails = waterConnectionDetailsService
                    .getActiveConnectionDetailsByConnection(changeOfUse.getConnection());
            loadBasicData(model, parentConnectionDetails, changeOfUse, changeOfUse, null);
            final WorkflowContainer workflowContainer = new WorkflowContainer();
            workflowContainer.setAdditionalRule(changeOfUse.getApplicationType().getCode());
            prepareWorkflow(model, changeOfUse, workflowContainer);
            model.addAttribute("additionalRule", changeOfUse.getApplicationType().getCode());
            model.addAttribute("stateType", changeOfUse.getClass().getSimpleName());
            model.addAttribute("currentUser", waterTaxUtils.getCurrentUserRole(securityUtils.getCurrentUser()));
            errors.rejectValue("connection.propertyIdentifier", "err.validate.connection.user.mapping",
                    "err.validate.connection.user.mapping");
            model.addAttribute("noJAORSAMessage", "No JA/SA exists to forward the application.");
            return CHANGEOFUSE_FORM;
        }
    }
    changeOfUse.setApplicationDate(new Date());
    if (isAnonymousUser)
        changeOfUse.setSource(ONLINE);
    else if (isCSCOperator)
        changeOfUse.setSource(CSC);
    else if (citizenPortalUser
            && (changeOfUse.getSource() == null || StringUtils.isBlank(changeOfUse.getSource().toString())))
        changeOfUse.setSource(waterTaxUtils.setSourceOfConnection(securityUtils.getCurrentUser()));
    else if (loggedInMeesevaUser) {
        changeOfUse.setSource(MEESEVA);
        if (changeOfUse.getMeesevaApplicationNumber() != null)
            changeOfUse.setApplicationNumber(changeOfUse.getMeesevaApplicationNumber());
    } else
        changeOfUse.setSource(Source.SYSTEM);
    changeOfUseService.createChangeOfUseApplication(changeOfUse, approvalPosition, approvalComent,
            changeOfUse.getApplicationType().getCode(), workFlowAction);

    if (loggedInMeesevaUser)
        return "redirect:/application/generate-meesevareceipt?transactionServiceNumber="
                + changeOfUse.getApplicationNumber();
    else
        return "redirect:/application/citizeenAcknowledgement?pathVars=" + changeOfUse.getApplicationNumber();
}

From source file:org.opentestsystem.delivery.testreg.rest.FileUploadDataController.java

@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/saveEntity/{fileId}", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@Secured({ "ROLE_Accommodations Upload", "ROLE_Student Upload", "ROLE_Entity Upload",
        "ROLE_StudentGroup Upload", "ROLE_User Upload", "ROLE_ExplicitEligibility Upload" })
@ResponseBody//from   ww  w . j a  v  a2s. c om
public List<FileUploadSummary> saveEntity(@ModelAttribute("fileId") final String fileId,
        final BindingResult result, final HttpServletResponse response) throws Exception {

    final long start = System.currentTimeMillis();
    final GridFSDBFile file = getGridFSDBFile(fileId);
    this.metricClient.sendPerformanceMetricToMna(buildMetricMessage(fileId, "saveEntity->getGridFSDBFile"),
            System.currentTimeMillis() - start);

    // reset our start marker...
    long startMarker = System.currentTimeMillis();
    final List<FileUploadSummary> summaryResponse = new ArrayList<>();
    //based on FormatType save procedure for DESIGNATEDSUPPORTSANDACCOMMODATIONS is changed
    if (retrieveFormatTypeFromFileMetadata(file)
            .equals(FormatType.DESIGNATEDSUPPORTSANDACCOMMODATIONS.name())) {
        final FileUploadSummary summaryCount = extractAccommodationData(file);
        summaryResponse.add(summaryCount);
    } else {
        final ParserResult<Map<FormatType, List<TestRegistrationBase>>> parsedEntities = extractFile(file);
        // EDIT: validation during the save step is being skipped due to very low likelihood underlying reference data would be changed between validation step & save step
        // validate(fileId, result, response); // validate the file
        // this.metricClient.sendPerformanceMetricToMna("saveEntity->validate", System.currentTimeMillis() - startMarker);

        for (final Map.Entry<FormatType, List<TestRegistrationBase>> mapEntry : parsedEntities.getParsedObject()
                .entrySet()) {

            final FormatType type = mapEntry.getKey();
            final List<TestRegistrationBase> testRegistrationBaseList = mapEntry.getValue();
            this.metricClient.sendPerformanceMetricToMna(
                    buildMetricMessage(fileId, "saveEntity->processing sb11Entity: type=" + type + "", true),
                    testRegistrationBaseList.size());

            // Filter entities that needed to be saved.
            startMarker = System.currentTimeMillis();
            filterErrorRecords(type, parsedEntities.getIgnoredRowNumbers(), testRegistrationBaseList,
                    result.getFieldErrors());
            this.metricClient.sendPerformanceMetricToMna(
                    buildMetricMessage(fileId, "saveEntity->filterErrorRecords"),
                    System.currentTimeMillis() - startMarker);

            // reset our start marker...
            startMarker = System.currentTimeMillis();
            this.sb11DependencyResolverInvoker.resolveDependency(testRegistrationBaseList); // Resolve dependencies if any
            this.metricClient.sendPerformanceMetricToMna(
                    buildMetricMessage(fileId, "saveEntity->resolveDependency"),
                    System.currentTimeMillis() - startMarker);

            // reset our start marker...
            startMarker = System.currentTimeMillis();
            final FileUploadSummary summaryCount = this.fileUploadUtils
                    .processGroupEntities(testRegistrationBaseList, this.entityService);
            this.metricClient.sendPerformanceMetricToMna(
                    buildMetricMessage(fileId, "saveEntity->processGroupEntities"),
                    System.currentTimeMillis() - startMarker);

            summaryCount.setFormatType(type);
            summaryResponse.add(summaryCount);
        }

    }

    this.metricClient.sendPerformanceMetricToMna(buildMetricMessage(fileId, "saveEntity->total time"),
            System.currentTimeMillis() - start);

    return summaryResponse;
}

From source file:pl.hycom.pip.messanger.controller.GreetingController.java

@PostMapping("/admin/greeting")
public String addGreeting(@Valid Greeting greeting, BindingResult bindingResult, Model model) {
    try {/*from  w  ww.j a va2 s .  c  om*/
        if (!greetingService.isValidLocale(greeting.getLocale())) {
            log.error("Not supported locale[" + greeting.getLocale() + "]");
            addError(bindingResult, "greeting.locale.empty");
        }

        if (bindingResult.hasErrors()) {
            prepareModel(model, greeting);
            log.error("Greeting validation errors: " + bindingResult.getAllErrors());
            return VIEW_GREETINGS;
        }

        List<com.github.messenger4j.profile.Greeting> greetings = getGreetingsWithDefaultLocale();
        com.github.messenger4j.profile.Greeting profileGreeting = new com.github.messenger4j.profile.Greeting(
                greeting.getText(), greeting.getLocale());
        greetings.add(profileGreeting);
        profileClient.setupWelcomeMessages(greetings);
        log.info("Greeting text correctly updated");
    } catch (MessengerApiException | MessengerIOException e) {
        log.error("Error during changing greeting message", e);
        addError(bindingResult, "unexpectedError");
        prepareModel(model, greeting);
        model.addAttribute("errors", bindingResult.getFieldErrors());
        return VIEW_GREETINGS;
    }

    return REDIRECT_ADMIN_GREETINGS;
}