Example usage for org.springframework.validation FieldError getField

List of usage examples for org.springframework.validation FieldError getField

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getField.

Prototype

public String getField() 

Source Link

Document

Return the affected field of the object.

Usage

From source file:com.zb.app.web.controller.login.LoginController.java

/**
 * ,???,?/*from   w  w  w .j a  v a2 s  .co m*/
 * 
 * @param travelCompanyVO
 * @param travelMemberVO
 * @return
 */
@RequestMapping(value = "/doRegister.htm")
@TokenPolicy(remove = true, data = ",token,??!")
public ModelAndView doRegister(@Valid TravelCompanyVO travelCompanyVO, @Valid TravelMemberVO travelMemberVO,
        BindingResult bindingResult, ModelAndView mav) {
    Map<String, Object> model = new HashMap<String, Object>();
    if (bindingResult.hasErrors()) {
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            model.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return createErrorJsonMav("!", model);
    }

    // ?
    TravelCompanyDO travelCompanyDO = new TravelCompanyDO();
    BeanUtils.copyProperties(travelCompanyDO, travelCompanyVO);
    travelCompanyDO.setcState(0);
    travelCompanyDO.setcSpell(PinyinParser.converterToFirstSpell(travelCompanyDO.getcName()));
    companyService.insert(travelCompanyDO);

    // 
    TravelMemberDO travelMemberDO = new TravelMemberDO();
    BeanUtils.copyProperties(travelMemberDO, travelMemberVO);
    travelMemberDO.setmState(0);
    travelMemberDO.setmPassword(EncryptBuilder.getInstance().encrypt(travelMemberVO.getmPassword()));
    travelMemberDO.setcId(travelCompanyDO.getcId());
    travelMemberDO.setmUserName(StringUtils.lowerCase(travelMemberVO.getmUserName()));
    travelMemberDO.setmType(MemberTypeEnum.SUPERADMIN.getValue());
    memberService.insert(travelMemberDO);
    Map<String, String> map = new HashMap<String, String>();
    map.put("cName", travelCompanyDO.getcName());
    map.put("mUserName", travelMemberDO.getmUserName());
    map.put("mEmail", travelMemberDO.getmEmail());
    return createSuccessJsonMav("?!", map);
}

From source file:de.hybris.platform.acceleratorservices.web.payment.controllers.SilentOrderPostMockController.java

@RequestMapping(value = "/process", method = RequestMethod.POST)
public String doValidateAndPost(@Valid final SopPaymentDetailsForm form, final BindingResult bindingResult,
        final HttpServletRequest request, final Model model) {
    final Map<String, String> params = cloneRequestParameters(request);

    // Remove values that we must not post back to the caller
    params.remove("card_cvNumber");

    getSopPaymentDetailsValidator().validate(form, bindingResult);

    if (bindingResult.hasErrors()) {
        // Validation errors
        params.put("decision", "REJECT");
        params.put("reasonCode", "102");
        params.put("decision_publicSignature", getMockedPublicDigest("REJECT" + "102"));

        // Remove card number on validation error
        params.remove("card_accountNumber");

        final List<String> missingFields = new ArrayList<String>();
        final List<String> invalidFields = new ArrayList<String>();

        for (final ObjectError objectError : bindingResult.getAllErrors()) {
            if (objectError instanceof FieldError) {
                final FieldError fieldError = (FieldError) objectError;

                if (fieldError.getRejectedValue() == null || "".equals(fieldError.getRejectedValue())) {
                    missingFields.add(fieldError.getField());
                } else {
                    invalidFields.add(fieldError.getField());
                }//from  ww w  .  j a va  2 s .c o m
            }
        }

        for (int i = 0; i < missingFields.size(); i++) {
            params.put("MissingField" + i, missingFields.get(i));
        }
        for (int i = 0; i < invalidFields.size(); i++) {
            params.put("InvalidField" + i, invalidFields.get(i));
        }
    } else {
        // No validation errors create subscription ID

        final String subscriptionId = UUID.randomUUID().toString();
        params.put("ccAuthReply_cvCode", "M");
        params.put("paySubscriptionCreateReply_subscriptionID", subscriptionId);
        params.put("paySubscriptionCreateReply_subscriptionIDPublicSignature",
                getMockedPublicDigest(subscriptionId));

        processTransactionDecision(request, null, params, false);

        //Mask the card number in the response
        final String endPortion = form.getCard_accountNumber().trim()
                .substring(form.getCard_accountNumber().length() - 4);
        final String maskedCardNumber = "************" + endPortion;

        params.put("card_accountNumber", maskedCardNumber);
    }

    model.addAttribute("postParams", params);
    model.addAttribute("postUrl", params.get("orderPage_receiptResponseURL"));

    return SOP_REDIRECT_POST_PAGE;
}

From source file:de.hybris.platform.sap.productconfig.frontend.controllers.AbstractProductConfigController.java

protected Map<String, FieldError> handleValidationErrorsBeforeUpdate(final ConfigurationData configData,
        final BindingResult bindingResult) {
    Map<String, FieldError> userInputToRestore;
    final int capacity = (int) (bindingResult.getErrorCount() / 0.75) + 1;
    userInputToRestore = new HashMap(capacity);
    for (final FieldError error : bindingResult.getFieldErrors()) {
        final String fieldPath = error.getField();
        final PathExtractor extractor = new PathExtractor(fieldPath);
        final int groupIndex = extractor.getGroupIndex();
        final int csticIndex = extractor.getCsticsIndex();
        UiGroupData group = configData.getGroups().get(groupIndex);
        for (int i = 0; i < extractor.getSubGroupCount(); i++) {
            group = group.getSubGroups().get(extractor.getSubGroupIndex(i));
        }//from w  w w.j a  v a  2  s. c  om
        final CsticData cstic = group.getCstics().get(csticIndex);
        userInputToRestore.put(cstic.getKey(), error);
        cstic.setValue(cstic.getLastValidValue());
    }
    return userInputToRestore;
}

From source file:fi.hsl.parkandride.front.ExceptionHandlers.java

@ExceptionHandler(BindException.class)
public ResponseEntity<Map<String, Object>> bindException(HttpServletRequest request, BindException ex) {
    List<Violation> violations = new ArrayList<>();
    for (FieldError fieldError : ex.getFieldErrors()) {
        violations.add(/*ww w.  j  a v  a2  s .  c om*/
                new Violation(fieldError.getCode(), fieldError.getField(), fieldError.getDefaultMessage()));
    }
    return handleError(request, BAD_REQUEST, ex, "Invalid request parameters", violations);
}

From source file:gov.nih.nci.cabig.caaers.web.utils.WebUtils.java

public static void populateErrorFieldNames(Map<String, Boolean> map, Errors errors) {
    logger.debug("F: populateErrorFieldNames(Map map, Errors errors)");
    if (map == null || errors == null || errors.getFieldErrors() == null || errors.getFieldErrors().size() == 0)
        return;/*from   ww w.j  av a 2s . c  om*/

    Iterator<FieldError> it = errors.getFieldErrors().iterator();
    while (it.hasNext()) {
        FieldError fe = it.next();
        String subName = fe.getField().substring(0, fe.getField().indexOf("].") + 1).toString();
        map.put(subName, Boolean.TRUE);
        logger.debug("FE: " + fe.getField());
    }
}

From source file:gt.org.ms.api.global.GlobalExceptionHandler.java

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {

    List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
    List<ValidationError> errors = new ArrayList<ValidationError>();

    for (FieldError fieldError : fieldErrors) {
        errors.add(/*from w w w.  j a  v a2  s  . c o  m*/
                new ValidationError(fieldError.getField().replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase(),
                        translateValidationMessage(fieldError.getDefaultMessage())));
    }

    ValidationException ve = new ValidationException(errors);
    LOG.info("ValidationException", ve);
    return handleException(ve);
}

From source file:jp.terasoluna.batch.tutorial.sample003.CustomValidationErrorHandler.java

public ValidateErrorStatus handleValidationError(DataValueObject dataValueObject, Errors errors) {

    if (log.isWarnEnabled()) {
        List<FieldError> fieldErrorList = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrorList) {
            log.warn(fieldError.getField() + "tB?[hK?{`FbNG?[?");
        }//  ww w  . j  a  v a 2s . co m
    }

    // G?[f?[^?A???s
    return ValidateErrorStatus.SKIP;
}

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 .j av a 2s  . com
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.broadleafcommerce.openadmin.web.processor.ErrorsProcessor.java

@Override
protected ProcessorResult processAttribute(Arguments arguments, Element element, String attributeName) {
    String attributeValue = element.getAttributeValue(attributeName);

    BindStatus bindStatus = FieldUtils.getBindStatus(arguments.getConfiguration(), arguments, attributeValue);

    if (bindStatus.isError()) {
        EntityForm form = (EntityForm) ((BindingResult) bindStatus.getErrors()).getTarget();

        // Map of tab name -> (Map field Name -> list of error messages)
        Map<String, Map<String, List<String>>> result = new HashMap<String, Map<String, List<String>>>();
        for (FieldError err : bindStatus.getErrors().getFieldErrors()) {
            //attempt to look up which tab the field error is on. If it can't be found, just use
            //the default tab for the group
            String tabName = EntityForm.DEFAULT_TAB_NAME;
            Tab tab = form.findTabForField(err.getField());
            if (tab != null) {
                tabName = tab.getTitle();
            }//from  ww  w. j  a  va 2s  .com

            Map<String, List<String>> tabErrors = result.get(tabName);
            if (tabErrors == null) {
                tabErrors = new HashMap<String, List<String>>();
                result.put(tabName, tabErrors);
            }
            if (err.getField().contains(DynamicEntityFormInfo.FIELD_SEPARATOR)) {
                //at this point the field name actually occurs within some array syntax
                String fieldName = err.getField().substring(err.getField().indexOf('[') + 1,
                        err.getField().lastIndexOf(']'));
                String[] fieldInfo = fieldName.split("\\" + DynamicEntityFormInfo.FIELD_SEPARATOR);
                Field formField = form.getDynamicForm(fieldInfo[0]).getFields().get(fieldName);

                if (formField != null) {
                    addFieldError(formField.getFriendlyName(), err.getCode(), tabErrors);
                } else {
                    LOG.warn("Could not find field " + fieldName + " within the dynamic form " + fieldInfo[0]);
                    addFieldError(fieldName, err.getCode(), tabErrors);
                }
            } else {
                Field formField = form.findField(err.getField());
                if (formField != null) {
                    addFieldError(formField.getFriendlyName(), err.getCode(), tabErrors);
                } else {
                    LOG.warn("Could not field field " + err.getField() + " within the main form");
                    addFieldError(err.getField(), err.getCode(), tabErrors);
                }
            }
        }

        String translatedGeneralTab = GENERAL_ERRORS_TAB_KEY;
        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
        if (context != null && context.getMessageSource() != null) {
            translatedGeneralTab = context.getMessageSource().getMessage(translatedGeneralTab, null,
                    translatedGeneralTab, context.getJavaLocale());
        }

        for (ObjectError err : bindStatus.getErrors().getGlobalErrors()) {
            Map<String, List<String>> tabErrors = result.get(GENERAL_ERRORS_TAB_KEY);
            if (tabErrors == null) {
                tabErrors = new HashMap<String, List<String>>();
                result.put(translatedGeneralTab, tabErrors);
            }
            addFieldError(GENERAL_ERROR_FIELD_KEY, err.getCode(), tabErrors);
        }

        Map<String, Object> localVariables = new HashMap<String, Object>();
        localVariables.put("tabErrors", result);
        return ProcessorResult.setLocalVariables(localVariables);
    }
    return ProcessorResult.OK;

}

From source file:org.cloudifysource.cloudformation.converter.CloudifyPrivateEc2ConverterController.java

/**
 * Handle PrivateEc2RestValidationException.
 * /*from   www.j  av a 2  s . c  o  m*/
 * @param response
 *            The http servlet response
 * @param e
 *            The handled exception.
 * @throws IOException
 *             When a problem occrus.
 */
@ExceptionHandler(PrivateEc2RestValidationException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public void handleValidationException(final HttpServletResponse response,
        final PrivateEc2RestValidationException e) throws IOException {
    final StringBuilder sb = new StringBuilder("Missing parameters: ");
    for (FieldError f : e.getBindingResult().getFieldErrors()) {
        sb.append(f.getField()).append(", ");
    }
    sb.setLength(sb.length() - 2);
    this.returnErrorMessage(response, sb.toString());
}